Merge pull request #134 from junegunn/devel
Before adoption: this commit came in with the history the project adopted, so no landing records it.
0.9.4
authored by Junegunn Choi · committed by Junegunn Choi · parents 4a1752d, b15a0e9 · Browse files · 20 files·+494 added−142 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
20 files+494 added−142 removed
- tests:+262 added−23 removed
- other:+232 added−119 removed
Provenance
- Commit
d4b41c5- Tree
91f123c- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent 1
4a1752d- Parent 2
b15a0e9
20 files changed+494 added−142 removed
modified:src/constants.go+1 added-1 removed
3 unmodified lines4 "github.com/junegunn/fzf/src/util"5 )6 7 // Current version8-const Version = "0.9.3"8+const Version = "0.9.4"9 10 // fzf events11 const (12 EvtReadNew util.EventType = iota6 unmodified linesmodified:src/core.go+29 added-15 removed
83 unmodified lines84 })85 }86 87 // Reader88+ streamingFilter := opts.Filter != nil && opts.Sort == 0 && !opts.Tac && !opts.Sync89+ if !streamingFilter {88- reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}89- go reader.ReadSource()90+ reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}91+ go reader.ReadSource()92+ }93 94 // Matcher95 patternBuilder := func(runes []rune) *Pattern {96 return BuildPattern(97 opts.Mode, opts.Case, opts.Nth, opts.Delimiter, runes)98 }96- matcher := NewMatcher(patternBuilder, opts.Sort > 0, eventBox)99+ matcher := NewMatcher(patternBuilder, opts.Sort > 0, opts.Tac, eventBox)100 101 // Filtering mode102 if opts.Filter != nil {103+ if opts.PrintQuery {104+ fmt.Println(*opts.Filter)105+ }106+107 pattern := patternBuilder([]rune(*opts.Filter))108 109+ if streamingFilter {110+ reader := Reader{111+ func(str string) {112+ item := chunkList.trans(&str, 0)113+ if pattern.MatchItem(item) {114+ fmt.Println(*item.text)115+ }116+ }, eventBox}117+ reader.ReadSource()118+ } else {102- eventBox.Unwatch(EvtReadNew)103- eventBox.WaitFor(EvtReadFin)119+ eventBox.Unwatch(EvtReadNew)120+ eventBox.WaitFor(EvtReadFin)121 105- snapshot, _ := chunkList.Snapshot()106- merger, _ := matcher.scan(MatchRequest{107- chunks: snapshot,108- pattern: pattern})109-110- if opts.PrintQuery {111- fmt.Println(*opts.Filter)122+ snapshot, _ := chunkList.Snapshot()123+ merger, _ := matcher.scan(MatchRequest{124+ chunks: snapshot,125+ pattern: pattern})126+ for i := 0; i < merger.Length(); i++ {127+ fmt.Println(merger.Get(i).AsString())128+ }129 }113- for i := 0; i < merger.Length(); i++ {114- fmt.Println(merger.Get(i).AsString())115- }130 os.Exit(0)131 }132 133 // Synchronous search80 unmodified linesmodified:src/Dockerfile.arch+1 added-1 removed
4 unmodified lines5 RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git6 7 # Install Go 1.48 RUN cd / && curl \9- https://storage.googleapis.com/golang/go1.4.1.linux-amd64.tar.gz | \9+ https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \10 tar -xz && mv go go1.411 12 ENV GOPATH /go13 ENV GOROOT /go1.414 unmodified linesmodified:src/Dockerfile.centos+1 added-1 removed
4 unmodified lines5 RUN yum install -y git gcc make tar ncurses-devel6 7 # Install Go 1.48 RUN cd / && curl \9- https://storage.googleapis.com/golang/go1.4.1.linux-amd64.tar.gz | \9+ https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \10 tar -xz && mv go go1.411 12 ENV GOPATH /go13 ENV GOROOT /go1.48 unmodified linesmodified:src/Dockerfile.ubuntu+1 added-1 removed
5 unmodified lines6 apt-get install -y --force-yes git curl build-essential libncurses-dev7 8 # Install Go 1.49 RUN cd / && curl \10- https://storage.googleapis.com/golang/go1.4.1.linux-amd64.tar.gz | \10+ https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \11 tar -xz && mv go go1.412 13 ENV GOPATH /go14 ENV GOROOT /go1.412 unmodified linesmodified:src/item_test.go+11 added-4 removed
18 unmodified lines19 }20 }21 22 func TestRankComparison(t *testing.T) {23- if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}) ||24- !compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}) ||25- !compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}) ||26- !compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}) {23+ if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}, false) ||24+ !compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}, false) ||25+ !compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}, false) ||26+ !compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}, false) {27 t.Error("Invalid order")28 }29+30+ if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}, true) ||31+ !compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}, false) ||32+ !compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}, true) ||33+ !compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}, false) {34+ t.Error("Invalid order (tac)")35+ }36 }37 38 // Match length, string length, index39 func TestItemRank(t *testing.T) {35 unmodified linesmodified:src/item.go+21 added-6 removed
85 unmodified lines86 func (a ByRelevance) Less(i, j int) bool {87 irank := a[i].Rank(true)88 jrank := a[j].Rank(true)89 90- return compareRanks(irank, jrank)90+ return compareRanks(irank, jrank, false)91 }92 93+// ByRelevanceTac is for sorting Items94+type ByRelevanceTac []*Item95+96+func (a ByRelevanceTac) Len() int {97+ return len(a)98+}99+100+func (a ByRelevanceTac) Swap(i, j int) {101+ a[i], a[j] = a[j], a[i]102+}103+104+func (a ByRelevanceTac) Less(i, j int) bool {105+ irank := a[i].Rank(true)106+ jrank := a[j].Rank(true)107+108+ return compareRanks(irank, jrank, true)109+}110+93-func compareRanks(irank Rank, jrank Rank) bool {111+func compareRanks(irank Rank, jrank Rank, tac bool) bool {112 if irank.matchlen < jrank.matchlen {113 return true114 } else if irank.matchlen > jrank.matchlen {115 return false4 unmodified lines120 } else if irank.strlen > jrank.strlen {121 return false122 }123 106- if irank.index <= jrank.index {107- return true108- }109- return false124+ return (irank.index <= jrank.index) != tac125 }modified:src/matcher.go+9 added-3 removed
19 unmodified lines20 // Matcher is responsible for performing search21 type Matcher struct {22 patternBuilder func([]rune) *Pattern23 sort bool24+ tac bool25 eventBox *util.EventBox26 reqBox *util.EventBox27 partitions int28 mergerCache map[string]*Merger9 unmodified lines38 )39 40 // NewMatcher returns a new Matcher41 func NewMatcher(patternBuilder func([]rune) *Pattern,41- sort bool, eventBox *util.EventBox) *Matcher {42+ sort bool, tac bool, eventBox *util.EventBox) *Matcher {43 return &Matcher{44 patternBuilder: patternBuilder,45 sort: sort,46+ tac: tac,47 eventBox: eventBox,48 reqBox: util.NewEventBox(),49 partitions: runtime.NumCPU(),50 mergerCache: make(map[string]*Merger)}109 unmodified lines160 }161 countChan <- len(matches)162 }163 if !empty && m.sort {164+ if m.tac {165+ sort.Sort(ByRelevanceTac(sliceMatches))166+ } else {162- sort.Sort(ByRelevance(sliceMatches))167+ sort.Sort(ByRelevance(sliceMatches))168+ }169 }170 resultChan <- partialResult{idx, sliceMatches}171 }(idx, chunks)172 }27 unmodified lines200 for range slices {201 partialResult := <-resultChan202 partialResults[partialResult.index] = partialResult.matches203 }198- return NewMerger(partialResults, !empty && m.sort), false204+ return NewMerger(partialResults, !empty && m.sort, m.tac), false205 }206 207 // Reset is called to interrupt/signal the ongoing search208 func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final bool) {10 unmodified linesmodified:src/merger_test.go+3 added-3 removed
60 unmodified lines61 lists, items := buildLists(false)62 cnt := len(items)63 64 // Not sorted: same order65- mg := NewMerger(lists, false)65+ mg := NewMerger(lists, false, false)66 assert(t, cnt == mg.Length(), "Invalid Length")67 for i := 0; i < cnt; i++ {68 assert(t, items[i] == mg.Get(i), "Invalid Get")69 }3 unmodified lines73 lists, items := buildLists(true)74 cnt := len(items)75 76 // Sorted sorted order77- mg := NewMerger(lists, true)77+ mg := NewMerger(lists, true, false)78 assert(t, cnt == mg.Length(), "Invalid Length")79 sort.Sort(ByRelevance(items))80 for i := 0; i < cnt; i++ {81 if items[i] != mg.Get(i) {1 unmodified line83 }84 }85 86 // Inverse order87- mg2 := NewMerger(lists, true)87+ mg2 := NewMerger(lists, true, false)88 for i := cnt - 1; i >= 0; i-- {89 if items[i] != mg2.Get(i) {90 t.Error("Not sorted", items[i], mg2.Get(i))91 }2 unmodified linesmodified:src/merger.go+18 added-14 removed
1 unmodified line2 3 import "fmt"4 5 // Merger with no data6-var EmptyMerger = NewMerger([][]*Item{}, false)6+var EmptyMerger = NewMerger([][]*Item{}, false, false)7 8 // Merger holds a set of locally sorted lists of items and provides the view of9 // a single, globally-sorted list10 type Merger struct {11 lists [][]*Item12 merged []*Item13 cursors []int14 sorted bool15+ tac bool16 final bool17 count int18 }19 20 // NewMerger returns a new Merger20-func NewMerger(lists [][]*Item, sorted bool) *Merger {21+func NewMerger(lists [][]*Item, sorted bool, tac bool) *Merger {22 mg := Merger{23 lists: lists,24 merged: []*Item{},25 cursors: make([]int, len(lists)),26 sorted: sorted,27+ tac: tac,28 final: false,29 count: 0}30 31 for _, list := range mg.lists {8 unmodified lines40 }41 42 // Get returns the pointer to the Item object indexed by the given integer43 func (mg *Merger) Get(idx int) *Item {42- if len(mg.lists) == 1 {43- return mg.lists[0][idx]44- } else if !mg.sorted {45- for _, list := range mg.lists {46- numItems := len(list)47- if idx < numItems {48- return list[idx]49- }50- idx -= numItems44+ if mg.sorted {45+ return mg.mergedGet(idx)46+ }47+48+ if mg.tac {49+ idx = mg.Length() - idx - 150+ }51+ for _, list := range mg.lists {52+ numItems := len(list)53+ if idx < numItems {54+ return list[idx]55 }52- panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))56+ idx -= numItems57 }54- return mg.mergedGet(idx)58+ panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))59 }60 61 func (mg *Merger) mergedGet(idx int) *Item {62 for i := len(mg.merged); i <= idx; i++ {6 unmodified lines69 continue70 }71 if cursor >= 0 {72 rank := list[cursor].Rank(false)69- if minIdx < 0 || compareRanks(rank, minRank) {73+ if minIdx < 0 || compareRanks(rank, minRank, mg.tac) {74 minRank = rank75 minIdx = listIdx76 }77 }13 unmodified linesmodified:src/options.go+10 added-3 removed
9 unmodified lines10 )11 12 const usage = `usage: fzf [options]13 14- Search14+ Search mode15 -x, --extended Extended-search mode16 -e, --extended-exact Extended-search mode (exact match)17 -i Case-insensitive match (default: smart-case match)18 +i Case-sensitive match3 unmodified lines22 --with-nth=N[,..] Transform the item using index expressions for search23 -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)24 25 Search result26- -s, --sort Sort the result27- +s, --no-sort Do not sort the result. Keep the sequence unchanged.26+ +s, --no-sort Do not sort the result27+ --tac Reverse the order of the input28+ (e.g. 'history | fzf --tac --no-sort')29 30 Interface31 -m, --multi Enable multi-select with tab/shift-tab32 --no-mouse Disable mouse45 unmodified lines78 Nth []Range79 WithNth []Range80 Delimiter *regexp.Regexp81 Sort int82+ Tac bool83 Multi bool84 Mouse bool85 Color bool86 Color256 bool16 unmodified lines103 Nth: make([]Range, 0),104 WithNth: make([]Range, 0),105 Delimiter: nil,106 Sort: 1000,107+ Tac: false,108 Multi: false,109 Mouse: true,110 Color: true,111 Color256: strings.Contains(os.Getenv("TERM"), "256"),102 unmodified lines214 case "-s", "--sort":215 opts.Sort = optionalNumeric(allArgs, &i)216 case "+s", "--no-sort":217 opts.Sort = 0218+ case "--tac":219+ opts.Tac = true220+ case "--no-tac":221+ opts.Tac = false222 case "-i":223 opts.Case = CaseIgnore224 case "+i":225 opts.Case = CaseRespect85 unmodified linesmodified:src/pattern_test.go+3 added-2 removed
96 unmodified lines97 pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("jg"))98 tokens := Tokenize(strptr("junegunn"), nil)99 trans := Transform(tokens, []Range{Range{1, 1}})100 101- for _, fun := range []func(*Chunk) []*Item{pattern.fuzzyMatch, pattern.extendedMatch} {101+ for _, mode := range []Mode{ModeFuzzy, ModeExtended} {102 chunk := Chunk{103 &Item{104 text: strptr("junegunn"),105 origText: strptr("junegunn.choi"),106 transformed: trans},107 }108- matches := fun(&chunk)108+ pattern.mode = mode109+ matches := pattern.matchChunk(&chunk)110 if *matches[0].text != "junegunn" || *matches[0].origText != "junegunn.choi" ||111 matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||112 matches[0].transformed != trans {113 t.Error("Invalid match result", matches)3 unmodified linesmodified:src/pattern.go+45 added-34 removed
217 unmodified lines218 }219 }220 }221 222- var matches []*Item223- if p.mode == ModeFuzzy {224- matches = p.fuzzyMatch(space)225- } else {226- matches = p.extendedMatch(space)227- }222+ matches := p.matchChunk(space)223 224 if !p.hasInvTerm {225 _cache.Add(chunk, cacheKey, matches)226 }227 return matches228 }229 230+func (p *Pattern) matchChunk(chunk *Chunk) []*Item {231+ matches := []*Item{}232+ if p.mode == ModeFuzzy {233+ for _, item := range *chunk {234+ if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {235+ matches = append(matches,236+ dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))237+ }238+ }239+ } else {240+ for _, item := range *chunk {241+ if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {242+ matches = append(matches, dupItem(item, offsets))243+ }244+ }245+ }246+ return matches247+}248+249+// MatchItem returns true if the Item is a match250+func (p *Pattern) MatchItem(item *Item) bool {251+ if p.mode == ModeFuzzy {252+ sidx, _ := p.fuzzyMatch(item)253+ return sidx >= 0254+ }255+ offsets := p.extendedMatch(item)256+ return len(offsets) == len(p.terms)257+}258+259 func dupItem(item *Item, offsets []Offset) *Item {260 sort.Sort(ByOrder(offsets))261 return &Item{262 text: item.text,3 unmodified lines266 offsets: offsets,267 rank: Rank{0, 0, item.index}}268 }269 246-func (p *Pattern) fuzzyMatch(chunk *Chunk) []*Item {247- matches := []*Item{}248- for _, item := range *chunk {249- input := p.prepareInput(item)250- if sidx, eidx := p.iter(algo.FuzzyMatch, input, p.text); sidx >= 0 {251- matches = append(matches,252- dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))253- }254- }255- return matches270+func (p *Pattern) fuzzyMatch(item *Item) (int, int) {271+ input := p.prepareInput(item)272+ return p.iter(algo.FuzzyMatch, input, p.text)273 }274 258-func (p *Pattern) extendedMatch(chunk *Chunk) []*Item {259- matches := []*Item{}260- for _, item := range *chunk {261- input := p.prepareInput(item)262- offsets := []Offset{}263- for _, term := range p.terms {264- pfun := p.procFun[term.typ]265- if sidx, eidx := p.iter(pfun, input, term.text); sidx >= 0 {266- if term.inv {267- break275+func (p *Pattern) extendedMatch(item *Item) []Offset {276+ input := p.prepareInput(item)277+ offsets := []Offset{}278+ for _, term := range p.terms {279+ pfun := p.procFun[term.typ]280+ if sidx, eidx := p.iter(pfun, input, term.text); sidx >= 0 {281+ if term.inv {282+ break268- }269- offsets = append(offsets, Offset{int32(sidx), int32(eidx)})270- } else if term.inv {271- offsets = append(offsets, Offset{0, 0})283 }284+ offsets = append(offsets, Offset{int32(sidx), int32(eidx)})285+ } else if term.inv {286+ offsets = append(offsets, Offset{0, 0})287 }274- if len(offsets) == len(p.terms) {275- matches = append(matches, dupItem(item, offsets))276- }288 }278- return matches289+ return offsets290 }291 292 func (p *Pattern) prepareInput(item *Item) *Transformed {293 if item.transformed != nil {27 unmodified linesmodified:src/terminal.go+5 added-15 removed
20 unmodified lines21 // Terminal represents terminal input/output22 type Terminal struct {23 prompt string24 reverse bool25- tac bool25 cx int26 cy int27 offset int28 yanked []rune54 unmodified lines83 func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {84 input := []rune(opts.Query)85 return &Terminal{86 prompt: opts.Prompt,88- tac: opts.Sort == 0,87 reverse: opts.Reverse,88 cx: len(input),89 cy: 0,90 offset: 0,54 unmodified lines145 t.reqBox.Set(reqInfo, nil)146 t.reqBox.Set(reqList, nil)147 }148 151-func (t *Terminal) listIndex(y int) int {152- if t.tac {153- return t.merger.Length() - y - 1154- }155- return y156-}157-149 func (t *Terminal) output() {150 if t.printQuery {151 fmt.Println(string(t.input))152 }153 if len(t.selected) == 0 {154 cnt := t.merger.Length()155 if cnt > 0 && cnt > t.cy {165- fmt.Println(t.merger.Get(t.listIndex(t.cy)).AsString())156+ fmt.Println(t.merger.Get(t.cy).AsString())157 }158 } else {159 sels := make([]selectedItem, 0, len(t.selected))160 for _, sel := range t.selected {75 unmodified lines236 count := t.merger.Length() - t.offset237 for i := 0; i < maxy; i++ {238 t.move(i+2, 0, true)239 if i < count {249- t.printItem(t.merger.Get(t.listIndex(i+t.offset)), i == t.cy-t.offset)240+ t.printItem(t.merger.Get(i+t.offset), i == t.cy-t.offset)241 }242 }243 }244 270 unmodified lines515 }516 }517 }518 toggle := func() {528- idx := t.listIndex(t.cy)529- if idx < t.merger.Length() {530- item := t.merger.Get(idx)519+ if t.cy < t.merger.Length() {520+ item := t.merger.Get(t.cy)521 if _, found := t.selected[item.text]; !found {522 var strptr *string523 if item.origText != nil {524 strptr = item.origText114 unmodified lines639 }640 } else if me.Double {641 // Double-click642 if my >= 2 {653- if t.vset(my-2) && t.listIndex(t.cy) < t.merger.Length() {643+ if t.vset(my-2) && t.cy < t.merger.Length() {644 req(reqClose)645 }646 }647 } else if me.Down {62 unmodified linesmodified:test/test_go.rb+261 added-22 removed
1 #!/usr/bin/env ruby2 # encoding: utf-83 4 require 'minitest/autorun'5+require 'fileutils'6 7 class NilClass8 def include? str9 false10 end11+12+ def start_with? str13+ false14+ end15+16+ def end_with? str17+ false18+ end19 end20 21 module Temp22 def readonce23 name = self.class::TEMPNAME24 waited = 025 while waited < 526 begin18- data = File.read(name)27+ data = `cat #{name}`28 return data unless data.empty?29 rescue30 sleep 0.131 waited += 0.16 unmodified lines38 end39 end40 end41 42+class Shell43+ class << self44+ def bash45+ 'PS1= PROMPT_COMMAND= bash --rcfile ~/.fzf.bash'46+ end47+48+ def zsh49+ FileUtils.mkdir_p '/tmp/fzf-zsh'50+ FileUtils.cp File.expand_path('~/.fzf.zsh'), '/tmp/fzf-zsh/.zshrc'51+ 'PS1= PROMPT_COMMAND= HISTSIZE=100 ZDOTDIR=/tmp/fzf-zsh zsh'52+ end53+ end54+end55+56 class Tmux57 include Temp58 59 TEMPNAME = '/tmp/fzf-test.txt'60 61 attr_reader :win62 40- def initialize shell = 'bash'41- @win = go("new-window -d -P -F '#I' 'PS1= PROMPT_COMMAND= bash --rcfile ~/.fzf.#{shell}'").first63+ def initialize shell = :bash64+ @win =65+ case shell66+ when :bash67+ go("new-window -d -P -F '#I' '#{Shell.bash}'").first68+ when :zsh69+ go("new-window -d -P -F '#I' '#{Shell.zsh}'").first70+ when :fish71+ go("new-window -d -P -F '#I' 'fish'").first72+ else73+ raise "Unknown shell: #{shell}"74+ end75 @lines = `tput lines`.chomp.to_i76+77+ if shell == :fish78+ send_keys('function fish_prompt; end; clear', :Enter)79+ self.until { |lines| lines.empty? }80+ end81 end82 83 def closed?84 !go("list-window -F '#I'").include?(win)85 end86 49- def close timeout = 187+ def close88 send_keys 'C-c', 'C-u', 'exit', :Enter51- wait(timeout) { closed? }89+ wait { closed? }90 end91 92 def kill93 go("kill-window -t #{win} 2> /dev/null")94 end95 96 def send_keys *args97+ target =98+ if args.last.is_a?(Hash)99+ hash = args.pop100+ go("select-window -t #{win}")101+ "#{win}.#{hash[:pane]}"102+ else103+ win104+ end105 args = args.map { |a| %{"#{a}"} }.join ' '60- go("send-keys -t #{win} #{args}")106+ go("send-keys -t #{target} #{args}")107 end108 63- def capture64- go("capture-pane -t #{win} \\; save-buffer #{TEMPNAME}")65- raise "Window not found" if $?.exitstatus != 0109+ def capture opts = {}110+ timeout, pane = defaults(opts).values_at(:timeout, :pane)111+ waited = 0112+ loop do113+ go("capture-pane -t #{win}.#{pane} \\; save-buffer #{TEMPNAME}")114+ break if $?.exitstatus == 0115+116+ if waited > timeout117+ raise "Window not found"118+ end119+ waited += 0.1120+ sleep 0.1121+ end122 readonce.split($/)[0, @lines].reverse.drop_while(&:empty?).reverse123 end124 69- def until timeout = 170- wait(timeout) { yield capture }125+ def until opts = {}126+ lines = nil127+ wait(opts) do128+ yield lines = capture(opts)129+ end130+ lines131 end132 133+ def prepare134+ self.send_keys 'echo hello', :Enter135+ self.until { |lines| lines[-1].start_with?('hello') }136+ self.send_keys 'clear', :Enter137+ self.until { |lines| lines.empty? }138+ end139 private74- def wait timeout = 1140+ def defaults opts141+ { timeout: 5, pane: 0 }.merge(opts)142+ end143+144+ def wait opts = {}145+ timeout, pane = defaults(opts).values_at(:timeout, :pane)146 waited = 0147 until yield77- waited += 0.178- sleep 0.1148 if waited > timeout149 hl = '=' * 10150 puts hl82- capture.each_with_index do |line, idx|151+ capture(opts).each_with_index do |line, idx|152 puts [idx.to_s.rjust(2), line].join(': ')153 end154 puts hl155 raise "timeout"156 end157+ waited += 0.1158+ sleep 0.1159 end160 end161 162 def go *args163 %x[tmux #{args.join ' '}].split($/)164 end165 end166 96-class TestGoFZF < MiniTest::Unit::TestCase167+class TestBase < Minitest::Test168 include Temp169 170 FIN = 'FIN'171 TEMPNAME = '/tmp/output'2 unmodified lines174 175 def setup176 ENV.delete 'FZF_DEFAULT_OPTS'177 ENV.delete 'FZF_DEFAULT_COMMAND'107- @tmux = Tmux.new178 end179 110- def teardown111- @tmux.kill112- end113-180 def fzf(*opts)181 fzf!(*opts) + " > #{TEMPNAME} && echo #{FIN}"182 end183 10 unmodified lines194 end195 }.compact196 "fzf #{opts.join ' '}"197 end198+end199 200+class TestGoFZF < TestBase201+ def setup202+ super203+ @tmux = Tmux.new204+ end205+206+ def teardown207+ @tmux.kill208+ end209+210 def test_vanilla211 tmux.send_keys "seq 1 100000 | #{fzf}", :Enter135- tmux.until(10) { |lines| lines.last =~ /^>/ && lines[-2] =~ /^ 100000/ }212+ tmux.until(timeout: 10) { |lines|213+ lines.last =~ /^>/ && lines[-2] =~ /^ 100000/ }214 lines = tmux.capture215 assert_equal ' 2', lines[-4]216 assert_equal '> 1', lines[-3]217 assert_equal ' 100000/100000', lines[-2]181 unmodified lines399 tmux.until { |lines| lines[-1] == '>' }400 tmux.send_keys 'C-K', :Enter401 assert_equal ['1919'], readonce.split($/)402 end403+404+ def test_tac405+ tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter406+ tmux.until { |lines| lines[-2].include? '1000/1000' }407+ tmux.send_keys :BTab, :BTab, :BTab, :Enter408+ assert_equal %w[1000 999 998], readonce.split($/)409+ end410+411+ def test_tac_sort412+ tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter413+ tmux.until { |lines| lines[-2].include? '1000/1000' }414+ tmux.send_keys '99'415+ tmux.send_keys :BTab, :BTab, :BTab, :Enter416+ assert_equal %w[99 999 998], readonce.split($/)417+ end418+419+ def test_tac_nosort420+ tmux.send_keys "seq 1 1000 | #{fzf :tac, :no_sort, :multi}", :Enter421+ tmux.until { |lines| lines[-2].include? '1000/1000' }422+ tmux.send_keys '00'423+ tmux.send_keys :BTab, :BTab, :BTab, :Enter424+ assert_equal %w[1000 900 800], readonce.split($/)425+ end426 end427 428+module TestShell429+ def setup430+ super431+ end432+433+ def teardown434+ @tmux.kill435+ end436+437+ def test_ctrl_t438+ tmux.prepare439+ tmux.send_keys 'C-t', pane: 0440+ lines = tmux.until(pane: 1) { |lines| lines[-1].start_with? '>' }441+ expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')442+ tmux.send_keys :BTab, :BTab, :Enter, pane: 1443+ tmux.until(pane: 0) { |lines| lines[-1].include? expected }444+ tmux.send_keys 'C-c'445+446+ # FZF_TMUX=0447+ new_shell448+ tmux.send_keys 'C-t', pane: 0449+ lines = tmux.until(pane: 0) { |lines| lines[-1].start_with? '>' }450+ expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')451+ tmux.send_keys :BTab, :BTab, :Enter, pane: 0452+ tmux.until(pane: 0) { |lines| lines[-1].include? expected }453+ tmux.send_keys 'C-c', 'C-d'454+ end455+456+ def test_alt_c457+ tmux.prepare458+ tmux.send_keys :Escape, :c459+ lines = tmux.until { |lines| lines[-1].start_with? '>' }460+ expected = lines[-3][2..-1]461+ p expected462+ tmux.send_keys :Enter463+ tmux.prepare464+ tmux.send_keys :pwd, :Enter465+ tmux.until { |lines| p lines; lines[-1].end_with?(expected) }466+ end467+468+ def test_ctrl_r469+ tmux.prepare470+ tmux.send_keys 'echo 1st', :Enter; tmux.prepare471+ tmux.send_keys 'echo 2nd', :Enter; tmux.prepare472+ tmux.send_keys 'echo 3d', :Enter; tmux.prepare473+ tmux.send_keys 'echo 3rd', :Enter; tmux.prepare474+ tmux.send_keys 'echo 4th', :Enter; tmux.prepare475+ tmux.send_keys 'C-r'476+ tmux.until { |lines| lines[-1].start_with? '>' }477+ tmux.send_keys '3d'478+ tmux.until { |lines| lines[-3].end_with? 'echo 3rd' } # --no-sort479+ tmux.send_keys :Enter480+ tmux.until { |lines| lines[-1] == 'echo 3rd' }481+ tmux.send_keys :Enter482+ tmux.until { |lines| lines[-1] == '3rd' }483+ end484+end485+486+class TestBash < TestBase487+ include TestShell488+489+ def new_shell490+ tmux.send_keys "FZF_TMUX=0 #{Shell.bash}", :Enter491+ tmux.prepare492+ end493+494+ def setup495+ super496+ @tmux = Tmux.new :bash497+ end498+499+ def test_file_completion500+ tmux.send_keys 'mkdir -p /tmp/fzf-test; touch /tmp/fzf-test/{1..100}', :Enter501+ tmux.prepare502+ tmux.send_keys 'cat /tmp/fzf-test/10**', :Tab503+ tmux.until { |lines| lines[-1].start_with? '>' }504+ tmux.send_keys :BTab, :BTab, :Enter505+ tmux.until { |lines|506+ lines[-1].include?('/tmp/fzf-test/10') &&507+ lines[-1].include?('/tmp/fzf-test/100')508+ }509+ end510+511+ def test_dir_completion512+ tmux.send_keys 'mkdir -p /tmp/fzf-test/d{1..100}', :Enter513+ tmux.prepare514+ tmux.send_keys 'cd /tmp/fzf-test/**', :Tab515+ tmux.until { |lines| lines[-1].start_with? '>' }516+ tmux.send_keys :BTab, :BTab # BTab does not work here517+ tmux.send_keys 55518+ tmux.until { |lines| lines[-2].start_with? ' 1/' }519+ tmux.send_keys :Enter520+ tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55' }521+ end522+523+ def test_process_completion524+ tmux.send_keys 'sleep 12345 &', :Enter525+ lines = tmux.until { |lines| lines[-1].start_with? '[1]' }526+ pid = lines[-1].split.last527+ tmux.prepare528+ tmux.send_keys 'kill ', :Tab529+ tmux.until { |lines| lines[-1].start_with? '>' }530+ tmux.send_keys 'sleep12345'531+ tmux.until { |lines| lines[-3].include? 'sleep 12345' }532+ tmux.send_keys :Enter533+ tmux.until { |lines| lines[-1] == "kill #{pid}" }534+ end535+end536+537+class TestZsh < TestBase538+ include TestShell539+540+ def new_shell541+ tmux.send_keys "FZF_TMUX=0 #{Shell.zsh}", :Enter542+ tmux.prepare543+ end544+545+ def setup546+ super547+ @tmux = Tmux.new :zsh548+ end549+end550+551+class TestFish < TestBase552+ include TestShell553+554+ def new_shell555+ tmux.send_keys 'env FZF_TMUX=0 fish', :Enter556+ tmux.send_keys 'function fish_prompt; end; clear', :Enter557+ tmux.until { |lines| lines.empty? }558+ end559+560+ def setup561+ super562+ @tmux = Tmux.new :fish563+ end564+end565+modified:test/test_ruby.rb+1 added-1 removed
52 unmodified lines53 self54 end55 end56 57-class TestRubyFZF < MiniTest::Unit::TestCase57+class TestRubyFZF < Minitest::Test58 def setup59 ENV.delete 'FZF_DEFAULT_SORT'60 ENV.delete 'FZF_DEFAULT_OPTS'61 ENV.delete 'FZF_DEFAULT_COMMAND'789 unmodified linesmodified:.travis.yml+4 added
1 language: ruby2+rvm:3+- 2.2.04 5 install:6 - sudo apt-get update7 - sudo apt-get install -y libncurses-dev lib32ncurses5-dev8 - sudo add-apt-repository -y ppa:pi-rho/dev9+- sudo apt-add-repository -y ppa:fish-shell/release-210 - sudo apt-get update11 - sudo apt-get install -y tmux=1.9a-1~ppa1~p12+- sudo apt-get install -y zsh fish13 14 script: |15 export GOROOT=~/go1.416 export GOPATH=~/go12 unmodified linesadded:CHANGELOG.md+60 added
1+CHANGELOG2+=========3+4+0.9.45+-----6+7+### New features8+9+#### Added `--tac` option to reverse the order of the input.10+11+One might argue that this option is unnecessary since we can already put `tac`12+or `tail -r` in the command pipeline to achieve the same result. However, the13+advantage of `--tac` is that it does not block until the input is complete.14+15+### *Backward incompatible changes*16+17+#### Changed behavior on `--no-sort`18+19+`--no-sort` option will no longer reverse the display order within finder. You20+may want to use the new `--tac` option with `--no-sort`.21+22+```23+history | fzf +s --tac24+```25+26+### Improvements27+28+#### `--filter` will not block when sort is disabled29+30+When fzf works in filtering mode (`--filter`) and sort is disabled31+(`--no-sort`), there's no need to block until input is complete. The new32+version of fzf will print the matches on-the-fly when the following condition33+is met:34+35+ --filter TERM --no-sort [--no-tac --no-sync]36+37+or simply:38+39+ -f TERM +s40+41+This change removes unnecessary delay in the use cases like the following:42+43+ fzf -f xxx +s | head -544+45+However, in this case, fzf processes the lines sequentially, so it cannot46+utilize multiple cores, and fzf will run slightly slower than the previous47+mode of execution where filtering is done in parallel after the entire input48+is loaded. If the user is concerned about this performance problem, one can49+add `--sync` option to re-enable buffering.50+51+0.9.352+-----53+54+### New features55+- Added `--sync` option for multi-staged filtering56+57+### Improvements58+- `--select-1` and `--exit-0` will start finder immediately when the condition59+ cannot be met60+modified:install+5 added-5 removed
1 #!/usr/bin/env bash2 3-version=0.9.33+version=0.9.44 5 cd $(dirname $BASH_SOURCE)6 fzf_base=$(pwd)7 236 unmodified lines244 bind '"\C-t": " \C-u \C-a\C-k$(__fsel)\e\C-e\C-y\C-a\C-y\ey\C-h\C-e\er \C-h"'245 fi246 247 # CTRL-R - Paste the selected command from history into the command line248- bind '"\C-r": " \C-e\C-u$(HISTTIMEFORMAT= history | fzf +s +m -n2..,.. | sed \"s/ *[0-9]* *//\")\e\C-e\er"'248+ bind '"\C-r": " \C-e\C-u$(HISTTIMEFORMAT= history | fzf +s --tac +m -n2..,.. | sed \"s/ *[0-9]* *//\")\e\C-e\er"'249 250 # ALT-C - cd into the selected directory251 bind '"\ec": " \C-e\C-u$(__fcd)\e\C-e\er\C-m"'252 else9 unmodified lines262 fi263 bind -m vi-command '"\C-t": "i\C-t"'264 265 # CTRL-R - Paste the selected command from history into the command line266- bind '"\C-r": "\eddi$(HISTTIMEFORMAT= history | fzf +s +m -n2..,.. | sed \"s/ *[0-9]* *//\")\C-x\C-e\e$a\C-x\C-r"'266+ bind '"\C-r": "\eddi$(HISTTIMEFORMAT= history | fzf +s --tac +m -n2..,.. | sed \"s/ *[0-9]* *//\")\C-x\C-e\e$a\C-x\C-r"'267 bind -m vi-command '"\C-r": "i\C-r"'268 269 # ALT-C - cd into the selected directory270 bind '"\ec": "\eddi$(__fcd)\C-x\C-e\C-x\C-r\C-m"'51 unmodified lines322 bindkey '\ec' fzf-cd-widget323 324 # CTRL-R - Paste the selected command from history into the command line325 fzf-history-widget() {326- LBUFFER=$(fc -l 1 | fzf +s +m -n2..,.. | sed "s/ *[0-9*]* *//")326+ LBUFFER=$(fc -l 1 | fzf +s --tac +m -n2..,.. | sed "s/ *[0-9*]* *//")327 zle redisplay328 }329 zle -N fzf-history-widget330 bindkey '^R' fzf-history-widget80 unmodified lines411 end412 end413 414 function __fzf_ctrl_r415- history | __fzf_reverse | fzf +s +m > $TMPDIR/fzf.result415+ history | __fzf_reverse | fzf +s --tac +m > $TMPDIR/fzf.result416 and commandline (cat $TMPDIR/fzf.result)417 commandline -f repaint418 rm -f $TMPDIR/fzf.result419 end79 unmodified linesmodified:README.md+5 added-11 removed
73 unmodified lines74 75 ```76 usage: fzf [options]77 78- Search78+ Search mode79 -x, --extended Extended-search mode80 -e, --extended-exact Extended-search mode (exact match)81 -i Case-insensitive match (default: smart-case match)82 +i Case-sensitive match3 unmodified lines86 --with-nth=N[,..] Transform the item using index expressions for search87 -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)88 89 Search result90- -s, --sort Sort the result91- +s, --no-sort Do not sort the result. Keep the sequence unchanged.90+ +s, --no-sort Do not sort the result91+ --tac Reverse the order of the input92+ (e.g. 'history | fzf --tac --no-sort')93 94 Interface95 -m, --multi Enable multi-select with tab/shift-tab96 --no-mouse Disable mouse31 unmodified lines128 ```sh129 vim $(fzf)130 ```131 131-If you want to preserve the exact sequence of the input, provide `--no-sort` (or132-`+s`) option.133-134-```sh135-history | fzf +s136-```137-132 ### Keys133 134 Use CTRL-J and CTRL-K (or CTRL-N and CTRL-P) to change the selection, press135 enter key to select the item. CTRL-C, CTRL-G, or ESC will terminate the finder.54 unmodified lines190 }191 192 # fh - repeat history193 fh() {200- eval $(([ -n "$ZSH_NAME" ] && fc -l 1 || history) | fzf +s | sed 's/ *[0-9]* *//')194+ eval $(([ -n "$ZSH_NAME" ] && fc -l 1 || history) | fzf +s --tac | sed 's/ *[0-9]* *//')195 }196 197 # fkill - kill process198 fkill() {358 unmodified lines