core.go
This file
Path
src/core.go
644 lines · 16.8 KiB · Go
Last changed by
Address code scanning alertsJunegunn Choibefore adoption25868a6
History of this fileTake it
The walk stopped after 200 commits: lines older than 76efddd point at it.
bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 1–6why, one step back1// Package fzf implements fzf, a command-line fuzzy finder.2package fzf34import (5 "fmt"6 "maps"Address code scanning alertsJunegunn Choibefore adoption25868a6
line 7why, one step back7 "math"bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 8–59why, one step back8 "os"9 "sync"10 "time"1112 "github.com/junegunn/fzf/src/tui"13 "github.com/junegunn/fzf/src/util"14)1516/*17Reader -> EvtReadFin18Reader -> EvtReadNew -> Matcher (restart)19Terminal -> EvtSearchNew:bool -> Matcher (restart)20Matcher -> EvtSearchProgress -> Terminal (update info)21Matcher -> EvtSearchFin -> Terminal (update list)22*/2324type revision struct {25 major int26 minor int27}2829func (r *revision) bumpMajor() {30 r.major++31 r.minor = 032}3334func (r *revision) bumpMinor() {35 r.minor++36}3738func (r revision) compatible(other revision) bool {39 return r.major == other.major40}4142func 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}5354// Run starts fzf55func Run(opts *Options) (int, error) {56 if opts.Filter == nil {57 if opts.useTmux() {58 return runTmux(os.Args, opts)59 }Support zellij floating pane via --popup (new name for --tmux) (#4145)Junegunn Choibefore adoption6f17d49
lines 60–62why, one step back60 if opts.useZellij() {61 return runZellij(os.Args, opts)62 }bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 63–244why, one step back6364 if needWinpty(opts) {65 return runWinpty(os.Args, opts)66 }67 }6869 if err := postProcessOptions(opts); err != nil {70 return ExitError, err71 }7273 defer util.RunAtExitFuncs()7475 // Output channel given76 if opts.Output != nil {77 opts.Printer = func(str string) {78 opts.Output <- str79 }80 }8182 sort := opts.Sort > 083 sortCriteria = opts.Criteria8485 // Event channel86 eventBox := util.NewEventBox()8788 // ANSI code processor89 ansiProcessor := func(data []byte) (util.Chars, *[]ansiOffset) {90 return util.ToChars(data), nil91 }9293 var lineAnsiState, prevLineAnsiState *ansiState94 if opts.Ansi {95 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {96 prevLineAnsiState = lineAnsiState97 trimmed, offsets, newState := extractColor(byteString(data), lineAnsiState, nil)98 lineAnsiState = newState99100 // 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.lbg105 marker.color.attr = marker.color.attr | tui.FullBg106 newOffsets := append(*offsets, marker)107 offsets = &newOffsets108109 // Reset the full-line background color110 lineAnsiState.lbg = -1111 }112 return util.ToChars(stringBytes(trimmed)), offsets113 }114 }115116 // Chunk list117 cache := NewChunkCache()118 var chunkList *ChunkList119 var itemIndex int32120 // 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 *ansiState126 if prevLineAnsiState != nil {127 ansiStateDup := *prevLineAnsiState128 ansiState = &ansiStateDup129 }130 for _, token := range tokens {131 prevAnsiState := ansiState132 _, _, 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))142143 // We should not trim trailing whitespaces with background colors144 var maxColorOffset int32145 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 }154155 var nthTransformer func([]Token, int32) string156 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 = itemIndex160 itemIndex++161 return true162 })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 = itemIndex172 item.origText = &data173 itemIndex++174 return true175 })176 }177178 // Process executor179 executor := util.NewExecutor(opts.WithShell)180181 // Terminal I/O182 var terminal *Terminal183 var err error184 var initialEnv []string185 initialReload := opts.extractReloadOnStart()186 if opts.Filter == nil {187 terminal, err = NewTerminal(opts, eventBox, executor)188 if err != nil {189 return ExitError, err190 }191 if len(initialReload) > 0 {192 var temps []string193 initialReload, temps = terminal.replacePlaceholderInInitialCommand(initialReload)194 initialEnv = terminal.environ()195 defer removeFiles(temps)196 }197 }198199 // Reader200 streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync && opts.Bench == 0201 var reader *Reader202 var ingestionStart time.Time203 if !streamingFilter {204 reader = NewReader(func(data []byte) bool {205 return chunkList.Push(data)206 }, eventBox, executor, opts.ReadZero, opts.Filter == nil)207208 ingestionStart = time.Now()209 readyChan := make(chan bool)210 go reader.ReadSource(opts.Input, opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip, initialReload, initialEnv, readyChan)211 <-readyChan212 }213214 // Matcher215 forward := true216 withPos := false217 for idx := len(opts.Criteria) - 1; idx > 0; idx-- {218 switch opts.Criteria[idx] {219 case byChunk:220 withPos = true221 case byEnd:222 forward = false223 case byBegin:224 forward = true225 case byPathname:226 withPos = true227 forward = false228 }229 }230231 nth := opts.Nth232 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 }Address code scanning alertsJunegunn Choibefore adoption25868a6
lines 245–247why, one step back245 if opts.HeaderLines > math.MaxInt32 {246 opts.HeaderLines = math.MaxInt32247 }bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 248–473why, one step back248 headerLines := int32(opts.HeaderLines)249 headerUpdated := false250 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)259260 // Filtering mode261 if opts.Filter != nil {262 if opts.PrintQuery {263 opts.Printer(*opts.Filter)264 }265266 pattern := patternBuilder([]rune(*opts.Filter))267 matcher.sort = pattern.sortable268269 transformer := buildItemTransformer(opts)270271 found := false272 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 false281 }282 mutex.Lock()283 if result, _, _ := pattern.MatchItem(&item, false, slab); result.item != nil {284 opts.Printer(transformer(&item))285 found = true286 }287 mutex.Unlock()288 }289 return false290 }, 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)296297 // NOTE: Streaming filter is inherently not compatible with --tail298 snapshot, _, _ := chunkList.Snapshot(opts.Tail)299300 if opts.Bench > 0 {301 // Benchmark mode: repeat scan for the given duration302 totalItems := CountItems(snapshot)303 var matchCount int304 var times []time.Duration305 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 stats316 var total time.Duration317 minD, maxD := times[0], times[0]318 for _, d := range times {319 total += d320 if d < minD {321 minD = d322 }323 if d > maxD {324 maxD = d325 }326 }327 avg := total / time.Duration(len(times))328 selectivity := float64(matchCount) / float64(totalItems) * 100329 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, nil338 }339340 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 = true346 }347 }348 if found {349 return ExitOk, nil350 }351 return ExitNoMatch, nil352 }353354 // Synchronous search355 if opts.Sync {356 eventBox.Unwatch(EvtReadNew)357 eventBox.WaitFor(EvtReadFin)358 }359360 // Go interactive361 go matcher.Loop()362 defer matcher.Stop()363364 // Handling adaptive height365 maxFit := 0 // Maximum number of items that can fit on screen366 padHeight := 0367 heightUnknown := opts.Height.auto368 if heightUnknown {369 maxFit, padHeight = terminal.MaxFitAndPad()370 }371 deferred := opts.Select1 || opts.Exit0 || opts.Sync372 go terminal.Loop()373 if !deferred && !heightUnknown {374 // Start right away375 terminal.startChan <- fitpad{-1, -1}376 }377378 // Event coordination379 reading := true380 ticks := 0381 startTick := 0382 var nextCommand *commandSpec383 var nextEnviron []string384 eventBox.Watch(EvtReadNew)385 total := 0386 query := []rune{}387 determine := func(final bool) {388 if heightUnknown {389 items := max(0, total-int(headerLines))390 if items >= maxFit || final {391 deferred = false392 heightUnknown = false393 terminal.startChan <- fitpad{min(items, maxFit), padHeight}394 }395 } else if deferred {396 deferred = false397 terminal.startChan <- fitpad{-1, -1}398 }399 }400401 useSnapshot := false402 var snapshot []*Chunk403 var count int404 restart := func(command commandSpec, environ []string) {405 if !useSnapshot {406 clearDenylist()407 }408 reading = true409 headerUpdated = false410 startTick = ticks411 chunkList.Clear()412 itemIndex = 0413 inputRevision.bumpMajor()414 readyChan := make(chan bool)415 go reader.restart(command, environ, readyChan)416 <-readyChan417 }418419 exitCode := ExitOk420 stop := false421 for {422 delay := true423 ticks++424 input := func() []rune {425 paused, input := terminal.Input()426 if !paused {427 query = input428 }429 return query430 }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.code443 err = quitSignal.err444 stop = true445 return446 case EvtReadNew, EvtReadFin:447 if evt == EvtReadFin && nextCommand != nil {448 restart(*nextCommand, nextEnviron)449 nextCommand = nil450 nextEnviron = nil451 break452 } else {453 reading = reading && evt == EvtReadNew454 }455 if useSnapshot && evt == EvtReadFin { // reload-sync456 clearDenylist()457 useSnapshot = false458 }459 if !useSnapshot {460 if !snapshotRevision.compatible(inputRevision) {461 query = []rune{}462 }463 var changed bool464 snapshot, count, changed = chunkList.Snapshot(opts.Tail)465 if changed {466 inputRevision.bumpMinor()467 }468 snapshotRevision = inputRevision469 }470 total = count471 terminal.UpdateCount(max(0, total-int(headerLines)), !reading, value.(*string))472 if headerLines > 0 && !headerUpdated {473 terminal.UpdateHeader(GetItems(snapshot, int(headerLines)))Address code scanning alertsJunegunn Choibefore adoption25868a6
line 474why, one step back474 headerUpdated = total >= int(headerLines)bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 475–644why, one step back475 }476 if heightUnknown && !deferred {477 determine(!reading)478 }479 if !useSnapshot || evt == EvtReadFin {480 matcher.Reset(snapshot, input(), false, !reading, sort, snapshotRevision)481 }482483 case EvtSearchNew:484 var command *commandSpec485 var environ []string486 var changed bool487 headerLinesChanged := false488 withNthChanged := false489 switch val := value.(type) {490 case searchRequest:491 sort = val.sort492 command = val.command493 environ = val.environ494 changed = val.changed495 bump := false496 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 = true503 }504 if val.nth != nil {505 // Change nth and clear caches506 nth = *val.nth507 bump = true508 }509 if val.headerLines != nil {510 headerLines = int32(*val.headerLines)511 headerUpdated = false512 headerLinesChanged = true513 bump = true514 }515 if val.withNth != nil {516 newTransformer := val.withNth.fn517 // Cancel any in-flight scan and block the terminal from reading518 // items before mutating them in-place. Snapshot shares middle519 // 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 items523 lineAnsiState = nil524 prevLineAnsiState = nil525 chunkList.ForEachItem(func(item *Item) {526 origBytes := *item.origText527 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 = savedIndex534 item.transformed = nil535 }, func() {536 nthTransformer = newTransformer537 })538 terminal.ResumeRendering()539 matcher.ResumeScan()540 withNthChanged = true541 bump = true542 }543 if bump {544 patternCache = make(map[string]*Pattern)545 cache.Clear()546 inputRevision.bumpMinor()547 }548 if command != nil {549 useSnapshot = val.sync550 }551 }552 if command != nil {553 if reading {554 reader.terminate()555 nextCommand = command556 nextEnviron = environ557 } else {558 restart(*command, environ)559 }560 }561 if !changed {562 break563 }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 triggered570 // and the query string is changed at the same time i.e. command != nil && changed571 if command == nil || newCount > 0 {572 if snapshotRevision != inputRevision {573 query = []rune{}574 }575 snapshot = newSnapshot576 snapshotRevision = inputRevision577 }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 = false591592 case EvtSearchProgress:593 switch val := value.(type) {594 case float32:595 terminal.UpdateProgress(val)596 }597598 case EvtSearchFin:599 switch val := value.(type) {600 case MatchResult:601 merger := val.merger602 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 = ExitNoMatch620 }621 stop = true622 return623 }624 determine(merger.final)625 }626 }627 terminal.UpdateList(val)628 }629 }630 }631 events.Clear()632 })633 if stop {634 break635 }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, err644}