-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtui.go
More file actions
1382 lines (1248 loc) · 37.2 KB
/
tui.go
File metadata and controls
1382 lines (1248 loc) · 37.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
// SPDX-License-Identifier: MIT
package main
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/boyter/cs/v3/pkg/common"
"github.com/boyter/cs/v3/pkg/ranker"
"github.com/boyter/cs/v3/pkg/snippet"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
)
// searchResult represents a single search result
type searchResult struct {
Filename string
Location string
Score float64
Snippet string // plain text snippet (snippet mode)
SnippetLocs [][]int // match positions within Snippet [start, end]
LineRange string // line range info
LineResults []snippet.LineResult // per-line results with positions (lines mode)
Language string
TotalLines int64
Code int64
Comment int64
Blank int64
Complexity int64
DuplicateCount int
MatchLocations map[string][][]int // absolute byte positions in file
Prose bool // true for prose/text files (skip syntax highlighting)
}
// debounceTickMsg is sent after the debounce delay to trigger a search
type debounceTickMsg struct {
seq int
query string
}
// searchResultsMsg delivers incremental search results from the search goroutine
type searchResultsMsg struct {
seq int
results []searchResult
fileJobs []*common.FileJob
done bool // true = search complete
total int // total files scanned so far
textTotal int // non-binary, successfully read files (for BM25 ranking)
}
// Styles
var (
titleStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("5")) // fuchsia/magenta
selectedTitleStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("5")).
Bold(true)
snippetStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("252"))
selectedSnippetStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("252"))
matchStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("1")). // red
Bold(true)
selectedMatchStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("1")).
Bold(true)
statusStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("243"))
inputLabelStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("7"))
snippetLabelStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("243"))
selectedIndicator = lipgloss.NewStyle().
Foreground(lipgloss.Color("5")).
SetString("▎")
)
type model struct {
cfg *Config
searchInput textinput.Model
snippetInput textinput.Model
focusIndex int // 0=search, 1=snippet
results []searchResult
fileJobs []*common.FileJob
selectedIndex int
scrollOffset int
windowHeight int
windowWidth int
chosen string // set on Enter, printed after exit
searchSeq int // monotonic counter, incremented on every text change
searching bool // true while search is in flight
searchCancel context.CancelFunc // cancels in-flight search; nil if none
searchResults chan searchResultsMsg // channel from search goroutine
lastQuery string // query that produced current results
errMsg string // transient error message shown in status line
fileCount int // total files scanned (for status line)
textFileCount int // non-binary, successfully read files (for BM25 ranking)
snippetMode string // "snippet" or "lines"
searchCache *SearchCache // caches file locations across progressive queries
// File viewer overlay state
viewing bool // true when viewer is open
viewLines []string // lines of the viewed file
viewScroll int // scroll offset (line index of top of viewport)
viewFilename string // display filename
viewLocation string // full file path (for Enter-to-select)
viewLanguage string // language for title
viewLineRange string // original match line range
viewMatchLocs map[string][][]int // absolute byte match positions
viewLineOffsets []int // byte offset where each line starts
viewStartLine int // line to initially center on
viewProse bool // true if viewed file is prose (skip syntax highlighting)
}
func initialModel(cfg *Config) model {
switch cfg.Color {
case "always":
lipgloss.SetColorProfile(termenv.ANSI256)
case "never":
lipgloss.SetColorProfile(termenv.Ascii)
}
si := textinput.New()
si.Placeholder = "search query..."
si.Prompt = "> "
si.Focus()
si.CharLimit = 256
sn := textinput.New()
sn.Placeholder = ""
sn.Prompt = ""
sn.SetValue(fmt.Sprintf("%d", cfg.SnippetLength))
sn.CharLimit = 5
sn.Width = 5
return model{
cfg: cfg,
searchInput: si,
snippetInput: sn,
focusIndex: 0,
snippetMode: cfg.SnippetMode,
searchCache: NewSearchCache(),
}
}
func (m model) Init() tea.Cmd {
return tea.Batch(tea.EnterAltScreen, textinput.Blink)
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.windowHeight = msg.Height
m.windowWidth = msg.Width
m.clampScroll()
return m, nil
case debounceTickMsg:
if msg.seq != m.searchSeq {
return m, nil // stale tick, user kept typing
}
if m.searchCancel != nil {
m.searchCancel() // cancel previous search
}
query := strings.TrimSpace(msg.query)
if query == "" {
m.results = nil
m.fileJobs = nil
m.searching = false
m.fileCount = 0
return m, nil
}
// Parse snippet length from input
snippetLen := 300
if v := m.snippetInput.Value(); v != "" {
fmt.Sscanf(v, "%d", &snippetLen)
}
ctx, cancel := context.WithCancel(context.Background())
m.searchCancel = cancel
m.searching = true
m.results = nil
m.fileJobs = nil
m.selectedIndex = 0
m.scrollOffset = 0
m.fileCount = 0
ch := make(chan searchResultsMsg, 1)
m.searchResults = ch
go realSearch(ctx, m.cfg, m.searchSeq, query, snippetLen, m.snippetMode, m.searchCache, ch)
return m, listenForResults(ch)
case searchResultsMsg:
if msg.seq != m.searchSeq {
return m, nil // stale results from old search
}
m.results = append(m.results, msg.results...)
m.fileJobs = append(m.fileJobs, msg.fileJobs...)
m.fileCount = msg.total
m.textFileCount = msg.textTotal
if msg.done {
m.searching = false
m.searchCancel = nil
m.lastQuery = m.searchInput.Value()
// Rank all results with BM25 and re-extract snippets with global frequencies
if len(m.fileJobs) > 0 {
testIntent := ranker.HasTestIntent(strings.Fields(m.searchInput.Value()))
ranked := ranker.RankResults(m.cfg.Ranker, m.textFileCount, m.fileJobs, m.cfg.StructuralRankerConfig(), m.cfg.ResolveRankingProfile(), testIntent)
if m.cfg.Dedup {
ranked = ranker.DeduplicateResults(ranked)
}
docFreq := ranker.CalculateDocumentTermFrequency(ranked)
// Parse snippet length from input
snippetLen := 300
if v := m.snippetInput.Value(); v != "" {
fmt.Sscanf(v, "%d", &snippetLen)
}
ctxBefore, ctxAfter := m.cfg.ResolveContext()
var newResults []searchResult
for _, fj := range ranked {
fileMode := resolveSnippetMode(m.snippetMode, fj.Filename)
isProse := snippet.IsProseFile(fj.Extension)
if fileMode == "grep" {
lineResults := snippet.FindAllMatchingLines(fj, m.cfg.LineLimit, ctxBefore, ctxAfter)
lineRange := ""
if len(lineResults) > 0 {
lineRange = fmt.Sprintf("%d-%d",
lineResults[0].LineNumber,
lineResults[len(lineResults)-1].LineNumber)
}
fj.Content = nil
newResults = append(newResults, searchResult{
Filename: fj.Location,
Location: fj.Location,
Score: fj.Score,
LineResults: lineResults,
LineRange: lineRange,
Language: fj.Language,
TotalLines: fj.Lines,
Code: fj.Code,
Comment: fj.Comment,
Blank: fj.Blank,
Complexity: fj.Complexity,
DuplicateCount: fj.DuplicateCount,
MatchLocations: fj.MatchLocations,
Prose: isProse,
})
} else if fileMode == "lines" {
surroundLines := snippetLen / 100
if surroundLines < 1 {
surroundLines = 1
}
lineResults := snippet.FindMatchingLines(fj, surroundLines)
lineRange := ""
if len(lineResults) > 0 {
lineRange = fmt.Sprintf("%d-%d",
lineResults[0].LineNumber,
lineResults[len(lineResults)-1].LineNumber)
}
fj.Content = nil
newResults = append(newResults, searchResult{
Filename: fj.Location,
Location: fj.Location,
Score: fj.Score,
LineResults: lineResults,
LineRange: lineRange,
Language: fj.Language,
TotalLines: fj.Lines,
Code: fj.Code,
Comment: fj.Comment,
Blank: fj.Blank,
Complexity: fj.Complexity,
DuplicateCount: fj.DuplicateCount,
MatchLocations: fj.MatchLocations,
Prose: isProse,
})
} else {
snippets := snippet.ExtractRelevant(fj, docFreq, snippetLen)
snippetText := ""
lineRange := ""
var sLocs [][]int
if len(snippets) > 0 {
snippetText = snippets[0].Content
lineRange = fmt.Sprintf("%d-%d", snippets[0].LineStart, snippets[0].LineEnd)
sLocs = snippetMatchLocs(fj.MatchLocations, snippets[0].StartPos, snippets[0].EndPos)
}
fj.Content = nil
newResults = append(newResults, searchResult{
Filename: fj.Location,
Location: fj.Location,
Score: fj.Score,
Snippet: snippetText,
SnippetLocs: sLocs,
LineRange: lineRange,
Language: fj.Language,
TotalLines: fj.Lines,
Code: fj.Code,
Comment: fj.Comment,
Blank: fj.Blank,
Complexity: fj.Complexity,
DuplicateCount: fj.DuplicateCount,
MatchLocations: fj.MatchLocations,
Prose: isProse,
})
}
}
m.results = newResults
m.fileJobs = nil
m.selectedIndex = 0
m.scrollOffset = 0
}
return m, nil
}
// Keep listening for more results
return m, listenForResults(m.searchResults)
case tea.MouseMsg:
m.errMsg = ""
if m.viewing {
maxViewScroll := max(0, len(m.viewLines)-(m.windowHeight-3))
switch msg.Type {
case tea.MouseWheelUp:
m.viewScroll = max(0, m.viewScroll-3)
case tea.MouseWheelDown:
m.viewScroll = min(maxViewScroll, m.viewScroll+3)
}
return m, nil
}
switch msg.Type {
case tea.MouseWheelUp:
m.scrollOffset -= 3
m.clampScroll()
m.syncSelectedToScroll()
return m, nil
case tea.MouseWheelDown:
m.scrollOffset += 3
m.clampScroll()
m.syncSelectedToScroll()
return m, nil
case tea.MouseLeft:
idx := m.resultIndexAtY(msg.Y)
if idx >= 0 && idx < len(m.results) {
m.selectedIndex = idx
}
return m, nil
}
case tea.KeyMsg:
m.errMsg = ""
if m.viewing {
maxViewScroll := max(0, len(m.viewLines)-(m.windowHeight-3))
switch msg.Type {
case tea.KeyEsc, tea.KeyF5, tea.KeyCtrlO, tea.KeyCtrlP:
m.viewing = false
m.viewLines = nil // free memory
return m, nil
case tea.KeyUp:
m.viewScroll = max(0, m.viewScroll-1)
return m, nil
case tea.KeyDown:
m.viewScroll = min(maxViewScroll, m.viewScroll+1)
return m, nil
case tea.KeyPgUp:
m.viewScroll = max(0, m.viewScroll-(m.windowHeight-4))
return m, nil
case tea.KeyPgDown:
m.viewScroll = min(maxViewScroll, m.viewScroll+(m.windowHeight-4))
return m, nil
case tea.KeyEnter:
if m.cfg.Format == "vimgrep" {
m.chosen = tuiVimGrep(m.cfg, m.viewLocation, m.viewMatchLocs)
} else {
m.chosen = m.viewLocation
}
return m, tea.Quit
}
return m, nil
}
switch msg.Type {
case tea.KeyCtrlC, tea.KeyEsc:
if m.searchCancel != nil {
m.searchCancel()
}
return m, tea.Quit
case tea.KeyEnter:
if len(m.results) > 0 && m.selectedIndex < len(m.results) {
if m.searchCancel != nil {
m.searchCancel()
}
r := m.results[m.selectedIndex]
if m.cfg.Format == "vimgrep" {
m.chosen = tuiVimGrep(m.cfg, r.Location, r.MatchLocations)
} else {
m.chosen = r.Location
}
return m, tea.Quit
}
return m, nil
case tea.KeyTab, tea.KeyShiftTab:
if m.focusIndex == 0 {
m.focusIndex = 1
m.searchInput.Blur()
m.snippetInput.Focus()
} else {
m.focusIndex = 0
m.snippetInput.Blur()
m.searchInput.Focus()
}
return m, nil
case tea.KeyUp:
if m.focusIndex == 1 {
m.adjustSnippetLength(100)
if q := strings.TrimSpace(m.searchInput.Value()); q != "" {
m.searchSeq++
return m, makeDebounceCmd(m.searchSeq, m.searchInput.Value())
}
return m, nil
}
if m.selectedIndex > 0 {
m.selectedIndex--
m.ensureVisible()
}
return m, nil
case tea.KeyDown:
if m.focusIndex == 1 {
m.adjustSnippetLength(-100)
if q := strings.TrimSpace(m.searchInput.Value()); q != "" {
m.searchSeq++
return m, makeDebounceCmd(m.searchSeq, m.searchInput.Value())
}
return m, nil
}
if m.selectedIndex < len(m.results)-1 {
m.selectedIndex++
m.ensureVisible()
}
return m, nil
case tea.KeyPgUp:
if m.focusIndex == 1 {
m.adjustSnippetLength(200)
if q := strings.TrimSpace(m.searchInput.Value()); q != "" {
m.searchSeq++
return m, makeDebounceCmd(m.searchSeq, m.searchInput.Value())
}
return m, nil
}
case tea.KeyPgDown:
if m.focusIndex == 1 {
m.adjustSnippetLength(-200)
if q := strings.TrimSpace(m.searchInput.Value()); q != "" {
m.searchSeq++
return m, makeDebounceCmd(m.searchSeq, m.searchInput.Value())
}
return m, nil
}
case tea.KeyF1:
m.cycleRanker()
return m, m.retriggerSearch()
case tea.KeyF2:
m.cycleCodeFilter()
return m, m.retriggerSearch()
case tea.KeyF3:
m.cycleGravity()
return m, m.retriggerSearch()
case tea.KeyF4:
m.cycleNoise()
return m, m.retriggerSearch()
case tea.KeyF5, tea.KeyCtrlO, tea.KeyCtrlP:
if len(m.results) > 0 && m.selectedIndex < len(m.results) {
if err := m.openViewer(m.results[m.selectedIndex]); err != nil {
m.errMsg = fmt.Sprintf("cannot open file: %v", err)
}
}
return m, nil
case tea.KeyF6:
m.cycleSnippetMode()
return m, m.retriggerSearch()
}
}
// Update the focused input
if m.focusIndex == 0 {
prevValue := m.searchInput.Value()
var cmd tea.Cmd
m.searchInput, cmd = m.searchInput.Update(msg)
cmds = append(cmds, cmd)
// On text change, increment seq and start debounce timer
if m.searchInput.Value() != prevValue {
m.searchSeq++
cmds = append(cmds, makeDebounceCmd(m.searchSeq, m.searchInput.Value()))
}
} else {
var cmd tea.Cmd
m.snippetInput, cmd = m.snippetInput.Update(msg)
cmds = append(cmds, cmd)
}
return m, tea.Batch(cmds...)
}
func (m *model) adjustSnippetLength(delta int) {
val := 300
if v := m.snippetInput.Value(); v != "" {
fmt.Sscanf(v, "%d", &val)
}
val += delta
if val < 100 {
val = 100
}
if val > 8000 {
val = 8000
}
m.snippetInput.SetValue(fmt.Sprintf("%d", val))
}
// makeDebounceCmd returns a tea.Cmd that fires a debounceTickMsg after 200ms
func makeDebounceCmd(seq int, query string) tea.Cmd {
return tea.Tick(200*time.Millisecond, func(t time.Time) tea.Msg {
return debounceTickMsg{seq: seq, query: query}
})
}
// listenForResults returns a tea.Cmd that blocks until the next message arrives on ch
func listenForResults(ch <-chan searchResultsMsg) tea.Cmd {
return func() tea.Msg {
msg, ok := <-ch
if !ok {
return searchResultsMsg{done: true}
}
return msg
}
}
// realSearch wraps DoSearch for TUI use, streaming results in batches via the channel.
func realSearch(ctx context.Context, cfg *Config, seq int, query string, snippetLen int, snippetMode string, cache *SearchCache, ch chan<- searchResultsMsg) {
defer close(ch)
searchCh, stats, err := DoSearch(ctx, cfg, query, cache)
if err != nil {
select {
case ch <- searchResultsMsg{seq: seq, done: true}:
case <-ctx.Done():
}
return
}
var batch []searchResult
var batchJobs []*common.FileJob
ctxBefore, ctxAfter := cfg.ResolveContext()
for fj := range searchCh {
// Build a preliminary searchResult for immediate display
fileMode := resolveSnippetMode(snippetMode, fj.Filename)
isProse := snippet.IsProseFile(fj.Extension)
var sr searchResult
if fileMode == "grep" {
lineResults := snippet.FindAllMatchingLines(fj, cfg.LineLimit, ctxBefore, ctxAfter)
lineRange := ""
if len(lineResults) > 0 {
lineRange = fmt.Sprintf("%d-%d",
lineResults[0].LineNumber,
lineResults[len(lineResults)-1].LineNumber)
}
sr = searchResult{
Filename: fj.Location,
Location: fj.Location,
LineResults: lineResults,
LineRange: lineRange,
Language: fj.Language,
TotalLines: fj.Lines,
Code: fj.Code,
Comment: fj.Comment,
Blank: fj.Blank,
Complexity: fj.Complexity,
MatchLocations: fj.MatchLocations,
Prose: isProse,
}
} else if fileMode == "lines" {
lineResults := snippet.FindMatchingLines(fj, 2)
lineRange := ""
if len(lineResults) > 0 {
lineRange = fmt.Sprintf("%d-%d",
lineResults[0].LineNumber,
lineResults[len(lineResults)-1].LineNumber)
}
sr = searchResult{
Filename: fj.Location,
Location: fj.Location,
LineResults: lineResults,
LineRange: lineRange,
Language: fj.Language,
TotalLines: fj.Lines,
Code: fj.Code,
Comment: fj.Comment,
Blank: fj.Blank,
Complexity: fj.Complexity,
MatchLocations: fj.MatchLocations,
Prose: isProse,
}
} else {
docFreq := make(map[string]int, len(fj.MatchLocations))
for k, v := range fj.MatchLocations {
docFreq[k] = len(v)
}
snippets := snippet.ExtractRelevant(fj, docFreq, snippetLen)
snippetText := ""
lineRange := ""
var sLocs [][]int
if len(snippets) > 0 {
snippetText = snippets[0].Content
lineRange = fmt.Sprintf("%d-%d", snippets[0].LineStart, snippets[0].LineEnd)
sLocs = snippetMatchLocs(fj.MatchLocations, snippets[0].StartPos, snippets[0].EndPos)
}
sr = searchResult{
Filename: fj.Location,
Location: fj.Location,
Snippet: snippetText,
SnippetLocs: sLocs,
LineRange: lineRange,
Language: fj.Language,
TotalLines: fj.Lines,
Code: fj.Code,
Comment: fj.Comment,
Blank: fj.Blank,
Complexity: fj.Complexity,
MatchLocations: fj.MatchLocations,
Prose: isProse,
}
}
batch = append(batch, sr)
batchJobs = append(batchJobs, fj)
if len(batch) >= 5 {
select {
case ch <- searchResultsMsg{
seq: seq, results: batch, fileJobs: batchJobs,
total: int(stats.FileCount.Load()), textTotal: int(stats.TextFileCount.Load()),
}:
batch = nil
batchJobs = nil
case <-ctx.Done():
return
}
}
}
// Send remaining results + done signal
select {
case ch <- searchResultsMsg{
seq: seq, results: batch, fileJobs: batchJobs,
done: true, total: int(stats.FileCount.Load()), textTotal: int(stats.TextFileCount.Load()),
}:
case <-ctx.Done():
}
}
// snippetMatchLocs filters match locations to those within [startPos, endPos]
// and adjusts them to be relative to startPos (matching console.go behavior).
func snippetMatchLocs(matchLocations map[string][][]int, startPos, endPos int) [][]int {
var locs [][]int
for _, value := range matchLocations {
for _, s := range value {
if len(s) < 2 {
continue
}
if s[0] >= startPos && s[1] <= endPos {
locs = append(locs, []int{
s[0] - startPos,
s[1] - startPos,
})
}
}
}
return locs
}
// resultHeight returns the number of terminal lines a result takes up
func resultHeight(r searchResult) int {
if len(r.LineResults) > 0 {
gaps := 0
for i := 1; i < len(r.LineResults); i++ {
if r.LineResults[i].LineNumber > r.LineResults[i-1].LineNumber+1 {
gaps++
}
}
return 1 + len(r.LineResults) + gaps + 1
}
// 1 for title + lines in snippet + 1 blank line separator
lines := strings.Count(r.Snippet, "\n") + 1
return 1 + lines + 1
}
func (m *model) totalContentHeight() int {
total := 0
for _, r := range m.results {
total += resultHeight(r)
}
return total
}
func (m *model) clampScroll() {
if m.scrollOffset < 0 {
m.scrollOffset = 0
}
availHeight := m.windowHeight - 5
if availHeight < 1 {
availHeight = 1
}
maxScroll := m.totalContentHeight() - availHeight
if maxScroll < 0 {
maxScroll = 0
}
if m.scrollOffset > maxScroll {
m.scrollOffset = maxScroll
}
}
func (m *model) resultIndexAtY(y int) int {
const headerLines = 2
if y < headerLines {
return -1
}
contentLine := m.scrollOffset + (y - headerLines)
accum := 0
for i, r := range m.results {
rh := resultHeight(r)
if contentLine < accum+rh {
return i
}
accum += rh
}
return -1
}
func (m *model) syncSelectedToScroll() {
if len(m.results) == 0 {
return
}
availHeight := m.windowHeight - 5
if availHeight < 1 {
availHeight = 1
}
accum := 0
firstVisible, lastVisible := -1, -1
for i, r := range m.results {
rh := resultHeight(r)
if accum+rh > m.scrollOffset && accum < m.scrollOffset+availHeight {
if firstVisible == -1 {
firstVisible = i
}
lastVisible = i
}
accum += rh
if accum >= m.scrollOffset+availHeight && lastVisible >= 0 {
break
}
}
if firstVisible == -1 {
return
}
if m.selectedIndex < firstVisible {
m.selectedIndex = firstVisible
}
if m.selectedIndex > lastVisible {
m.selectedIndex = lastVisible
}
}
func (m *model) ensureVisible() {
// Calculate available height for results area
availHeight := m.windowHeight - 5 // input + status + separator + bottom bar + overhead
// Make sure selected item is visible by adjusting scroll offset
heightBefore := 0
for i := 0; i < m.selectedIndex; i++ {
if i < len(m.results) {
heightBefore += resultHeight(m.results[i])
}
}
selectedH := 0
if m.selectedIndex < len(m.results) {
selectedH = resultHeight(m.results[m.selectedIndex])
}
// Scroll up if selected is above viewport
if heightBefore < m.scrollOffset {
m.scrollOffset = heightBefore
}
// Scroll down if selected is below viewport
if heightBefore+selectedH > m.scrollOffset+availHeight {
m.scrollOffset = heightBefore + selectedH - availHeight
}
m.clampScroll()
}
// cycleRanker cycles the ranker through: simple → tfidf → bm25 → structural → simple…
func (m *model) cycleRanker() {
order := []string{"simple", "tfidf", "bm25", "structural", "min"}
for i, v := range order {
if v == m.cfg.Ranker {
m.cfg.Ranker = order[(i+1)%len(order)]
return
}
}
m.cfg.Ranker = "simple"
}
// cycleCodeFilter cycles: default → only-code → only-comments → only-strings → only-declarations → only-usages → default…
// Auto-switches ranker to "structural" when a filter is active.
func (m *model) cycleCodeFilter() {
switch {
case !m.cfg.OnlyCode && !m.cfg.OnlyComments && !m.cfg.OnlyStrings && !m.cfg.OnlyDeclarations && !m.cfg.OnlyUsages:
m.cfg.OnlyCode = true
case m.cfg.OnlyCode:
m.cfg.OnlyCode = false
m.cfg.OnlyComments = true
case m.cfg.OnlyComments:
m.cfg.OnlyComments = false
m.cfg.OnlyStrings = true
case m.cfg.OnlyStrings:
m.cfg.OnlyStrings = false
m.cfg.OnlyDeclarations = true
case m.cfg.OnlyDeclarations:
m.cfg.OnlyDeclarations = false
m.cfg.OnlyUsages = true
case m.cfg.OnlyUsages:
m.cfg.OnlyUsages = false
}
if m.cfg.HasContentFilter() {
m.cfg.Ranker = "structural"
}
}
// cycleGravity cycles: off → low → default → logic → brain → off…
func (m *model) cycleGravity() {
order := []string{"off", "low", "default", "logic", "brain"}
for i, v := range order {
if v == m.cfg.GravityIntent {
m.cfg.GravityIntent = order[(i+1)%len(order)]
return
}
}
m.cfg.GravityIntent = "off"
}
// cycleNoise cycles: silence → quiet → default → loud → raw → silence…
func (m *model) cycleNoise() {
order := []string{"silence", "quiet", "default", "loud", "raw"}
for i, v := range order {
if v == m.cfg.NoiseIntent {
m.cfg.NoiseIntent = order[(i+1)%len(order)]
return
}
}
m.cfg.NoiseIntent = "silence"
}
// cycleSnippetMode cycles: auto → snippet → lines → grep → auto…
func (m *model) cycleSnippetMode() {
order := []string{"auto", "snippet", "lines", "grep"}
for i, v := range order {
if v == m.snippetMode {
m.snippetMode = order[(i+1)%len(order)]
return
}
}
m.snippetMode = "auto"
}
// retriggerSearch bumps the search sequence and returns a debounce command to re-execute the current query.
func (m *model) retriggerSearch() tea.Cmd {
m.searchSeq++
return makeDebounceCmd(m.searchSeq, m.searchInput.Value())
}
// tuiVimGrep re-reads a file and formats all matches as vimgrep lines.
// Mirrors the branch structure of formatVimGrep in console.go.
func tuiVimGrep(cfg *Config, location string, matchLocations map[string][][]int) string {
content, err := readFileContent(location, cfg.MaxReadSizeBytes)
if err != nil {
return location
}
fj := &common.FileJob{
Filename: location,
Location: location,
Content: content,
MatchLocations: matchLocations,
}
fileMode := resolveSnippetMode(cfg.SnippetMode, location)
var vimGrepOutput []string
if fileMode == "grep" {
lineResults := snippet.FindAllMatchingLines(fj, cfg.LineLimit, 0, 0)
for _, lr := range lineResults {
col := 1
if len(lr.Locs) > 0 {
col = lr.Locs[0][0] + 1
}
hint := strings.ReplaceAll(lr.Content, "\n", "\\n")
line := fmt.Sprintf("%v:%v:%v:%v", location, lr.LineNumber, col, hint)
vimGrepOutput = append(vimGrepOutput, line)
}
} else if fileMode == "lines" {
lineResults := snippet.FindMatchingLines(fj, 0)
for _, lr := range lineResults {
col := 1
if len(lr.Locs) > 0 {
col = lr.Locs[0][0] + 1
}
hint := strings.ReplaceAll(lr.Content, "\n", "\\n")
line := fmt.Sprintf("%v:%v:%v:%v", location, lr.LineNumber, col, hint)
vimGrepOutput = append(vimGrepOutput, line)
}
} else {
docFreq := make(map[string]int, len(matchLocations))
for k, v := range matchLocations {
docFreq[k] = len(v)
}
snippets := snippet.ExtractRelevant(fj, docFreq, 50)
if len(snippets) > cfg.SnippetCount {
snippets = snippets[:cfg.SnippetCount]
}
for _, snip := range snippets {
hint := strings.ReplaceAll(snip.Content, "\n", "\\n")
line := fmt.Sprintf("%v:%v:%v:%v", location, snip.LineStart, snip.StartPos, hint)
vimGrepOutput = append(vimGrepOutput, line)
}
}
if len(vimGrepOutput) == 0 {
return location
}
return strings.Join(vimGrepOutput, "\n")
}
// codeFilterLabel returns a display label for the current code filter state.
func (m *model) codeFilterLabel() string {
switch {
case m.cfg.OnlyCode:
return "only-code"
case m.cfg.OnlyComments:
return "only-comments"
case m.cfg.OnlyStrings:
return "only-strings"
case m.cfg.OnlyDeclarations:
return "only-declarations"
case m.cfg.OnlyUsages:
return "only-usages"
default:
return "default"
}
}
func (m model) View() string {
if m.windowWidth == 0 {
return "loading..."
}
if m.viewing {
return m.renderViewer()