Skip to content
Myr

core.go

This file

Path

src/core.go

518 lines · 12.9 KiB · Go

Last changed by

Trim trailing whitespaces after processing ANSI sequencesJunegunn Choibefore adoption6392538

History of this file

Take it

The walk stopped after 200 commits: lines older than 3b0f976 point at it.

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 1–98why, one step back
1// Package fzf implements fzf, a command-line fuzzy finder.
2package fzf34import (5 "os"6 "sync"7 "time"89 "github.com/junegunn/fzf/src/util"10)1112/*13Reader -> EvtReadFin14Reader -> EvtReadNew -> Matcher (restart)15Terminal -> EvtSearchNew:bool -> Matcher (restart)16Matcher -> EvtSearchProgress -> Terminal (update info)17Matcher -> EvtSearchFin -> Terminal (update list)18Matcher -> EvtHeader -> Terminal (update header)19*/2021type revision struct {22 major int23 minor int24}2526func (r *revision) bumpMajor() {27 r.major++28 r.minor = 029}3031func (r *revision) bumpMinor() {32 r.minor++33}3435func (r revision) compatible(other revision) bool {36 return r.major == other.major37}3839// Run starts fzf40func Run(opts *Options) (int, error) {41 if opts.Filter == nil {42 if opts.Tmux != nil && len(os.Getenv("TMUX")) > 0 && opts.Tmux.index >= opts.Height.index {43 return runTmux(os.Args, opts)44 }4546 if needWinpty(opts) {47 return runWinpty(os.Args, opts)48 }49 }5051 if err := postProcessOptions(opts); err != nil {52 return ExitError, err53 }5455 defer util.RunAtExitFuncs()5657 // Output channel given58 if opts.Output != nil {59 opts.Printer = func(str string) {60 opts.Output <- str61 }62 }6364 sort := opts.Sort > 065 sortCriteria = opts.Criteria6667 // Event channel68 eventBox := util.NewEventBox()6970 // ANSI code processor71 ansiProcessor := func(data []byte) (util.Chars, *[]ansiOffset) {72 return util.ToChars(data), nil73 }7475 var lineAnsiState, prevLineAnsiState *ansiState76 if opts.Ansi {77 if opts.Theme.Colored {78 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {79 prevLineAnsiState = lineAnsiState80 trimmed, offsets, newState := extractColor(byteString(data), lineAnsiState, nil)81 lineAnsiState = newState82 return util.ToChars(stringBytes(trimmed)), offsets83 }84 } else {85 // When color is disabled but ansi option is given,86 // we simply strip out ANSI codes from the input87 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {88 trimmed, _, _ := extractColor(byteString(data), nil, nil)89 return util.ToChars(stringBytes(trimmed)), nil90 }91 }92 }9394 // Chunk list95 cache := NewChunkCache()96 var chunkList *ChunkList97 var itemIndex int3298 header := make([]string, 0, opts.HeaderLines)

Make --accept-nth and --with-nth support templatesJunegunn Choibefore adoption84e2262

line 99why, one step back
99 if opts.WithNth == nil {

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 100–111why, one step back
100 chunkList = NewChunkList(cache, func(item *Item, data []byte) bool {
101 if len(header) < opts.HeaderLines {102 header = append(header, byteString(data))103 eventBox.Set(EvtHeader, header)104 return false105 }106 item.text, item.colors = ansiProcessor(data)107 item.text.Index = itemIndex108 itemIndex++109 return true110 })111 } else {

Make --accept-nth and --with-nth support templatesJunegunn Choibefore adoption84e2262

line 112why, one step back
112 nthTransformer := opts.WithNth(opts.Delimiter)

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 113–130why, one step back
113 chunkList = NewChunkList(cache, func(item *Item, data []byte) bool {
114 tokens := Tokenize(byteString(data), opts.Delimiter)115 if opts.Ansi && opts.Theme.Colored && len(tokens) > 1 {116 var ansiState *ansiState117 if prevLineAnsiState != nil {118 ansiStateDup := *prevLineAnsiState119 ansiState = &ansiStateDup120 }121 for _, token := range tokens {122 prevAnsiState := ansiState123 _, _, ansiState = extractColor(token.text.ToString(), ansiState, nil)124 if prevAnsiState != nil {125 token.text.Prepend("\x1b[m" + prevAnsiState.ToString())126 } else {127 token.text.Prepend("\x1b[m")128 }129 }130 }

Add support for {n} in --with-nth and --accept-nth templatesJunegunn Choibefore adoption461115a

line 131why, one step back
131 transformed := nthTransformer(tokens, itemIndex)

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 132–137why, one step back
132 if len(header) < opts.HeaderLines {
133 header = append(header, transformed)134 eventBox.Set(EvtHeader, header)135 return false136 }137 item.text, item.colors = ansiProcessor(stringBytes(transformed))

Trim trailing whitespaces after processing ANSI sequencesJunegunn Choibefore adoption6392538

line 138why, one step back
138 item.text.TrimTrailingWhitespaces()

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 139–190why, one step back
139 item.text.Index = itemIndex
140 item.origText = &data141 itemIndex++142 return true143 })144 }145146 // Process executor147 executor := util.NewExecutor(opts.WithShell)148149 // Terminal I/O150 var terminal *Terminal151 var err error152 var initialEnv []string153 initialReload := opts.extractReloadOnStart()154 if opts.Filter == nil {155 terminal, err = NewTerminal(opts, eventBox, executor)156 if err != nil {157 return ExitError, err158 }159 if len(initialReload) > 0 {160 var temps []string161 initialReload, temps = terminal.replacePlaceholderInInitialCommand(initialReload)162 initialEnv = terminal.environ()163 defer removeFiles(temps)164 }165 }166167 // Reader168 streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync169 var reader *Reader170 if !streamingFilter {171 reader = NewReader(func(data []byte) bool {172 return chunkList.Push(data)173 }, eventBox, executor, opts.ReadZero, opts.Filter == nil)174175 readyChan := make(chan bool)176 go reader.ReadSource(opts.Input, opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip, initialReload, initialEnv, readyChan)177 <-readyChan178 }179180 // Matcher181 forward := true182 withPos := false183 for idx := len(opts.Criteria) - 1; idx > 0; idx-- {184 switch opts.Criteria[idx] {185 case byChunk:186 withPos = true187 case byEnd:188 forward = false189 case byBegin:190 forward = true

Option to prioritize file name matches (#4192)Junegunn Choibefore adoption243a760

lines 191–193why, one step back
191 case byPathname:
192 withPos = true193 forward = false

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 194–195why, one step back
194 }
195 }

Add change-nth actionJunegunn Choibefore adoptiond83eb28

lines 196–197why, one step back
196
197 nth := opts.Nth

Fix nth highlightingJunegunn Choibefore adoption62e0a28

lines 198–199why, one step back
198 inputRevision := revision{}
199 snapshotRevision := revision{}

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

line 200why, one step back
200 patternCache := make(map[string]*Pattern)

Add 'exclude' action for excluding current/selected items from the result (#4231)Junegunn Choibefore adoption67dd7e1

lines 201–210why, one step back
201 denyMutex := sync.Mutex{}
202 denylist := make(map[int32]struct{})203 clearDenylist := func() {204 denyMutex.Lock()205 if len(denylist) > 0 {206 patternCache = make(map[string]*Pattern)207 }208 denylist = make(map[int32]struct{})209 denyMutex.Unlock()210 }

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

line 211why, one step back
211 patternBuilder := func(runes []rune) *Pattern {

Add 'exclude' action for excluding current/selected items from the result (#4231)Junegunn Choibefore adoption67dd7e1

lines 212–217why, one step back
212 denyMutex.Lock()
213 denylistCopy := make(map[int32]struct{})214 for k, v := range denylist {215 denylistCopy[k] = v216 }217 denyMutex.Unlock()

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 218–219why, one step back
218 return BuildPattern(cache, patternCache,
219 opts.Fuzzy, opts.FuzzyAlgo, opts.Extended, opts.Case, opts.Normalize, forward, withPos,

Add 'exclude' action for excluding current/selected items from the result (#4231)Junegunn Choibefore adoption67dd7e1

line 220why, one step back
220 opts.Filter == nil, nth, opts.Delimiter, inputRevision, runes, denylistCopy)

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 221–319why, one step back
221 }
222 matcher := NewMatcher(cache, patternBuilder, sort, opts.Tac, eventBox, inputRevision)223224 // Filtering mode225 if opts.Filter != nil {226 if opts.PrintQuery {227 opts.Printer(*opts.Filter)228 }229230 pattern := patternBuilder([]rune(*opts.Filter))231 matcher.sort = pattern.sortable232233 found := false234 if streamingFilter {235 slab := util.MakeSlab(slab16Size, slab32Size)236 mutex := sync.Mutex{}237 reader := NewReader(238 func(runes []byte) bool {239 item := Item{}240 if chunkList.trans(&item, runes) {241 mutex.Lock()242 if result, _, _ := pattern.MatchItem(&item, false, slab); result != nil {243 opts.Printer(item.text.ToString())244 found = true245 }246 mutex.Unlock()247 }248 return false249 }, eventBox, executor, opts.ReadZero, false)250 reader.ReadSource(opts.Input, opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip, initialReload, initialEnv, nil)251 } else {252 eventBox.Unwatch(EvtReadNew)253 eventBox.WaitFor(EvtReadFin)254255 // NOTE: Streaming filter is inherently not compatible with --tail256 snapshot, _, _ := chunkList.Snapshot(opts.Tail)257 merger, _ := matcher.scan(MatchRequest{258 chunks: snapshot,259 pattern: pattern})260 for i := 0; i < merger.Length(); i++ {261 opts.Printer(merger.Get(i).item.AsString(opts.Ansi))262 found = true263 }264 }265 if found {266 return ExitOk, nil267 }268 return ExitNoMatch, nil269 }270271 // Synchronous search272 if opts.Sync {273 eventBox.Unwatch(EvtReadNew)274 eventBox.WaitFor(EvtReadFin)275 }276277 // Go interactive278 go matcher.Loop()279 defer matcher.Stop()280281 // Handling adaptive height282 maxFit := 0 // Maximum number of items that can fit on screen283 padHeight := 0284 heightUnknown := opts.Height.auto285 if heightUnknown {286 maxFit, padHeight = terminal.MaxFitAndPad()287 }288 deferred := opts.Select1 || opts.Exit0 || opts.Sync289 go terminal.Loop()290 if !deferred && !heightUnknown {291 // Start right away292 terminal.startChan <- fitpad{-1, -1}293 }294295 // Event coordination296 reading := true297 ticks := 0298 var nextCommand *commandSpec299 var nextEnviron []string300 eventBox.Watch(EvtReadNew)301 total := 0302 query := []rune{}303 determine := func(final bool) {304 if heightUnknown {305 if total >= maxFit || final {306 deferred = false307 heightUnknown = false308 terminal.startChan <- fitpad{util.Min(total, maxFit), padHeight}309 }310 } else if deferred {311 deferred = false312 terminal.startChan <- fitpad{-1, -1}313 }314 }315316 useSnapshot := false317 var snapshot []*Chunk318 var count int319 restart := func(command commandSpec, environ []string) {

Add 'exclude' action for excluding current/selected items from the result (#4231)Junegunn Choibefore adoption67dd7e1

lines 320–322why, one step back
320 if !useSnapshot {
321 clearDenylist()322 }

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 323–368why, one step back
323 reading = true
324 chunkList.Clear()325 itemIndex = 0326 inputRevision.bumpMajor()327 header = make([]string, 0, opts.HeaderLines)328 readyChan := make(chan bool)329 go reader.restart(command, environ, readyChan)330 <-readyChan331 }332333 exitCode := ExitOk334 stop := false335 for {336 delay := true337 ticks++338 input := func() []rune {339 paused, input := terminal.Input()340 if !paused {341 query = input342 }343 return query344 }345 eventBox.Wait(func(events *util.Events) {346 if _, fin := (*events)[EvtReadFin]; fin {347 delete(*events, EvtReadNew)348 }349 for evt, value := range *events {350 switch evt {351 case EvtQuit:352 if reading {353 reader.terminate()354 }355 quitSignal := value.(quitSignal)356 exitCode = quitSignal.code357 err = quitSignal.err358 stop = true359 return360 case EvtReadNew, EvtReadFin:361 if evt == EvtReadFin && nextCommand != nil {362 restart(*nextCommand, nextEnviron)363 nextCommand = nil364 nextEnviron = nil365 break366 } else {367 reading = reading && evt == EvtReadNew368 }

Add 'exclude' action for excluding current/selected items from the result (#4231)Junegunn Choibefore adoption67dd7e1

lines 369–370why, one step back
369 if useSnapshot && evt == EvtReadFin { // reload-sync
370 clearDenylist()

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 371–400why, one step back
371 useSnapshot = false
372 }373 if !useSnapshot {374 if !snapshotRevision.compatible(inputRevision) {375 query = []rune{}376 }377 var changed bool378 snapshot, count, changed = chunkList.Snapshot(opts.Tail)379 if changed {380 inputRevision.bumpMinor()381 }382 snapshotRevision = inputRevision383 }384 total = count385 terminal.UpdateCount(total, !reading, value.(*string))386 if heightUnknown && !deferred {387 determine(!reading)388 }389 matcher.Reset(snapshot, input(), false, !reading, sort, snapshotRevision)390391 case EvtSearchNew:392 var command *commandSpec393 var environ []string394 var changed bool395 switch val := value.(type) {396 case searchRequest:397 sort = val.sort398 command = val.command399 environ = val.environ400 changed = val.changed

Add 'exclude' action for excluding current/selected items from the result (#4231)Junegunn Choibefore adoption67dd7e1

lines 401–409why, one step back
401 bump := false
402 if len(val.denylist) > 0 && val.revision.compatible(inputRevision) {403 denyMutex.Lock()404 for _, itemIndex := range val.denylist {405 denylist[itemIndex] = struct{}{}406 }407 denyMutex.Unlock()408 bump = true409 }

Add change-nth actionJunegunn Choibefore adoptiond83eb28

lines 410–412why, one step back
410 if val.nth != nil {
411 // Change nth and clear caches412 nth = *val.nth

Add 'exclude' action for excluding current/selected items from the result (#4231)Junegunn Choibefore adoption67dd7e1

lines 413–415why, one step back
413 bump = true
414 }415 if bump {

Add change-nth actionJunegunn Choibefore adoptiond83eb28

line 416why, one step back
416 patternCache = make(map[string]*Pattern)

Fix change-nthJunegunn Choibefore adoptionba0935c

lines 417–418why, one step back
417 cache.Clear()
418 inputRevision.bumpMinor()

Add change-nth actionJunegunn Choibefore adoptiond83eb28

line 419why, one step back
419 }

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 420–479why, one step back
420 if command != nil {
421 useSnapshot = val.sync422 }423 }424 if command != nil {425 if reading {426 reader.terminate()427 nextCommand = command428 nextEnviron = environ429 } else {430 restart(*command, environ)431 }432 }433 if !changed {434 break435 }436 if !useSnapshot {437 newSnapshot, newCount, changed := chunkList.Snapshot(opts.Tail)438 if changed {439 inputRevision.bumpMinor()440 }441 // We want to avoid showing empty list when reload is triggered442 // and the query string is changed at the same time i.e. command != nil && changed443 if command == nil || newCount > 0 {444 if snapshotRevision != inputRevision {445 query = []rune{}446 }447 snapshot = newSnapshot448 snapshotRevision = inputRevision449 }450 }451 matcher.Reset(snapshot, input(), true, !reading, sort, snapshotRevision)452 delay = false453454 case EvtSearchProgress:455 switch val := value.(type) {456 case float32:457 terminal.UpdateProgress(val)458 }459460 case EvtHeader:461 headerPadded := make([]string, opts.HeaderLines)462 copy(headerPadded, value.([]string))463 terminal.UpdateHeader(headerPadded)464465 case EvtSearchFin:466 switch val := value.(type) {467 case *Merger:468 if deferred {469 count := val.Length()470 if opts.Select1 && count > 1 || opts.Exit0 && !opts.Select1 && count > 0 {471 determine(val.final)472 } else if val.final {473 if opts.Exit0 && count == 0 || opts.Select1 && count == 1 {474 if opts.PrintQuery {475 opts.Printer(opts.Query)476 }477 if len(opts.Expect) > 0 {478 opts.Printer("")479 }

Make --accept-nth compatible with --select-1Junegunn Choibefore adoption710ebdf

lines 480–488why, one step back
480 transformer := func(item *Item) string {
481 return item.AsString(opts.Ansi)482 }483 if opts.AcceptNth != nil {484 fn := opts.AcceptNth(opts.Delimiter)485 transformer = func(item *Item) string {486 return item.acceptNth(opts.Ansi, opts.Delimiter, fn)487 }488 }

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

line 489why, one step back
489 for i := 0; i < count; i++ {

Make --accept-nth compatible with --select-1Junegunn Choibefore adoption710ebdf

line 490why, one step back
490 opts.Printer(transformer(val.Get(i).item))

[fish] Enable home dir expansion of leading ~/bitraidbefore adoption3b0f976

lines 491–518why, one step back
491 }
492 if count == 0 {493 exitCode = ExitNoMatch494 }495 stop = true496 return497 }498 determine(val.final)499 }500 }501 terminal.UpdateList(val)502 }503 }504 }505 events.Clear()506 })507 if stop {508 break509 }510 if delay && reading {511 dur := util.DurWithin(512 time.Duration(ticks)*coordinatorDelayStep,513 0, coordinatorDelayMax)514 time.Sleep(dur)515 }516 }517 return exitCode, err518}