-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbleamd.go
More file actions
1501 lines (1286 loc) · 39.2 KB
/
bleamd.go
File metadata and controls
1501 lines (1286 loc) · 39.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"github.com/MichaelMure/go-term-markdown"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/mattn/go-isatty"
"github.com/pkg/errors"
)
const padding = 4
func main() {
if len(os.Args) >= 2 && (os.Args[1] == "version" || os.Args[1] == "--version") {
printVersion()
return
}
if len(os.Args) >= 2 && (os.Args[1] == "--init-config") {
theme := "default"
if len(os.Args) >= 3 {
theme = os.Args[2]
}
initConfig(theme)
return
}
if len(os.Args) >= 2 && (os.Args[1] == "--config-path") {
fmt.Printf("Config file location: %s\n", getConfigPath())
return
}
var content []byte
switch len(os.Args) {
case 1:
if isatty.IsTerminal(os.Stdin.Fd()) {
exitError(fmt.Errorf("usage: %s <file.md>", os.Args[0]))
}
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
exitError(errors.Wrap(err, "error while reading STDIN"))
}
content = data
case 2:
data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
exitError(errors.Wrap(err, "error while reading file"))
}
err = os.Chdir(path.Dir(os.Args[1]))
if err != nil {
exitError(err)
}
content = data
default:
exitError(fmt.Errorf("only one file is supported"))
}
model := newModel(content)
// Use default mouse mode (button clicks only) to allow text selection
// WithMouseAllMotion() would capture all mouse events and prevent selection
p := tea.NewProgram(model, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
exitError(errors.Wrap(err, "error starting the interactive UI"))
}
}
func exitError(err error) {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
func initConfig(theme string) {
var config *Config
switch theme {
case "onedark", "one-dark":
config = OneDarkConfig()
case "default":
config = DefaultConfig()
default:
fmt.Printf("Unknown theme: %s\n", theme)
fmt.Println("Available themes: default, onedark")
os.Exit(1)
}
configPath := getConfigPath()
// Check if config already exists
if _, err := os.Stat(configPath); err == nil {
fmt.Printf("Config file already exists at: %s\n", configPath)
fmt.Println("To regenerate, please delete the existing file first.")
return
}
// Save the config
if err := config.Save(); err != nil {
exitError(fmt.Errorf("failed to create config file: %w", err))
}
fmt.Printf("Created %s theme config file at: %s\n", theme, configPath)
fmt.Println("You can now edit this file to customize colors and keybindings.")
fmt.Println("\nExample color values:")
fmt.Println(" \"#ff0000\" - Red")
fmt.Println(" \"#00ff00\" - Green")
fmt.Println(" \"#0000ff\" - Blue")
fmt.Println(" \"#ffff00\" - Yellow")
fmt.Println(" \"#ff00ff\" - Magenta")
fmt.Println(" \"#00ffff\" - Cyan")
}
type model struct {
content []byte
raw string
width int
height int
xOffset int
yOffset int
lines int
renderedContent []byte
// search state
search *SearchState
searchActive bool
searchInput string
// help state
helpActive bool
// configuration
config *Config
// hyperlink tracking for hover
linkPositions []linkPosition
hoveredURL string
// styles
styles struct {
helpBox lipgloss.Style
searchBox lipgloss.Style
statusBar lipgloss.Style
}
// mode tracking for status bar
mode string
// mouse capture mode - toggleable for text selection
mouseCaptureEnabled bool
}
func newModel(content []byte) model {
config, err := LoadConfig()
if err != nil {
config = DefaultConfig()
}
m := model{
content: content,
raw: string(content),
width: 80, // Default width, will be updated on first WindowSizeMsg
search: NewSearchState(config),
config: config,
mode: "reading",
mouseCaptureEnabled: true, // Start with mouse capture enabled for hover
}
// Initial render with default width
m.renderedContent = m.render()
// Count lines
lineCount := 0
for _, b := range m.renderedContent {
if b == '\n' {
lineCount++
}
}
m.lines = lineCount
// Initialize styles
// Initialize help box style with configurable border color
helpBoxStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
Padding(1, 2)
if config.Colors.HelpBoxBorder != "" {
if colorCode, err := hexToANSI(config.Colors.HelpBoxBorder); err == nil {
helpBoxStyle = helpBoxStyle.BorderForeground(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
}
m.styles.helpBox = helpBoxStyle
// Initialize search box style with configurable border color
searchBoxStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
Padding(0, 1)
if config.Colors.SearchBoxBorder != "" {
if colorCode, err := hexToANSI(config.Colors.SearchBoxBorder); err == nil {
searchBoxStyle = searchBoxStyle.BorderForeground(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
}
m.styles.searchBox = searchBoxStyle
m.styles.statusBar = lipgloss.NewStyle().
Foreground(lipgloss.Color("241")).
MarginTop(1)
return m
}
func (m model) Init() tea.Cmd {
// Start with full mouse tracking enabled (for hover effects)
// User can press 'm' to toggle and enable text selection
return tea.EnableMouseAllMotion
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
// Re-render content with new width
if len(m.raw) > 0 {
m.renderedContent = m.render()
// Count lines
lineCount := 0
for _, b := range m.renderedContent {
if b == '\n' {
lineCount++
}
}
m.lines = lineCount
// Update link positions for the current view
m = m.updateLinkPositions()
}
return m, nil
case tea.MouseMsg:
return m.handleMouseMsg(msg)
case tea.KeyMsg:
return m.handleKeyMsg(msg)
}
return m, nil
}
func (m model) updateLinkPositions() model {
// DEBUG
f, _ := os.Create("/tmp/bleamd_update_debug.txt")
if f != nil {
fmt.Fprintf(f, "updateLinkPositions called\n")
fmt.Fprintf(f, " width=%d, height=%d\n", m.width, m.height)
fmt.Fprintf(f, " yOffset=%d, xOffset=%d\n", m.yOffset, m.xOffset)
}
// Replicate the View() logic to get visible content and extract link positions
content := m.renderedContent
if m.search.term != "" {
content = m.search.HighlightContent(content)
}
lines := strings.Split(string(content), "\n")
if f != nil {
fmt.Fprintf(f, " total lines=%d\n", len(lines))
}
// Calculate visible area (same logic as View())
visibleHeight := m.height
visibleHeight -= 1 // Status bar
if m.searchActive {
visibleHeight -= 3
}
if m.search.term != "" {
visibleHeight -= 1
}
// Apply vertical scrolling
startLine := m.yOffset
endLine := startLine + visibleHeight
if len(lines) == 0 {
lines = []string{""}
}
if endLine > len(lines) {
endLine = len(lines)
}
if startLine >= len(lines) {
startLine = len(lines) - 1
}
if startLine < 0 {
startLine = 0
}
if endLine < startLine {
endLine = startLine
}
visibleLines := lines[startLine:endLine]
// Apply horizontal scrolling
for i, line := range visibleLines {
if m.xOffset < len(line) {
visibleLines[i] = line[m.xOffset:]
} else {
visibleLines[i] = ""
}
}
result := strings.Join(visibleLines, "\n")
// Extract link positions from visible content
m.linkPositions = m.extractLinkPositions(result)
if f != nil {
fmt.Fprintf(f, " extracted %d link positions\n", len(m.linkPositions))
for i, link := range m.linkPositions {
fmt.Fprintf(f, " Link %d: %q at (%d,%d) width=%d\n", i, link.text, link.x, link.y, link.width)
}
f.Close()
}
return m
}
func (m model) handleMouseMsg(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
// Handle mouse wheel scrolling
switch msg.Action {
case tea.MouseActionPress:
if msg.Button == tea.MouseButtonWheelUp {
return m.scrollUp(), nil
}
if msg.Button == tea.MouseButtonWheelDown {
return m.scrollDown(), nil
}
}
// Check if mouse is hovering over any link
previousHoveredURL := m.hoveredURL
m.hoveredURL = ""
for _, link := range m.linkPositions {
// Check if mouse position is within link bounds
if msg.X >= link.x && msg.X < link.x+link.width && msg.Y == link.y {
m.hoveredURL = link.url
// Handle click on link
if msg.Action == tea.MouseActionPress && msg.Button == tea.MouseButtonLeft {
openURL(link.url)
}
break
}
}
// If hover state changed, re-render to update underline colors
if previousHoveredURL != m.hoveredURL {
m.renderedContent = m.render()
m = m.updateLinkPositions()
}
return m, nil
}
func (m model) handleKeyMsg(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.helpActive {
m.helpActive = false
m.mode = "reading"
return m, nil
}
if m.searchActive {
m.mode = "search"
switch msg.String() {
case "enter":
return m.executeSearch()
case "esc", "ctrl+c", "ctrl+g":
return m.cancelSearch()
case "backspace":
if len(m.searchInput) > 0 {
m.searchInput = m.searchInput[:len(m.searchInput)-1]
}
return m, nil
default:
if len(msg.String()) == 1 {
m.searchInput += msg.String()
}
return m, nil
}
}
// Update mode based on search state
if m.search.term != "" {
m.mode = "search-nav"
} else {
m.mode = "reading"
}
// Handle navigation keys based on config
key := msg.String()
// In search-nav mode, allow escape or q to exit and clear search
if m.mode == "search-nav" {
if key == "esc" || key == "escape" {
return m.clearSearch(), nil
}
// Check if 'q' is pressed and it's not bound to quit (to avoid conflicts)
if key == "q" && !m.isKeyInSlice(key, m.config.Keybindings.Quit) {
return m.clearSearch(), nil
}
}
// Check if key matches any configured keybinding
if m.isKeyInSlice(key, m.config.Keybindings.ScrollUp) {
return m.scrollUp(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.ScrollDown) {
return m.scrollDown(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.ScrollLeft) {
return m.scrollLeft(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.ScrollRight) {
return m.scrollRight(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.PageUp) {
return m.pageUp(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.PageDown) {
return m.pageDown(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.GoToTop) {
return m.goToTop(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.GoToBottom) {
return m.goToBottom(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.StartSearch) {
return m.startSearch(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.NextMatch) {
return m.nextMatch(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.PrevMatch) {
return m.prevMatch(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.ClearSearch) {
return m.clearSearch(), nil
}
if m.isKeyInSlice(key, m.config.Keybindings.ShowHelp) {
m.helpActive = true
m.mode = "help"
return m, nil
}
if m.isKeyInSlice(key, m.config.Keybindings.Quit) {
return m, tea.Quit
}
// Toggle mouse capture mode
if m.isKeyInSlice(key, m.config.Keybindings.ToggleMouse) {
m.mouseCaptureEnabled = !m.mouseCaptureEnabled
if m.mouseCaptureEnabled {
return m, tea.EnableMouseAllMotion
} else {
// Disable all mouse motion tracking to allow text selection
return m, tea.DisableMouse
}
}
return m, nil
}
func (m model) isKeyInSlice(key string, keys []string) bool {
for _, k := range keys {
if key == k || key == strings.ToLower(k) {
return true
}
// Handle Ctrl+key format conversion from C-x to ctrl+x
if strings.HasPrefix(k, "C-") {
ctrlKey := "ctrl+" + strings.ToLower(strings.TrimPrefix(k, "C-"))
if key == ctrlKey {
return true
}
}
// Handle special key mappings
switch k {
case "Up", "ArrowUp":
if key == "up" {
return true
}
case "Down", "ArrowDown":
if key == "down" {
return true
}
case "Left", "ArrowLeft":
if key == "left" {
return true
}
case "Right", "ArrowRight":
if key == "right" {
return true
}
case "PageUp", "PgUp":
if key == "pgup" {
return true
}
case "PageDown", "PgDn", "PageDn":
if key == "pgdown" {
return true
}
case "Space", " ":
if key == " " {
return true
}
}
}
return false
}
func (m model) renderStatusBar() string {
// If hovering over a link, show the URL instead of keybindings
if m.hoveredURL != "" {
style := lipgloss.NewStyle().
PaddingLeft(1).
PaddingRight(1)
// Apply hovered link URL color if configured, otherwise use status bar text color
if m.config.Colors.HoveredLinkURL != "" {
if colorCode, err := hexToANSI(m.config.Colors.HoveredLinkURL); err == nil {
style = style.Foreground(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
} else if m.config.Colors.StatusBarText != "" {
if colorCode, err := hexToANSI(m.config.Colors.StatusBarText); err == nil {
style = style.Foreground(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
}
// Apply background color if configured
if m.config.Colors.StatusBarBg != "" {
if colorCode, err := hexToANSI(m.config.Colors.StatusBarBg); err == nil {
style = style.Background(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
}
return style.Render("🔗 " + m.hoveredURL)
}
// Helper to format key lists (take first key only for brevity)
firstKey := func(keys []string) string {
if len(keys) > 0 {
key := keys[0]
// Handle special keys
switch key {
case "Up", "ArrowUp":
return "↑"
case "Down", "ArrowDown":
return "↓"
case "Left", "ArrowLeft":
return "←"
case "Right", "ArrowRight":
return "→"
case "PageUp", "PgUp":
return "PgUp"
case "PageDown", "PgDn", "PageDn":
return "PgDn"
case "Space", " ":
return "Space"
case "Escape":
return "Esc"
}
// Handle Ctrl+key
if strings.HasPrefix(key, "C-") {
return "^" + strings.TrimPrefix(key, "C-")
}
return key
}
return ""
}
var items []string
switch m.mode {
case "reading":
// Show mouse mode indicator
mouseMode := "hover"
if !m.mouseCaptureEnabled {
mouseMode = "select"
}
items = []string{
fmt.Sprintf("%s/%s scroll", firstKey(m.config.Keybindings.ScrollUp), firstKey(m.config.Keybindings.ScrollDown)),
fmt.Sprintf("%s/%s page", firstKey(m.config.Keybindings.PageUp), firstKey(m.config.Keybindings.PageDown)),
fmt.Sprintf("%s search", firstKey(m.config.Keybindings.StartSearch)),
fmt.Sprintf("%s mouse:%s", firstKey(m.config.Keybindings.ToggleMouse), mouseMode),
fmt.Sprintf("%s help", firstKey(m.config.Keybindings.ShowHelp)),
fmt.Sprintf("%s quit", firstKey(m.config.Keybindings.Quit)),
}
case "search":
items = []string{
"Enter execute",
"Esc cancel",
"type to search...",
}
case "search-nav":
items = []string{
fmt.Sprintf("%s/%s scroll", firstKey(m.config.Keybindings.ScrollUp), firstKey(m.config.Keybindings.ScrollDown)),
fmt.Sprintf("%s/%s match", firstKey(m.config.Keybindings.NextMatch), firstKey(m.config.Keybindings.PrevMatch)),
fmt.Sprintf("%s clear", firstKey(m.config.Keybindings.ClearSearch)),
fmt.Sprintf("%s help", firstKey(m.config.Keybindings.ShowHelp)),
fmt.Sprintf("%s quit", firstKey(m.config.Keybindings.Quit)),
}
case "help":
items = []string{
"Press any key to close help",
}
}
// Join items with separator
statusText := strings.Join(items, " │ ")
// Apply styling - full width with configurable colors
style := lipgloss.NewStyle().
PaddingLeft(1).
PaddingRight(1)
// Apply text color if configured
if m.config.Colors.StatusBarText != "" {
if colorCode, err := hexToANSI(m.config.Colors.StatusBarText); err == nil {
style = style.Foreground(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
}
// Apply background color if configured (empty = transparent)
if m.config.Colors.StatusBarBg != "" {
if colorCode, err := hexToANSI(m.config.Colors.StatusBarBg); err == nil {
style = style.Background(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
}
return style.Render(statusText)
}
func (m model) View() string {
// Get the content to display (needed even when help is active for background)
content := m.renderedContent
if m.search.term != "" {
content = m.search.HighlightContent(content)
}
if m.helpActive {
return m.renderHelp(content)
}
// Apply viewport scrolling
lines := strings.Split(string(content), "\n")
// Calculate visible area
visibleHeight := m.height
visibleHeight -= 2 // Reserve 2 blank lines above status bar
if m.searchActive {
visibleHeight -= 3 // Reserve space for search input
}
if m.search.term != "" {
visibleHeight -= 1 // Reserve space for search status (Match X of Y)
}
// Note: We don't subtract 1 for the status bar itself because the status bar
// shares a line with the last newline from the content
// Apply vertical scrolling
startLine := m.yOffset
endLine := startLine + visibleHeight
// Handle empty content
if len(lines) == 0 {
lines = []string{""}
}
if endLine > len(lines) {
endLine = len(lines)
}
if startLine >= len(lines) {
startLine = len(lines) - 1
}
if startLine < 0 {
startLine = 0
}
if endLine < startLine {
endLine = startLine
}
visibleLines := lines[startLine:endLine]
// Apply horizontal scrolling
for i, line := range visibleLines {
if m.xOffset < len(line) {
visibleLines[i] = line[m.xOffset:]
} else {
visibleLines[i] = ""
}
}
result := strings.Join(visibleLines, "\n")
// Calculate how many lines we've used so far
contentLines := len(visibleLines)
// Add search status if needed (Match X of Y)
if m.search.term != "" {
statusText := m.search.GetStatusText()
if statusText != "" {
// Apply same padding as status bar (0 vertical, 1 horizontal)
searchStatusStyle := lipgloss.NewStyle().
Width(m.width).
Padding(0, 1)
// Apply search status colors if configured
if m.config.Colors.StatusBarText != "" {
if colorCode, err := hexToANSI(m.config.Colors.StatusBarText); err == nil {
searchStatusStyle = searchStatusStyle.Foreground(lipgloss.Color(fmt.Sprintf("%d", colorCode)))
}
}
result += "\n" + searchStatusStyle.Render(statusText)
contentLines++
}
}
// Add search input if active
if m.searchActive {
// Create outer container that spans full width to center the search box
searchBox := m.styles.searchBox.
Width(m.width - 6).
Render("Search: " + m.searchInput)
// Center it with an outer style
centered := lipgloss.NewStyle().
Width(m.width).
Align(lipgloss.Center).
Render(searchBox)
result += "\n" + centered
contentLines += 3 // Search box takes 3 lines with border
}
// Calculate how much padding we need to push status bar to bottom
// We need: contentLines + padding + 2 blank lines + status bar = m.height lines total
// Which means: contentLines + padding + 2 + 1 = m.height
// So: padding = m.height - contentLines - 3
// BUT: we need one extra line because status bar shares the last line
linesNeededForStatusBar := 2 // 2 blank lines above status bar
availableLinesForPadding := m.height - contentLines - linesNeededForStatusBar // status bar doesn't need a separate line count
// Add padding to push status bar to bottom
if availableLinesForPadding > 0 {
for i := 0; i < availableLinesForPadding; i++ {
result += "\n"
}
}
// Add 2 blank lines above the status bar (margin top)
result += "\n\n"
// Add status bar - this should be the last line, no newlines after
result += m.renderStatusBar()
return result
}
func (m model) extractLinkPositions(content string) []linkPosition {
// Extract hyperlink URLs and their text positions WITHOUT modifying the content
// This preserves OSC 8 sequences so terminals can recognize clickable links
hyperlinkPattern := regexp.MustCompile(`\x1b\]8;;([^\x1b]+)\x1b\\((?:[^\x1b]|\x1b\[[0-9;]*m)+)\x1b\]8;;\x1b\\`)
var links []linkPosition
lines := strings.Split(content, "\n")
// DEBUG
f, _ := os.Create("/tmp/bleamd_extract_debug.txt")
if f != nil {
fmt.Fprintf(f, "extractLinkPositions called with %d lines\n", len(lines))
}
for y, line := range lines {
matches := hyperlinkPattern.FindAllStringSubmatchIndex(line, -1)
if f != nil && len(matches) > 0 {
fmt.Fprintf(f, "Line %d has %d matches\n", y, len(matches))
fmt.Fprintf(f, " Raw line (first 200 chars): %q\n", line[:min(200, len(line))])
}
for _, match := range matches {
if len(match) >= 6 {
urlStart := match[2]
urlEnd := match[3]
textStart := match[4]
textEnd := match[5]
url := line[urlStart:urlEnd]
text := line[textStart:textEnd]
// Strip ANSI codes from text to get visible length
visibleText := stripANSI(text)
// Calculate X position by counting visible characters before the link
// We need to strip ALL escape sequences from the portion before the link text
beforeLink := line[:match[4]] // Get everything before the link text starts
visibleBefore := stripAllEscapeSequences(beforeLink)
x := len(visibleBefore)
if f != nil {
fmt.Fprintf(f, " Found link: url=%s, text=%q, visibleText=%q\n", url, text, visibleText)
fmt.Fprintf(f, " beforeLink length=%d, visibleBefore=%q (len=%d)\n", len(beforeLink), visibleBefore, len(visibleBefore))
fmt.Fprintf(f, " Position: x=%d, y=%d, width=%d\n", x, y, len(visibleText))
}
links = append(links, linkPosition{
url: url,
text: visibleText,
x: x,
y: y,
width: len(visibleText),
})
}
}
}
if f != nil {
fmt.Fprintf(f, "\nTotal links extracted: %d\n", len(links))
f.Close()
}
return links
}
func stripAllEscapeSequences(s string) string {
// Remove all ANSI escape sequences AND OSC 8 sequences
// OSC 8: \x1b]8;;URL\x1b\\
osc8Pattern := regexp.MustCompile(`\x1b\]8;;[^\x1b]*\x1b\\`)
s = osc8Pattern.ReplaceAllString(s, "")
// ANSI codes: \x1b[...m
ansiPattern := regexp.MustCompile(`\x1b\[[0-9;]*m`)
s = ansiPattern.ReplaceAllString(s, "")
return s
}
type linkPosition struct {
url string
text string
x int
y int
width int
}
func (m model) render() []byte {
// Get options from config, plus required options
opts := m.config.GetMarkdownOptions()
// Calculate render width
// The markdown library includes both link text AND URL in line length calculations,
// but we convert to OSC 8 hyperlinks where only the link text is visible.
// So we render at a wider width to prevent unnecessary wrapping.
// Use 2x terminal width to give plenty of room for URLs
renderWidth := (m.width - padding) * 2
if renderWidth < 40 {
renderWidth = 40
}
// Process badges before rendering
processedMarkdown := processBadges(m.raw, m.config)
rendered := markdown.Render(processedMarkdown, renderWidth, padding, opts...)
// Add hyperlinks with underlines (pass hoveredURL for hover state)
rendered = addHyperlinks(rendered, processedMarkdown, m.config, m.hoveredURL)
// Count lines
lineCount := 0
for _, b := range rendered {
if b == '\n' {
lineCount++
}
}
// Update the model's line count (this is a bit of a hack since we can't modify m in this method)
// We'll handle this in the View method instead
return rendered
}
func (m model) renderHelp(backgroundContent []byte) string {
// Render the full background view WITHOUT search highlighting
// Save the current search term and clear it temporarily
savedSearchTerm := m.search.term
m.search.term = ""
normalView := m.renderNormalView()
// Restore the search term
m.search.term = savedSearchTerm
bgLines := strings.Split(normalView, "\n")
// Ensure we have exactly m.height lines
for len(bgLines) < m.height {
bgLines = append(bgLines, "")
}
if len(bgLines) > m.height {
bgLines = bgLines[:m.height]
}
// Render the help box (no fixed height so it sizes to content)
helpContent := m.buildHelpContent()
helpBox := m.styles.helpBox.
Width(60).
Render(helpContent)
helpLines := strings.Split(helpBox, "\n")
// Calculate centered position for overlay
helpHeight := len(helpLines)
// The border adds to the width, so measure the actual rendered width
// Use rune count for proper Unicode character counting
helpWidth := 0
for _, line := range helpLines {
stripped := stripANSI(line)
w := len([]rune(stripped)) // Count runes, not bytes
if w > helpWidth {
helpWidth = w
}
}
// DEBUG
f, _ := os.Create("/tmp/bleamd_help_debug.txt")
if f != nil {
fmt.Fprintf(f, "m.width=%d, m.height=%d\n", m.width, m.height)
fmt.Fprintf(f, "helpWidth=%d, helpHeight=%d\n", helpWidth, helpHeight)
fmt.Fprintf(f, "First help line: %q\n", helpLines[0])
fmt.Fprintf(f, "First help line visible length: %d\n", len([]rune(stripANSI(helpLines[0]))))
f.Close()
}
startY := (m.height - helpHeight) / 2
startX := (m.width - helpWidth) / 2
if startX < 0 {
startX = 0
}
if startY < 0 {
startY = 0
}
// DEBUG
f, _ = os.OpenFile("/tmp/bleamd_help_debug.txt", os.O_APPEND|os.O_WRONLY, 0644)
if f != nil {
fmt.Fprintf(f, "startX=%d, startY=%d\n", startX, startY)
f.Close()
}
// Overlay the help box onto the background
for i, helpLine := range helpLines {
y := startY + i
if y >= 0 && y < len(bgLines) {
bgLine := bgLines[y]
// Build new line with overlay
var result strings.Builder
// Left part of background
if startX > 0 {
leftPart := truncateVisibleChars(bgLine, startX)
result.WriteString(leftPart)
// Pad if needed
leftLen := len([]rune(stripANSI(leftPart)))
if leftLen < startX {
result.WriteString(strings.Repeat(" ", startX-leftLen))
}
}
// Help box line
result.WriteString(helpLine)
// Right part of background
helpVisibleLen := len([]rune(stripANSI(helpLine)))
endX := startX + helpVisibleLen
bgVisibleLen := len([]rune(stripANSI(bgLine)))
if endX < bgVisibleLen {
rightPart := skipVisibleChars(bgLine, endX)
result.WriteString(rightPart)
}
bgLines[y] = result.String()
}
}