Debian Codegraph @

src/core.go

raw
1 // Package fzf implements fzf, a command-line fuzzy finder.
2 package fzf
3
4 import (
5 "fmt"
6 "maps"
7 "math"
8 "os"
9 "sync"
10 "time"
11
12 "github.com/junegunn/fzf/src/tui"
13 "github.com/junegunn/fzf/src/util"
14 )
15
16 /*
17 Reader -> EvtReadFin
18 Reader -> EvtReadNew -> Matcher (restart)
19 Terminal -> EvtSearchNew:bool -> Matcher (restart)
20 Matcher -> EvtSearchProgress -> Terminal (update info)
21 Matcher -> EvtSearchFin -> Terminal (update list)
22 */
23
24 type revision struct {
25 major int
26 minor int
27 }
28
29 func (r *revision) bumpMajor() {
30 r.major++
31 r.minor = 0
32 }
33
34 func (r *revision) bumpMinor() {
35 r.minor++
36 }
37
38 func (r revision) compatible(other revision) bool {
39 return r.major == other.major
40 }
41
42 func buildItemTransformer(opts *Options) func(*Item) string {
43 if opts.AcceptNth != nil {
44 fn := opts.AcceptNth(opts.Delimiter)
45 return func(item *Item) string {
46 return item.acceptNth(opts.Ansi, opts.Delimiter, fn)
47 }
48 }
49 return func(item *Item) string {
50 return item.AsString(opts.Ansi)
51 }
52 }
53
54 // Run starts fzf
55 func Run(opts *Options) (int, error) {
56 if opts.Filter == nil {
57 if opts.useTmux() {
58 return runTmux(os.Args, opts)
59 }
60 if opts.useZellij() {
61 return runZellij(os.Args, opts)
62 }
63
64 if needWinpty(opts) {
65 return runWinpty(os.Args, opts)
66 }
67 }
68
69 if err := postProcessOptions(opts); err != nil {
70 return ExitError, err
71 }
72
73 defer util.RunAtExitFuncs()
74
75 // Output channel given
76 if opts.Output != nil {
77 opts.Printer = func(str string) {
78 opts.Output <- str
79 }
80 }
81
82 sort := opts.Sort > 0
83 sortCriteria = opts.Criteria
84
85 // Event channel
86 eventBox := util.NewEventBox()
87
88 // ANSI code processor
89 ansiProcessor := func(data []byte) (util.Chars, *[]ansiOffset) {
90 return util.ToChars(data), nil
91 }
92
93 var lineAnsiState, prevLineAnsiState *ansiState
94 if opts.Ansi {
95 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {
96 prevLineAnsiState = lineAnsiState
97 trimmed, offsets, newState := extractColor(byteString(data), lineAnsiState, nil)
98 lineAnsiState = newState
99
100 // Full line background is found. Add a special marker.
101 if offsets != nil && newState != nil && len(*offsets) > 0 && newState.lbg >= 0 {
102 marker := (*offsets)[len(*offsets)-1]
103 marker.offset[0] = marker.offset[1]
104 marker.color.bg = newState.lbg
105 marker.color.attr = marker.color.attr | tui.FullBg
106 newOffsets := append(*offsets, marker)
107 offsets = &newOffsets
108
109 // Reset the full-line background color
110 lineAnsiState.lbg = -1
111 }
112 return util.ToChars(stringBytes(trimmed)), offsets
113 }
114 }
115
116 // Chunk list
117 cache := NewChunkCache()
118 var chunkList *ChunkList
119 var itemIndex int32
120 // transformItem applies with-nth transformation to an item's raw data.
121 // It handles ANSI token propagation using prevLineAnsiState for cross-line continuity.
122 transformItem := func(item *Item, data []byte, transformer func([]Token, int32) string, index int32) {
123 tokens := Tokenize(byteString(data), opts.Delimiter)
124 if opts.Ansi && len(tokens) > 1 {
125 var ansiState *ansiState
126 if prevLineAnsiState != nil {
127 ansiStateDup := *prevLineAnsiState
128 ansiState = &ansiStateDup
129 }
130 for _, token := range tokens {
131 prevAnsiState := ansiState
132 _, _, ansiState = extractColor(token.text.ToString(), ansiState, nil)
133 if prevAnsiState != nil {
134 token.text.Prepend("\x1b[m" + prevAnsiState.ToString())
135 } else {
136 token.text.Prepend("\x1b[m")
137 }
138 }
139 }
140 transformed := transformer(tokens, index)
141 item.text, item.colors = ansiProcessor(stringBytes(transformed))
142
143 // We should not trim trailing whitespaces with background colors
144 var maxColorOffset int32
145 if item.colors != nil {
146 for _, ansi := range *item.colors {
147 if ansi.color.bg >= 0 {
148 maxColorOffset = max(maxColorOffset, ansi.offset[1])
149 }
150 }
151 }
152 item.text.TrimTrailingWhitespaces(int(maxColorOffset))
153 }
154
155 var nthTransformer func([]Token, int32) string
156 if opts.WithNth == nil {
157 chunkList = NewChunkList(cache, func(item *Item, data []byte) bool {
158 item.text, item.colors = ansiProcessor(data)
159 item.text.Index = itemIndex
160 itemIndex++
161 return true
162 })
163 } else {
164 nthTransformer = opts.WithNth(opts.Delimiter)
165 chunkList = NewChunkList(cache, func(item *Item, data []byte) bool {
166 if nthTransformer == nil {
167 item.text, item.colors = ansiProcessor(data)
168 } else {
169 transformItem(item, data, nthTransformer, itemIndex)
170 }
171 item.text.Index = itemIndex
172 item.origText = &data
173 itemIndex++
174 return true
175 })
176 }
177
178 // Process executor
179 executor := util.NewExecutor(opts.WithShell)
180
181 // Terminal I/O
182 var terminal *Terminal
183 var err error
184 var initialEnv []string
185 initialReload := opts.extractReloadOnStart()
186 if opts.Filter == nil {
187 terminal, err = NewTerminal(opts, eventBox, executor)
188 if err != nil {
189 return ExitError, err
190 }
191 if len(initialReload) > 0 {
192 var temps []string
193 initialReload, temps = terminal.replacePlaceholderInInitialCommand(initialReload)
194 initialEnv = terminal.environ()
195 defer removeFiles(temps)
196 }
197 }
198
199 // Reader
200 streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync && opts.Bench == 0
201 var reader *Reader
202 var ingestionStart time.Time
203 if !streamingFilter {
204 reader = NewReader(func(data []byte) bool {
205 return chunkList.Push(data)
206 }, eventBox, executor, opts.ReadZero, opts.Filter == nil)
207
208 ingestionStart = time.Now()
209 readyChan := make(chan bool)
210 go reader.ReadSource(opts.Input, opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip, initialReload, initialEnv, readyChan)
211 <-readyChan
212 }
213
214 // Matcher
215 forward := true
216 withPos := false
217 for idx := len(opts.Criteria) - 1; idx > 0; idx-- {
218 switch opts.Criteria[idx] {
219 case byChunk:
220 withPos = true
221 case byEnd:
222 forward = false
223 case byBegin:
224 forward = true
225 case byPathname:
226 withPos = true
227 forward = false
228 }
229 }
230
231 nth := opts.Nth
232 inputRevision := revision{}
233 snapshotRevision := revision{}
234 patternCache := make(map[string]*Pattern)
235 denyMutex := sync.Mutex{}
236 denylist := make(map[int32]struct{})
237 clearDenylist := func() {
238 denyMutex.Lock()
239 if len(denylist) > 0 {
240 patternCache = make(map[string]*Pattern)
241 }
242 denylist = make(map[int32]struct{})
243 denyMutex.Unlock()
244 }
245 if opts.HeaderLines > math.MaxInt32 {
246 opts.HeaderLines = math.MaxInt32
247 }
248 headerLines := int32(opts.HeaderLines)
249 headerUpdated := false
250 patternBuilder := func(runes []rune) *Pattern {
251 denyMutex.Lock()
252 denylistCopy := maps.Clone(denylist)
253 denyMutex.Unlock()
254 return BuildPattern(cache, patternCache,
255 opts.Fuzzy, opts.FuzzyAlgo, opts.Extended, opts.Case, opts.Normalize, forward, withPos,
256 opts.Filter == nil, nth, opts.Delimiter, inputRevision, runes, denylistCopy, headerLines)
257 }
258 matcher := NewMatcher(cache, patternBuilder, sort, opts.Tac, eventBox, inputRevision, opts.Threads)
259
260 // Filtering mode
261 if opts.Filter != nil {
262 if opts.PrintQuery {
263 opts.Printer(*opts.Filter)
264 }
265
266 pattern := patternBuilder([]rune(*opts.Filter))
267 matcher.sort = pattern.sortable
268
269 transformer := buildItemTransformer(opts)
270
271 found := false
272 if streamingFilter {
273 slab := util.MakeSlab(slab16Size, slab32Size)
274 mutex := sync.Mutex{}
275 reader := NewReader(
276 func(runes []byte) bool {
277 item := Item{}
278 if chunkList.trans(&item, runes) {
279 if item.Index() < headerLines {
280 return false
281 }
282 mutex.Lock()
283 if result, _, _ := pattern.MatchItem(&item, false, slab); result.item != nil {
284 opts.Printer(transformer(&item))
285 found = true
286 }
287 mutex.Unlock()
288 }
289 return false
290 }, eventBox, executor, opts.ReadZero, false)
291 reader.ReadSource(opts.Input, opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip, initialReload, initialEnv, nil)
292 } else {
293 eventBox.Unwatch(EvtReadNew)
294 eventBox.WaitFor(EvtReadFin)
295 ingestionTime := time.Since(ingestionStart)
296
297 // NOTE: Streaming filter is inherently not compatible with --tail
298 snapshot, _, _ := chunkList.Snapshot(opts.Tail)
299
300 if opts.Bench > 0 {
301 // Benchmark mode: repeat scan for the given duration
302 totalItems := CountItems(snapshot)
303 var matchCount int
304 var times []time.Duration
305 deadline := time.Now().Add(opts.Bench)
306 for time.Now().Before(deadline) {
307 cache.Clear()
308 start := time.Now()
309 result := matcher.scan(MatchRequest{
310 chunks: snapshot,
311 pattern: pattern})
312 times = append(times, time.Since(start))
313 matchCount = result.merger.Length()
314 }
315 // Print stats
316 var total time.Duration
317 minD, maxD := times[0], times[0]
318 for _, d := range times {
319 total += d
320 if d < minD {
321 minD = d
322 }
323 if d > maxD {
324 maxD = d
325 }
326 }
327 avg := total / time.Duration(len(times))
328 selectivity := float64(matchCount) / float64(totalItems) * 100
329 fmt.Printf(" %d iterations avg: %.2fms min: %.2fms max: %.2fms total: %.2fs items: %d matches: %d (%.2f%%) ingestion: %.2fms\n",
330 len(times),
331 float64(avg.Microseconds())/1000,
332 float64(minD.Microseconds())/1000,
333 float64(maxD.Microseconds())/1000,
334 total.Seconds(),
335 totalItems, matchCount, selectivity,
336 float64(ingestionTime.Microseconds())/1000)
337 return ExitOk, nil
338 }
339
340 result := matcher.scan(MatchRequest{
341 chunks: snapshot,
342 pattern: pattern})
343 for i := 0; i < result.merger.Length(); i++ {
344 opts.Printer(transformer(result.merger.Get(i).item))
345 found = true
346 }
347 }
348 if found {
349 return ExitOk, nil
350 }
351 return ExitNoMatch, nil
352 }
353
354 // Synchronous search
355 if opts.Sync {
356 eventBox.Unwatch(EvtReadNew)
357 eventBox.WaitFor(EvtReadFin)
358 }
359
360 // Go interactive
361 go matcher.Loop()
362 defer matcher.Stop()
363
364 // Handling adaptive height
365 maxFit := 0 // Maximum number of items that can fit on screen
366 padHeight := 0
367 heightUnknown := opts.Height.auto
368 if heightUnknown {
369 maxFit, padHeight = terminal.MaxFitAndPad()
370 }
371 deferred := opts.Select1 || opts.Exit0 || opts.Sync
372 go terminal.Loop()
373 if !deferred && !heightUnknown {
374 // Start right away
375 terminal.startChan <- fitpad{-1, -1}
376 }
377
378 // Event coordination
379 reading := true
380 ticks := 0
381 startTick := 0
382 var nextCommand *commandSpec
383 var nextEnviron []string
384 eventBox.Watch(EvtReadNew)
385 total := 0
386 query := []rune{}
387 determine := func(final bool) {
388 if heightUnknown {
389 items := max(0, total-int(headerLines))
390 if items >= maxFit || final {
391 deferred = false
392 heightUnknown = false
393 terminal.startChan <- fitpad{min(items, maxFit), padHeight}
394 }
395 } else if deferred {
396 deferred = false
397 terminal.startChan <- fitpad{-1, -1}
398 }
399 }
400
401 useSnapshot := false
402 var snapshot []*Chunk
403 var count int
404 restart := func(command commandSpec, environ []string) {
405 if !useSnapshot {
406 clearDenylist()
407 }
408 reading = true
409 headerUpdated = false
410 startTick = ticks
411 chunkList.Clear()
412 itemIndex = 0
413 inputRevision.bumpMajor()
414 readyChan := make(chan bool)
415 go reader.restart(command, environ, readyChan)
416 <-readyChan
417 }
418
419 exitCode := ExitOk
420 stop := false
421 for {
422 delay := true
423 ticks++
424 input := func() []rune {
425 paused, input := terminal.Input()
426 if !paused {
427 query = input
428 }
429 return query
430 }
431 eventBox.Wait(func(events *util.Events) {
432 if _, fin := (*events)[EvtReadFin]; fin {
433 delete(*events, EvtReadNew)
434 }
435 for evt, value := range *events {
436 switch evt {
437 case EvtQuit:
438 if reading {
439 reader.terminate()
440 }
441 quitSignal := value.(quitSignal)
442 exitCode = quitSignal.code
443 err = quitSignal.err
444 stop = true
445 return
446 case EvtReadNew, EvtReadFin:
447 if evt == EvtReadFin && nextCommand != nil {
448 restart(*nextCommand, nextEnviron)
449 nextCommand = nil
450 nextEnviron = nil
451 break
452 } else {
453 reading = reading && evt == EvtReadNew
454 }
455 if useSnapshot && evt == EvtReadFin { // reload-sync
456 clearDenylist()
457 useSnapshot = false
458 }
459 if !useSnapshot {
460 if !snapshotRevision.compatible(inputRevision) {
461 query = []rune{}
462 }
463 var changed bool
464 snapshot, count, changed = chunkList.Snapshot(opts.Tail)
465 if changed {
466 inputRevision.bumpMinor()
467 }
468 snapshotRevision = inputRevision
469 }
470 total = count
471 terminal.UpdateCount(max(0, total-int(headerLines)), !reading, value.(*string))
472 if headerLines > 0 && !headerUpdated {
473 terminal.UpdateHeader(GetItems(snapshot, int(headerLines)))
474 headerUpdated = total >= int(headerLines)
475 }
476 if heightUnknown && !deferred {
477 determine(!reading)
478 }
479 if !useSnapshot || evt == EvtReadFin {
480 matcher.Reset(snapshot, input(), false, !reading, sort, snapshotRevision)
481 }
482
483 case EvtSearchNew:
484 var command *commandSpec
485 var environ []string
486 var changed bool
487 headerLinesChanged := false
488 withNthChanged := false
489 switch val := value.(type) {
490 case searchRequest:
491 sort = val.sort
492 command = val.command
493 environ = val.environ
494 changed = val.changed
495 bump := false
496 if len(val.denylist) > 0 && val.revision.compatible(inputRevision) {
497 denyMutex.Lock()
498 for _, itemIndex := range val.denylist {
499 denylist[itemIndex] = struct{}{}
500 }
501 denyMutex.Unlock()
502 bump = true
503 }
504 if val.nth != nil {
505 // Change nth and clear caches
506 nth = *val.nth
507 bump = true
508 }
509 if val.headerLines != nil {
510 headerLines = int32(*val.headerLines)
511 headerUpdated = false
512 headerLinesChanged = true
513 bump = true
514 }
515 if val.withNth != nil {
516 newTransformer := val.withNth.fn
517 // Cancel any in-flight scan and block the terminal from reading
518 // items before mutating them in-place. Snapshot shares middle
519 // chunk pointers, so the matcher and terminal can race with us.
520 matcher.CancelScan()
521 terminal.PauseRendering()
522 // Reset cross-line ANSI state before re-processing all items
523 lineAnsiState = nil
524 prevLineAnsiState = nil
525 chunkList.ForEachItem(func(item *Item) {
526 origBytes := *item.origText
527 savedIndex := item.Index()
528 if newTransformer != nil {
529 transformItem(item, origBytes, newTransformer, savedIndex)
530 } else {
531 item.text, item.colors = ansiProcessor(origBytes)
532 }
533 item.text.Index = savedIndex
534 item.transformed = nil
535 }, func() {
536 nthTransformer = newTransformer
537 })
538 terminal.ResumeRendering()
539 matcher.ResumeScan()
540 withNthChanged = true
541 bump = true
542 }
543 if bump {
544 patternCache = make(map[string]*Pattern)
545 cache.Clear()
546 inputRevision.bumpMinor()
547 }
548 if command != nil {
549 useSnapshot = val.sync
550 }
551 }
552 if command != nil {
553 if reading {
554 reader.terminate()
555 nextCommand = command
556 nextEnviron = environ
557 } else {
558 restart(*command, environ)
559 }
560 }
561 if !changed {
562 break
563 }
564 if !useSnapshot {
565 newSnapshot, newCount, changed := chunkList.Snapshot(opts.Tail)
566 if changed {
567 inputRevision.bumpMinor()
568 }
569 // We want to avoid showing empty list when reload is triggered
570 // and the query string is changed at the same time i.e. command != nil && changed
571 if command == nil || newCount > 0 {
572 if snapshotRevision != inputRevision {
573 query = []rune{}
574 }
575 snapshot = newSnapshot
576 snapshotRevision = inputRevision
577 }
578 }
579 if headerLinesChanged {
580 terminal.UpdateCount(max(0, total-int(headerLines)), !reading, nil)
581 if headerLines > 0 {
582 terminal.UpdateHeader(GetItems(snapshot, int(headerLines)))
583 } else {
584 terminal.UpdateHeader(nil)
585 }
586 } else if withNthChanged && headerLines > 0 {
587 terminal.UpdateHeader(GetItems(snapshot, int(headerLines)))
588 }
589 matcher.Reset(snapshot, input(), true, !reading, sort, snapshotRevision)
590 delay = false
591
592 case EvtSearchProgress:
593 switch val := value.(type) {
594 case float32:
595 terminal.UpdateProgress(val)
596 }
597
598 case EvtSearchFin:
599 switch val := value.(type) {
600 case MatchResult:
601 merger := val.merger
602 if deferred {
603 count := merger.Length()
604 if opts.Select1 && count > 1 || opts.Exit0 && !opts.Select1 && count > 0 {
605 determine(merger.final)
606 } else if merger.final {
607 if opts.Exit0 && count == 0 || opts.Select1 && count == 1 {
608 if opts.PrintQuery {
609 opts.Printer(opts.Query)
610 }
611 if len(opts.Expect) > 0 {
612 opts.Printer("")
613 }
614 transformer := buildItemTransformer(opts)
615 for i := range count {
616 opts.Printer(transformer(merger.Get(i).item))
617 }
618 if count == 0 {
619 exitCode = ExitNoMatch
620 }
621 stop = true
622 return
623 }
624 determine(merger.final)
625 }
626 }
627 terminal.UpdateList(val)
628 }
629 }
630 }
631 events.Clear()
632 })
633 if stop {
634 break
635 }
636 if delay && reading {
637 dur := util.Constrain(
638 time.Duration(ticks-startTick)*coordinatorDelayStep,
639 0, coordinatorDelayMax)
640 time.Sleep(dur)
641 }
642 }
643 return exitCode, err
644 }