Skip to content
Myr

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

20 files+494 added−142 removed

modified:src/constants.go+1 added-1 removed
3 unmodified lines
4 "github.com/junegunn/fzf/src/util"5)67// Current version8const Version = "0.9.3"8const Version = "0.9.4"910// fzf events11const (12 EvtReadNew util.EventType = iota
6 unmodified lines
modified:src/core.go+29 added-15 removed
83 unmodified lines
84 })85 }8687 // 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 }9394 // 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)100101 // Filtering mode102 if opts.Filter != nil {103 if opts.PrintQuery {104 fmt.Println(*opts.Filter)105 }106107 pattern := patternBuilder([]rune(*opts.Filter))108109 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)121105 snapshot, _ := chunkList.Snapshot()106 merger, _ := matcher.scan(MatchRequest{107 chunks: snapshot,108 pattern: pattern})109110 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 }132133 // Synchronous search
80 unmodified lines
modified:src/Dockerfile.arch+1 added-1 removed
4 unmodified lines
5RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git67# Install Go 1.48RUN 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.41112ENV GOPATH /go13ENV GOROOT /go1.4
14 unmodified lines
modified:src/Dockerfile.centos+1 added-1 removed
4 unmodified lines
5RUN yum install -y git gcc make tar ncurses-devel67# Install Go 1.48RUN 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.41112ENV GOPATH /go13ENV GOROOT /go1.4
8 unmodified lines
modified:src/Dockerfile.ubuntu+1 added-1 removed
5 unmodified lines
6 apt-get install -y --force-yes git curl build-essential libncurses-dev78# Install Go 1.49RUN 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.41213ENV GOPATH /go14ENV GOROOT /go1.4
12 unmodified lines
modified:src/item_test.go+11 added-4 removed
18 unmodified lines
19 }20}2122func 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 }2930 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}3738// Match length, string length, index39func TestItemRank(t *testing.T) {
35 unmodified lines
modified:src/item.go+21 added-6 removed
85 unmodified lines
86func (a ByRelevance) Less(i, j int) bool {87 irank := a[i].Rank(true)88 jrank := a[j].Rank(true)8990 return compareRanks(irank, jrank)90 return compareRanks(irank, jrank, false)91}9293// ByRelevanceTac is for sorting Items94type ByRelevanceTac []*Item9596func (a ByRelevanceTac) Len() int {97 return len(a)98}99100func (a ByRelevanceTac) Swap(i, j int) {101 a[i], a[j] = a[j], a[i]102}103104func (a ByRelevanceTac) Less(i, j int) bool {105 irank := a[i].Rank(true)106 jrank := a[j].Rank(true)107108 return compareRanks(irank, jrank, true)109}11093func compareRanks(irank Rank, jrank Rank) bool {111func 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 false
4 unmodified lines
120 } else if irank.strlen > jrank.strlen {121 return false122 }123106 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 lines
20// Matcher is responsible for performing search21type Matcher struct {22 patternBuilder func([]rune) *Pattern23 sort bool24 tac bool25 eventBox *util.EventBox26 reqBox *util.EventBox27 partitions int28 mergerCache map[string]*Merger
9 unmodified lines
38)3940// NewMatcher returns a new Matcher41func 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 lines
160 }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 lines
200 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}206207// Reset is called to interrupt/signal the ongoing search208func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final bool) {
10 unmodified lines
modified:src/merger_test.go+3 added-3 removed
60 unmodified lines
61 lists, items := buildLists(false)62 cnt := len(items)6364 // 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 lines
73 lists, items := buildLists(true)74 cnt := len(items)7576 // 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 line
83 }84 }8586 // 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 lines
modified:src/merger.go+18 added-14 removed
1 unmodified line
23import "fmt"45// Merger with no data6var EmptyMerger = NewMerger([][]*Item{}, false)6var EmptyMerger = NewMerger([][]*Item{}, false, false)78// Merger holds a set of locally sorted lists of items and provides the view of9// a single, globally-sorted list10type Merger struct {11 lists [][]*Item12 merged []*Item13 cursors []int14 sorted bool15 tac bool16 final bool17 count int18}1920// NewMerger returns a new Merger20func NewMerger(lists [][]*Item, sorted bool) *Merger {21func 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}3031 for _, list := range mg.lists {
8 unmodified lines
40}4142// Get returns the pointer to the Item object indexed by the given integer43func (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 }4748 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}6061func (mg *Merger) mergedGet(idx int) *Item {62 for i := len(mg.merged); i <= idx; i++ {
6 unmodified lines
69 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 lines
modified:src/options.go+10 added-3 removed
9 unmodified lines
10)1112const usage = `usage: fzf [options]1314 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 match
3 unmodified lines
22 --with-nth=N[,..] Transform the item using index expressions for search23 -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)2425 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')2930 Interface31 -m, --multi Enable multi-select with tab/shift-tab32 --no-mouse Disable mouse
45 unmodified lines
78 Nth []Range79 WithNth []Range80 Delimiter *regexp.Regexp81 Sort int82 Tac bool83 Multi bool84 Mouse bool85 Color bool86 Color256 bool
16 unmodified lines
103 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 lines
214 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 = CaseRespect
85 unmodified lines
modified:src/pattern_test.go+3 added-2 removed
96 unmodified lines
97 pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("jg"))98 tokens := Tokenize(strptr("junegunn"), nil)99 trans := Transform(tokens, []Range{Range{1, 1}})100101 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 lines
modified:src/pattern.go+45 added-34 removed
217 unmodified lines
218 }219 }220 }221222 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)223224 if !p.hasInvTerm {225 _cache.Add(chunk, cacheKey, matches)226 }227 return matches228}229230func (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}248249// MatchItem returns true if the Item is a match250func (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}258259func dupItem(item *Item, offsets []Offset) *Item {260 sort.Sort(ByOrder(offsets))261 return &Item{262 text: item.text,
3 unmodified lines
266 offsets: offsets,267 rank: Rank{0, 0, item.index}}268}269246func (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 matches270func (p *Pattern) fuzzyMatch(item *Item) (int, int) {271 input := p.prepareInput(item)272 return p.iter(algo.FuzzyMatch, input, p.text)273}274258func (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 break275func (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}291292func (p *Pattern) prepareInput(item *Item) *Transformed {293 if item.transformed != nil {
27 unmodified lines
modified:src/terminal.go+5 added-15 removed
20 unmodified lines
21// Terminal represents terminal input/output22type Terminal struct {23 prompt string24 reverse bool25 tac bool25 cx int26 cy int27 offset int28 yanked []rune
54 unmodified lines
83func 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 lines
145 t.reqBox.Set(reqInfo, nil)146 t.reqBox.Set(reqList, nil)147}148151func (t *Terminal) listIndex(y int) int {152 if t.tac {153 return t.merger.Length() - y - 1154 }155 return y156}157149func (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 lines
236 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 lines
515 }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.origText
114 unmodified lines
639 }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 lines
modified:test/test_go.rb+261 added-22 removed
1#!/usr/bin/env ruby2# encoding: utf-834require 'minitest/autorun'5require 'fileutils'67class NilClass8 def include? str9 false10 end1112 def start_with? str13 false14 end1516 def end_with? str17 false18 end19end2021module 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.1
6 unmodified lines
38 end39 end40end4142class Shell43 class << self44 def bash45 'PS1= PROMPT_COMMAND= bash --rcfile ~/.fzf.bash'46 end4748 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 end54end5556class Tmux57 include Temp5859 TEMPNAME = '/tmp/fzf-test.txt'6061 attr_reader :win6240 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_i7677 if shell == :fish78 send_keys('function fish_prompt; end; clear', :Enter)79 self.until { |lines| lines.empty? }80 end81 end8283 def closed?84 !go("list-window -F '#I'").include?(win)85 end8649 def close timeout = 187 def close88 send_keys 'C-c', 'C-u', 'exit', :Enter51 wait(timeout) { closed? }89 wait { closed? }90 end9192 def kill93 go("kill-window -t #{win} 2> /dev/null")94 end9596 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 end10863 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 == 0115116 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 end12469 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 end132133 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 end139private74 def wait timeout = 1140 def defaults opts141 { timeout: 5, pane: 0 }.merge(opts)142 end143144 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 end161162 def go *args163 %x[tmux #{args.join ' '}].split($/)164 end165end16696class TestGoFZF < MiniTest::Unit::TestCase167class TestBase < Minitest::Test168 include Temp169170 FIN = 'FIN'171 TEMPNAME = '/tmp/output'
2 unmodified lines
174175 def setup176 ENV.delete 'FZF_DEFAULT_OPTS'177 ENV.delete 'FZF_DEFAULT_COMMAND'107 @tmux = Tmux.new178 end179110 def teardown111 @tmux.kill112 end113180 def fzf(*opts)181 fzf!(*opts) + " > #{TEMPNAME} && echo #{FIN}"182 end183
10 unmodified lines
194 end195 }.compact196 "fzf #{opts.join ' '}"197 end198end199200class TestGoFZF < TestBase201 def setup202 super203 @tmux = Tmux.new204 end205206 def teardown207 @tmux.kill208 end209210 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 lines
399 tmux.until { |lines| lines[-1] == '>' }400 tmux.send_keys 'C-K', :Enter401 assert_equal ['1919'], readonce.split($/)402 end403404 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 end410411 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 end418419 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 end426end427428module TestShell429 def setup430 super431 end432433 def teardown434 @tmux.kill435 end436437 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'445446 # 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 end455456 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 end467468 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 end484end485486class TestBash < TestBase487 include TestShell488489 def new_shell490 tmux.send_keys "FZF_TMUX=0 #{Shell.bash}", :Enter491 tmux.prepare492 end493494 def setup495 super496 @tmux = Tmux.new :bash497 end498499 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 end510511 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 end522523 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 end535end536537class TestZsh < TestBase538 include TestShell539540 def new_shell541 tmux.send_keys "FZF_TMUX=0 #{Shell.zsh}", :Enter542 tmux.prepare543 end544545 def setup546 super547 @tmux = Tmux.new :zsh548 end549end550551class TestFish < TestBase552 include TestShell553554 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 end559560 def setup561 super562 @tmux = Tmux.new :fish563 end564end565
modified:test/test_ruby.rb+1 added-1 removed
52 unmodified lines
53 self54 end55end5657class TestRubyFZF < MiniTest::Unit::TestCase57class TestRubyFZF < Minitest::Test58 def setup59 ENV.delete 'FZF_DEFAULT_SORT'60 ENV.delete 'FZF_DEFAULT_OPTS'61 ENV.delete 'FZF_DEFAULT_COMMAND'
789 unmodified lines
modified:.travis.yml+4 added
1language: ruby2rvm:3- 2.2.045install: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 fish1314script: |15 export GOROOT=~/go1.416 export GOPATH=~/go
12 unmodified lines
added:CHANGELOG.md+60 added
1CHANGELOG2=========340.9.45-----67### New features89#### Added `--tac` option to reverse the order of the input.1011One might argue that this option is unnecessary since we can already put `tac`12or `tail -r` in the command pipeline to achieve the same result. However, the13advantage of `--tac` is that it does not block until the input is complete.1415### *Backward incompatible changes*1617#### Changed behavior on `--no-sort`1819`--no-sort` option will no longer reverse the display order within finder. You20may want to use the new `--tac` option with `--no-sort`.2122```23history | fzf +s --tac24```2526### Improvements2728#### `--filter` will not block when sort is disabled2930When fzf works in filtering mode (`--filter`) and sort is disabled31(`--no-sort`), there's no need to block until input is complete. The new32version of fzf will print the matches on-the-fly when the following condition33is met:3435 --filter TERM --no-sort [--no-tac --no-sync]3637or simply:3839 -f TERM +s4041This change removes unnecessary delay in the use cases like the following:4243 fzf -f xxx +s | head -54445However, in this case, fzf processes the lines sequentially, so it cannot46utilize multiple cores, and fzf will run slightly slower than the previous47mode of execution where filtering is done in parallel after the entire input48is loaded. If the user is concerned about this performance problem, one can49add `--sync` option to re-enable buffering.50510.9.352-----5354### New features55- Added `--sync` option for multi-staged filtering5657### 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 bash23version=0.9.33version=0.9.445cd $(dirname $BASH_SOURCE)6fzf_base=$(pwd)7
236 unmodified lines
244 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 fi246247 # 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"'249250 # ALT-C - cd into the selected directory251 bind '"\ec": " \C-e\C-u$(__fcd)\e\C-e\er\C-m"'252else
9 unmodified lines
262 fi263 bind -m vi-command '"\C-t": "i\C-t"'264265 # 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"'268269 # ALT-C - cd into the selected directory270 bind '"\ec": "\eddi$(__fcd)\C-x\C-e\C-x\C-r\C-m"'
51 unmodified lines
322bindkey '\ec' fzf-cd-widget323324# CTRL-R - Paste the selected command from history into the command line325fzf-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}329zle -N fzf-history-widget330bindkey '^R' fzf-history-widget
80 unmodified lines
411 end412 end413414 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 end
79 unmodified lines
modified:README.md+5 added-11 removed
73 unmodified lines
7475```76usage: fzf [options]7778 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 match
3 unmodified lines
86 --with-nth=N[,..] Transform the item using index expressions for search87 -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)8889 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')9394 Interface95 -m, --multi Enable multi-select with tab/shift-tab96 --no-mouse Disable mouse
31 unmodified lines
128```sh129vim $(fzf)130```131131If you want to preserve the exact sequence of the input, provide `--no-sort` (or132`+s`) option.133134```sh135history | fzf +s136```137132### Keys133134Use CTRL-J and CTRL-K (or CTRL-N and CTRL-P) to change the selection, press135enter key to select the item. CTRL-C, CTRL-G, or ESC will terminate the finder.
54 unmodified lines
190}191192# fh - repeat history193fh() {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}196197# fkill - kill process198fkill() {
358 unmodified lines