Skip to content
Myr

core.go

This file

Path

src/core.go

344 lines · 9.0 KiB · Go

Last changed by

Merge branch 'devel' into masterJunegunn Choibefore adoption51dfacd

History of this file

Take it

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

[vim] Use cterm colors on Windows (#1793)Jan Edmund Lazobefore adoptionaa0e10e

lines 1–45why, one step back
1/*
2Package fzf implements fzf, a command-line fuzzy finder.34The MIT License (MIT)56Copyright (c) 2017 Junegunn Choi78Permission is hereby granted, free of charge, to any person obtaining a copy9of this software and associated documentation files (the "Software"), to deal10in the Software without restriction, including without limitation the rights11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell12copies of the Software, and to permit persons to whom the Software is13furnished to do so, subject to the following conditions:1415The above copyright notice and this permission notice shall be included in16all copies or substantial portions of the Software.1718THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN24THE SOFTWARE.25*/26package fzf2728import (29 "fmt"30 "os"31 "time"3233 "github.com/junegunn/fzf/src/util"34)3536/*37Reader -> EvtReadFin38Reader -> EvtReadNew -> Matcher (restart)39Terminal -> EvtSearchNew:bool -> Matcher (restart)40Matcher -> EvtSearchProgress -> Terminal (update info)41Matcher -> EvtSearchFin -> Terminal (update list)42Matcher -> EvtHeader -> Terminal (update header)43*/4445// Run starts fzf

Merge branch 'devel' into masterJunegunn Choibefore adoption51dfacd

line 46why, one step back
46func Run(opts *Options, version string, revision string) {

[vim] Use cterm colors on Windows (#1793)Jan Edmund Lazobefore adoptionaa0e10e

lines 47–68why, one step back
47 sort := opts.Sort > 0
48 sortCriteria = opts.Criteria4950 if opts.Version {51 if len(revision) > 0 {52 fmt.Printf("%s (%s)\n", version, revision)53 } else {54 fmt.Println(version)55 }56 os.Exit(exitOk)57 }5859 // Event channel60 eventBox := util.NewEventBox()6162 // ANSI code processor63 ansiProcessor := func(data []byte) (util.Chars, *[]ansiOffset) {64 return util.ToChars(data), nil65 }6667 var lineAnsiState, prevLineAnsiState *ansiState68 if opts.Ansi {

Add support for text styling using --colorJunegunn Choibefore adoption11841f6

line 69why, one step back
69 if opts.Theme.Colored {

[vim] Use cterm colors on Windows (#1793)Jan Edmund Lazobefore adoptionaa0e10e

lines 70–104why, one step back
70 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {
71 prevLineAnsiState = lineAnsiState72 trimmed, offsets, newState := extractColor(string(data), lineAnsiState, nil)73 lineAnsiState = newState74 return util.ToChars([]byte(trimmed)), offsets75 }76 } else {77 // When color is disabled but ansi option is given,78 // we simply strip out ANSI codes from the input79 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {80 trimmed, _, _ := extractColor(string(data), nil, nil)81 return util.ToChars([]byte(trimmed)), nil82 }83 }84 }8586 // Chunk list87 var chunkList *ChunkList88 var itemIndex int3289 header := make([]string, 0, opts.HeaderLines)90 if len(opts.WithNth) == 0 {91 chunkList = NewChunkList(func(item *Item, data []byte) bool {92 if len(header) < opts.HeaderLines {93 header = append(header, string(data))94 eventBox.Set(EvtHeader, header)95 return false96 }97 item.text, item.colors = ansiProcessor(data)98 item.text.Index = itemIndex99 itemIndex++100 return true101 })102 } else {103 chunkList = NewChunkList(func(item *Item, data []byte) bool {104 tokens := Tokenize(string(data), opts.Delimiter)

Add support for text styling using --colorJunegunn Choibefore adoption11841f6

line 105why, one step back
105 if opts.Ansi && opts.Theme.Colored && len(tokens) > 1 {

[vim] Use cterm colors on Windows (#1793)Jan Edmund Lazobefore adoptionaa0e10e

lines 106–298why, one step back
106 var ansiState *ansiState
107 if prevLineAnsiState != nil {108 ansiStateDup := *prevLineAnsiState109 ansiState = &ansiStateDup110 }111 for _, token := range tokens {112 prevAnsiState := ansiState113 _, _, ansiState = extractColor(token.text.ToString(), ansiState, nil)114 if prevAnsiState != nil {115 token.text.Prepend("\x1b[m" + prevAnsiState.ToString())116 } else {117 token.text.Prepend("\x1b[m")118 }119 }120 }121 trans := Transform(tokens, opts.WithNth)122 transformed := joinTokens(trans)123 if len(header) < opts.HeaderLines {124 header = append(header, transformed)125 eventBox.Set(EvtHeader, header)126 return false127 }128 item.text, item.colors = ansiProcessor([]byte(transformed))129 item.text.TrimTrailingWhitespaces()130 item.text.Index = itemIndex131 item.origText = &data132 itemIndex++133 return true134 })135 }136137 // Reader138 streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync139 var reader *Reader140 if !streamingFilter {141 reader = NewReader(func(data []byte) bool {142 return chunkList.Push(data)143 }, eventBox, opts.ReadZero, opts.Filter == nil)144 go reader.ReadSource()145 }146147 // Matcher148 forward := true149 for _, cri := range opts.Criteria[1:] {150 if cri == byEnd {151 forward = false152 break153 }154 if cri == byBegin {155 break156 }157 }158 patternBuilder := func(runes []rune) *Pattern {159 return BuildPattern(160 opts.Fuzzy, opts.FuzzyAlgo, opts.Extended, opts.Case, opts.Normalize, forward,161 opts.Filter == nil, opts.Nth, opts.Delimiter, runes)162 }163 matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox)164165 // Filtering mode166 if opts.Filter != nil {167 if opts.PrintQuery {168 opts.Printer(*opts.Filter)169 }170171 pattern := patternBuilder([]rune(*opts.Filter))172 matcher.sort = pattern.sortable173174 found := false175 if streamingFilter {176 slab := util.MakeSlab(slab16Size, slab32Size)177 reader := NewReader(178 func(runes []byte) bool {179 item := Item{}180 if chunkList.trans(&item, runes) {181 if result, _, _ := pattern.MatchItem(&item, false, slab); result != nil {182 opts.Printer(item.text.ToString())183 found = true184 }185 }186 return false187 }, eventBox, opts.ReadZero, false)188 reader.ReadSource()189 } else {190 eventBox.Unwatch(EvtReadNew)191 eventBox.WaitFor(EvtReadFin)192193 snapshot, _ := chunkList.Snapshot()194 merger, _ := matcher.scan(MatchRequest{195 chunks: snapshot,196 pattern: pattern})197 for i := 0; i < merger.Length(); i++ {198 opts.Printer(merger.Get(i).item.AsString(opts.Ansi))199 found = true200 }201 }202 if found {203 os.Exit(exitOk)204 }205 os.Exit(exitNoMatch)206 }207208 // Synchronous search209 if opts.Sync {210 eventBox.Unwatch(EvtReadNew)211 eventBox.WaitFor(EvtReadFin)212 }213214 // Go interactive215 go matcher.Loop()216217 // Terminal I/O218 terminal := NewTerminal(opts, eventBox)219 deferred := opts.Select1 || opts.Exit0220 go terminal.Loop()221 if !deferred {222 terminal.startChan <- true223 }224225 // Event coordination226 reading := true227 clearCache := util.Once(false)228 clearSelection := util.Once(false)229 ticks := 0230 var nextCommand *string231 restart := func(command string) {232 reading = true233 clearCache = util.Once(true)234 clearSelection = util.Once(true)235 chunkList.Clear()236 header = make([]string, 0, opts.HeaderLines)237 go reader.restart(command)238 }239 eventBox.Watch(EvtReadNew)240 for {241 delay := true242 ticks++243 input := func() []rune {244 if opts.Phony {245 return []rune{}246 }247 return []rune(terminal.Input())248 }249 eventBox.Wait(func(events *util.Events) {250 if _, fin := (*events)[EvtReadFin]; fin {251 delete(*events, EvtReadNew)252 }253 for evt, value := range *events {254 switch evt {255256 case EvtReadNew, EvtReadFin:257 if evt == EvtReadFin && nextCommand != nil {258 restart(*nextCommand)259 nextCommand = nil260 break261 } else {262 reading = reading && evt == EvtReadNew263 }264 snapshot, count := chunkList.Snapshot()265 terminal.UpdateCount(count, !reading, value.(*string))266 if opts.Sync {267 opts.Sync = false268 terminal.UpdateList(PassMerger(&snapshot, opts.Tac), false)269 }270 matcher.Reset(snapshot, input(), false, !reading, sort, clearCache())271272 case EvtSearchNew:273 var command *string274 switch val := value.(type) {275 case searchRequest:276 sort = val.sort277 command = val.command278 }279 if command != nil {280 if reading {281 reader.terminate()282 nextCommand = command283 } else {284 restart(*command)285 }286 break287 }288 snapshot, _ := chunkList.Snapshot()289 matcher.Reset(snapshot, input(), true, !reading, sort, clearCache())290 delay = false291292 case EvtSearchProgress:293 switch val := value.(type) {294 case float32:295 terminal.UpdateProgress(val)296 }297298 case EvtHeader:

Fix incorrect header array mutationJunegunn Choibefore adoption212de25

lines 299–301why, one step back
299 headerPadded := make([]string, opts.HeaderLines)
300 copy(headerPadded, value.([]string))301 terminal.UpdateHeader(headerPadded)

[vim] Use cterm colors on Windows (#1793)Jan Edmund Lazobefore adoptionaa0e10e

lines 302–344why, one step back
302
303 case EvtSearchFin:304 switch val := value.(type) {305 case *Merger:306 if deferred {307 count := val.Length()308 if opts.Select1 && count > 1 || opts.Exit0 && !opts.Select1 && count > 0 {309 deferred = false310 terminal.startChan <- true311 } else if val.final {312 if opts.Exit0 && count == 0 || opts.Select1 && count == 1 {313 if opts.PrintQuery {314 opts.Printer(opts.Query)315 }316 if len(opts.Expect) > 0 {317 opts.Printer("")318 }319 for i := 0; i < count; i++ {320 opts.Printer(val.Get(i).item.AsString(opts.Ansi))321 }322 if count > 0 {323 os.Exit(exitOk)324 }325 os.Exit(exitNoMatch)326 }327 deferred = false328 terminal.startChan <- true329 }330 }331 terminal.UpdateList(val, clearSelection())332 }333 }334 }335 events.Clear()336 })337 if delay && reading {338 dur := util.DurWithin(339 time.Duration(ticks)*coordinatorDelayStep,340 0, coordinatorDelayMax)341 time.Sleep(dur)342 }343 }344}