Merge pull request #116 from junegunn/go
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Rewritten in Go
authored by Junegunn Choi · committed by Junegunn Choi · parents 4ceb520, 5c491d5 · Browse files · 40 files·+4162 added−79 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
40 files+4162 added−79 removed
- other:+4162 added−79 removed
Provenance
- Commit
209a6d3- Tree
d02ee4f- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent 1
4ceb520- Parent 2
5c491d5
40 files changed+4162 added−79 removed
modified:plugin/fzf.vim+4 added-2 removed
1-" Copyright (c) 2014 Junegunn Choi1+" Copyright (c) 2015 Junegunn Choi2 "3 " MIT License4 "5 " Permission is hereby granted, free of charge, to any person obtaining18 unmodified lines24 let s:min_tmux_width = 1025 let s:min_tmux_height = 326 let s:default_tmux_height = '40%'27 let s:launcher = 'xterm -e bash -ic %s'28+let s:fzf_go = expand('<sfile>:h:h').'/bin/fzf'29 let s:fzf_rb = expand('<sfile>:h:h').'/fzf'30 31 let s:cpo_save = &cpo32 set cpo&vim1 unmodified line34 function! s:fzf_exec()35 if !exists('s:exec')36 call system('type fzf')37 if v:shell_error37- let s:exec = executable(s:fzf_rb) ? s:fzf_rb : ''38+ let s:exec = executable(s:fzf_go) ?39+ \ s:fzf_go : (executable(s:fzf_rb) ? s:fzf_rb : '')40 else41 let s:exec = 'fzf'42 endif43 return s:fzf_exec()208 unmodified linesadded:src/algo/algo_test.go+44 added
1+package algo2+3+import (4+ "strings"5+ "testing"6+)7+8+func assertMatch(t *testing.T, fun func(bool, *string, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {9+ if !caseSensitive {10+ pattern = strings.ToLower(pattern)11+ }12+ s, e := fun(caseSensitive, &input, []rune(pattern))13+ if s != sidx {14+ t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)15+ }16+ if e != eidx {17+ t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", e, eidx, input, pattern)18+ }19+}20+21+func TestFuzzyMatch(t *testing.T) {22+ assertMatch(t, FuzzyMatch, false, "fooBarbaz", "oBZ", 2, 9)23+ assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBZ", -1, -1)24+ assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBz", 2, 9)25+ assertMatch(t, FuzzyMatch, true, "fooBarbaz", "fooBarbazz", -1, -1)26+}27+28+func TestExactMatchNaive(t *testing.T) {29+ assertMatch(t, ExactMatchNaive, false, "fooBarbaz", "oBA", 2, 5)30+ assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "oBA", -1, -1)31+ assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "fooBarbazz", -1, -1)32+}33+34+func TestPrefixMatch(t *testing.T) {35+ assertMatch(t, PrefixMatch, false, "fooBarbaz", "Foo", 0, 3)36+ assertMatch(t, PrefixMatch, true, "fooBarbaz", "Foo", -1, -1)37+ assertMatch(t, PrefixMatch, false, "fooBarbaz", "baz", -1, -1)38+}39+40+func TestSuffixMatch(t *testing.T) {41+ assertMatch(t, SuffixMatch, false, "fooBarbaz", "Foo", -1, -1)42+ assertMatch(t, SuffixMatch, false, "fooBarbaz", "baz", 6, 9)43+ assertMatch(t, SuffixMatch, true, "fooBarbaz", "Baz", -1, -1)44+}added:src/algo/algo.go+155 added
1+package algo2+3+import "strings"4+5+/*6+ * String matching algorithms here do not use strings.ToLower to avoid7+ * performance penalty. And they assume pattern runes are given in lowercase8+ * letters when caseSensitive is false.9+ *10+ * In short: They try to do as little work as possible.11+ */12+13+// FuzzyMatch performs fuzzy-match14+func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {15+ runes := []rune(*input)16+17+ // 0. (FIXME) How to find the shortest match?18+ // a_____b__c__abc19+ // ^^^^^^^^^^ ^^^20+ // 1. forward scan (abc)21+ // *-----*-----*>22+ // a_____b___abc__23+ // 2. reverse scan (cba)24+ // a_____b___abc__25+ // <***26+ pidx := 027+ sidx := -128+ eidx := -129+30+ for index, char := range runes {31+ // This is considerably faster than blindly applying strings.ToLower to the32+ // whole string33+ if !caseSensitive && char >= 65 && char <= 90 {34+ char += 3235+ }36+ if char == pattern[pidx] {37+ if sidx < 0 {38+ sidx = index39+ }40+ if pidx++; pidx == len(pattern) {41+ eidx = index + 142+ break43+ }44+ }45+ }46+47+ if sidx >= 0 && eidx >= 0 {48+ pidx--49+ for index := eidx - 1; index >= sidx; index-- {50+ char := runes[index]51+ if !caseSensitive && char >= 65 && char <= 90 {52+ char += 3253+ }54+ if char == pattern[pidx] {55+ if pidx--; pidx < 0 {56+ sidx = index57+ break58+ }59+ }60+ }61+ return sidx, eidx62+ }63+ return -1, -164+}65+66+// ExactMatchStrings performs exact-match using strings package.67+// Currently not used.68+func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int, int) {69+ var str string70+ if caseSensitive {71+ str = *input72+ } else {73+ str = strings.ToLower(*input)74+ }75+76+ if idx := strings.Index(str, string(pattern)); idx >= 0 {77+ prefixRuneLen := len([]rune((*input)[:idx]))78+ return prefixRuneLen, prefixRuneLen + len(pattern)79+ }80+ return -1, -181+}82+83+// ExactMatchNaive is a basic string searching algorithm that handles case84+// sensitivity. Although naive, it still performs better than the combination85+// of strings.ToLower + strings.Index for typical fzf use cases where input86+// strings and patterns are not very long.87+//88+// We might try to implement better algorithms in the future:89+// http://en.wikipedia.org/wiki/String_searching_algorithm90+func ExactMatchNaive(caseSensitive bool, input *string, pattern []rune) (int, int) {91+ runes := []rune(*input)92+ numRunes := len(runes)93+ plen := len(pattern)94+ if numRunes < plen {95+ return -1, -196+ }97+98+ pidx := 099+ for index := 0; index < numRunes; index++ {100+ char := runes[index]101+ if !caseSensitive && char >= 65 && char <= 90 {102+ char += 32103+ }104+ if pattern[pidx] == char {105+ pidx++106+ if pidx == plen {107+ return index - plen + 1, index + 1108+ }109+ } else {110+ index -= pidx111+ pidx = 0112+ }113+ }114+ return -1, -1115+}116+117+// PrefixMatch performs prefix-match118+func PrefixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {119+ runes := []rune(*input)120+ if len(runes) < len(pattern) {121+ return -1, -1122+ }123+124+ for index, r := range pattern {125+ char := runes[index]126+ if !caseSensitive && char >= 65 && char <= 90 {127+ char += 32128+ }129+ if char != r {130+ return -1, -1131+ }132+ }133+ return 0, len(pattern)134+}135+136+// SuffixMatch performs suffix-match137+func SuffixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {138+ runes := []rune(strings.TrimRight(*input, " "))139+ trimmedLen := len(runes)140+ diff := trimmedLen - len(pattern)141+ if diff < 0 {142+ return -1, -1143+ }144+145+ for index, r := range pattern {146+ char := runes[index+diff]147+ if !caseSensitive && char >= 65 && char <= 90 {148+ char += 32149+ }150+ if char != r {151+ return -1, -1152+ }153+ }154+ return trimmedLen - len(pattern), trimmedLen155+}added:src/curses/curses.go+426 added
1+package curses2+3+/*4+#include <ncurses.h>5+#include <locale.h>6+#cgo LDFLAGS: -lncurses7+void swapOutput() {8+ FILE* temp = stdout;9+ stdout = stderr;10+ stderr = temp;11+}12+*/13+import "C"14+15+import (16+ "os"17+ "os/signal"18+ "syscall"19+ "time"20+ "unicode/utf8"21+)22+23+// Types of user action24+const (25+ Rune = iota26+27+ CtrlA28+ CtrlB29+ CtrlC30+ CtrlD31+ CtrlE32+ CtrlF33+ CtrlG34+ CtrlH35+ Tab36+ CtrlJ37+ CtrlK38+ CtrlL39+ CtrlM40+ CtrlN41+ CtrlO42+ CtrlP43+ CtrlQ44+ CtrlR45+ CtrlS46+ CtrlT47+ CtrlU48+ CtrlV49+ CtrlW50+ CtrlX51+ CtrlY52+ CtrlZ53+ ESC54+55+ Invalid56+ Mouse57+58+ BTab59+60+ Del61+ PgUp62+ PgDn63+64+ AltB65+ AltF66+ AltD67+ AltBS68+)69+70+// Pallete71+const (72+ ColNormal = iota73+ ColPrompt74+ ColMatch75+ ColCurrent76+ ColCurrentMatch77+ ColSpinner78+ ColInfo79+ ColCursor80+ ColSelected81+)82+83+const (84+ doubleClickDuration = 500 * time.Millisecond85+)86+87+type Event struct {88+ Type int89+ Char rune90+ MouseEvent *MouseEvent91+}92+93+type MouseEvent struct {94+ Y int95+ X int96+ S int97+ Down bool98+ Double bool99+ Mod bool100+}101+102+var (103+ _buf []byte104+ _in *os.File105+ _color func(int, bool) C.int106+ _prevDownTime time.Time107+ _prevDownY int108+ _clickY []int109+)110+111+func init() {112+ _prevDownTime = time.Unix(0, 0)113+ _clickY = []int{}114+}115+116+func attrColored(pair int, bold bool) C.int {117+ var attr C.int118+ if pair > ColNormal {119+ attr = C.COLOR_PAIR(C.int(pair))120+ }121+ if bold {122+ attr = attr | C.A_BOLD123+ }124+ return attr125+}126+127+func attrMono(pair int, bold bool) C.int {128+ var attr C.int129+ switch pair {130+ case ColCurrent:131+ if bold {132+ attr = C.A_REVERSE133+ }134+ case ColMatch:135+ attr = C.A_UNDERLINE136+ case ColCurrentMatch:137+ attr = C.A_UNDERLINE | C.A_REVERSE138+ }139+ if bold {140+ attr = attr | C.A_BOLD141+ }142+ return attr143+}144+145+func MaxX() int {146+ return int(C.COLS)147+}148+149+func MaxY() int {150+ return int(C.LINES)151+}152+153+func getch(nonblock bool) int {154+ b := make([]byte, 1)155+ syscall.SetNonblock(int(_in.Fd()), nonblock)156+ _, err := _in.Read(b)157+ if err != nil {158+ return -1159+ }160+ return int(b[0])161+}162+163+func Init(color bool, color256 bool, black bool, mouse bool) {164+ {165+ in, err := os.OpenFile("/dev/tty", syscall.O_RDONLY, 0)166+ if err != nil {167+ panic("Failed to open /dev/tty")168+ }169+ _in = in170+ // Break STDIN171+ // syscall.Dup2(int(in.Fd()), int(os.Stdin.Fd()))172+ }173+174+ C.swapOutput()175+176+ C.setlocale(C.LC_ALL, C.CString(""))177+ C.initscr()178+ if mouse {179+ C.mousemask(C.ALL_MOUSE_EVENTS, nil)180+ }181+ C.cbreak()182+ C.noecho()183+ C.raw() // stty dsusp undef184+185+ intChan := make(chan os.Signal, 1)186+ signal.Notify(intChan, os.Interrupt, os.Kill)187+ go func() {188+ <-intChan189+ Close()190+ os.Exit(1)191+ }()192+193+ if color {194+ C.start_color()195+ var bg C.short196+ if black {197+ bg = C.COLOR_BLACK198+ } else {199+ C.use_default_colors()200+ bg = -1201+ }202+ if color256 {203+ C.init_pair(ColPrompt, 110, bg)204+ C.init_pair(ColMatch, 108, bg)205+ C.init_pair(ColCurrent, 254, 236)206+ C.init_pair(ColCurrentMatch, 151, 236)207+ C.init_pair(ColSpinner, 148, bg)208+ C.init_pair(ColInfo, 144, bg)209+ C.init_pair(ColCursor, 161, 236)210+ C.init_pair(ColSelected, 168, 236)211+ } else {212+ C.init_pair(ColPrompt, C.COLOR_BLUE, bg)213+ C.init_pair(ColMatch, C.COLOR_GREEN, bg)214+ C.init_pair(ColCurrent, C.COLOR_YELLOW, C.COLOR_BLACK)215+ C.init_pair(ColCurrentMatch, C.COLOR_GREEN, C.COLOR_BLACK)216+ C.init_pair(ColSpinner, C.COLOR_GREEN, bg)217+ C.init_pair(ColInfo, C.COLOR_WHITE, bg)218+ C.init_pair(ColCursor, C.COLOR_RED, C.COLOR_BLACK)219+ C.init_pair(ColSelected, C.COLOR_MAGENTA, C.COLOR_BLACK)220+ }221+ _color = attrColored222+ } else {223+ _color = attrMono224+ }225+}226+227+func Close() {228+ C.endwin()229+ C.swapOutput()230+}231+232+func GetBytes() []byte {233+ c := getch(false)234+ _buf = append(_buf, byte(c))235+236+ for {237+ c = getch(true)238+ if c == -1 {239+ break240+ }241+ _buf = append(_buf, byte(c))242+ }243+244+ return _buf245+}246+247+// 27 (91 79) 77 type x y248+func mouseSequence(sz *int) Event {249+ if len(_buf) < 6 {250+ return Event{Invalid, 0, nil}251+ }252+ *sz = 6253+ switch _buf[3] {254+ case 32, 36, 40, 48, // mouse-down / shift / cmd / ctrl255+ 35, 39, 43, 51: // mouse-up / shift / cmd / ctrl256+ mod := _buf[3] >= 36257+ down := _buf[3]%2 == 0258+ x := int(_buf[4] - 33)259+ y := int(_buf[5] - 33)260+ double := false261+ if down {262+ now := time.Now()263+ if now.Sub(_prevDownTime) < doubleClickDuration {264+ _clickY = append(_clickY, y)265+ } else {266+ _clickY = []int{y}267+ }268+ _prevDownTime = now269+ } else {270+ if len(_clickY) > 1 && _clickY[0] == _clickY[1] &&271+ time.Now().Sub(_prevDownTime) < doubleClickDuration {272+ double = true273+ }274+ }275+ return Event{Mouse, 0, &MouseEvent{y, x, 0, down, double, mod}}276+ case 96, 100, 104, 112, // scroll-up / shift / cmd / ctrl277+ 97, 101, 105, 113: // scroll-down / shift / cmd / ctrl278+ mod := _buf[3] >= 100279+ s := 1 - int(_buf[3]%2)*2280+ return Event{Mouse, 0, &MouseEvent{0, 0, s, false, false, mod}}281+ }282+ return Event{Invalid, 0, nil}283+}284+285+func escSequence(sz *int) Event {286+ if len(_buf) < 2 {287+ return Event{ESC, 0, nil}288+ }289+ *sz = 2290+ switch _buf[1] {291+ case 98:292+ return Event{AltB, 0, nil}293+ case 100:294+ return Event{AltD, 0, nil}295+ case 102:296+ return Event{AltF, 0, nil}297+ case 127:298+ return Event{AltBS, 0, nil}299+ case 91, 79:300+ if len(_buf) < 3 {301+ return Event{Invalid, 0, nil}302+ }303+ *sz = 3304+ switch _buf[2] {305+ case 68:306+ return Event{CtrlB, 0, nil}307+ case 67:308+ return Event{CtrlF, 0, nil}309+ case 66:310+ return Event{CtrlJ, 0, nil}311+ case 65:312+ return Event{CtrlK, 0, nil}313+ case 90:314+ return Event{BTab, 0, nil}315+ case 72:316+ return Event{CtrlA, 0, nil}317+ case 70:318+ return Event{CtrlE, 0, nil}319+ case 77:320+ return mouseSequence(sz)321+ case 49, 50, 51, 52, 53, 54:322+ if len(_buf) < 4 {323+ return Event{Invalid, 0, nil}324+ }325+ *sz = 4326+ switch _buf[2] {327+ case 50:328+ return Event{Invalid, 0, nil} // INS329+ case 51:330+ return Event{Del, 0, nil}331+ case 52:332+ return Event{CtrlE, 0, nil}333+ case 53:334+ return Event{PgUp, 0, nil}335+ case 54:336+ return Event{PgDn, 0, nil}337+ case 49:338+ switch _buf[3] {339+ case 126:340+ return Event{CtrlA, 0, nil}341+ case 59:342+ if len(_buf) != 6 {343+ return Event{Invalid, 0, nil}344+ }345+ *sz = 6346+ switch _buf[4] {347+ case 50:348+ switch _buf[5] {349+ case 68:350+ return Event{CtrlA, 0, nil}351+ case 67:352+ return Event{CtrlE, 0, nil}353+ }354+ case 53:355+ switch _buf[5] {356+ case 68:357+ return Event{AltB, 0, nil}358+ case 67:359+ return Event{AltF, 0, nil}360+ }361+ } // _buf[4]362+ } // _buf[3]363+ } // _buf[2]364+ } // _buf[2]365+ } // _buf[1]366+ return Event{Invalid, 0, nil}367+}368+369+func GetChar() Event {370+ if len(_buf) == 0 {371+ _buf = GetBytes()372+ }373+ if len(_buf) == 0 {374+ panic("Empty _buffer")375+ }376+377+ sz := 1378+ defer func() {379+ _buf = _buf[sz:]380+ }()381+382+ switch _buf[0] {383+ case CtrlC, CtrlG, CtrlQ:384+ return Event{CtrlC, 0, nil}385+ case 127:386+ return Event{CtrlH, 0, nil}387+ case ESC:388+ return escSequence(&sz)389+ }390+391+ // CTRL-A ~ CTRL-Z392+ if _buf[0] <= CtrlZ {393+ return Event{int(_buf[0]), 0, nil}394+ }395+ r, rsz := utf8.DecodeRune(_buf)396+ sz = rsz397+ return Event{Rune, r, nil}398+}399+400+func Move(y int, x int) {401+ C.move(C.int(y), C.int(x))402+}403+404+func MoveAndClear(y int, x int) {405+ Move(y, x)406+ C.clrtoeol()407+}408+409+func Print(text string) {410+ C.addstr(C.CString(text))411+}412+413+func CPrint(pair int, bold bool, text string) {414+ attr := _color(pair, bold)415+ C.attron(attr)416+ Print(text)417+ C.attroff(attr)418+}419+420+func Clear() {421+ C.clear()422+}423+424+func Refresh() {425+ C.refresh()426+}added:src/fzf/main.go+7 added
1+package main2+3+import "github.com/junegunn/fzf/src"4+5+func main() {6+ fzf.Run(fzf.ParseOptions())7+}added:src/util/atomicbool_test.go+17 added
1+package util2+3+import "testing"4+5+func TestAtomicBool(t *testing.T) {6+ if !NewAtomicBool(true).Get() || NewAtomicBool(false).Get() {7+ t.Error("Invalid initial value")8+ }9+10+ ab := NewAtomicBool(true)11+ if ab.Set(false) {12+ t.Error("Invalid return value")13+ }14+ if ab.Get() {15+ t.Error("Invalid state")16+ }17+}added:src/util/atomicbool.go+32 added
1+package util2+3+import "sync"4+5+// AtomicBool is a boxed-class that provides synchronized access to the6+// underlying boolean value7+type AtomicBool struct {8+ mutex sync.Mutex9+ state bool10+}11+12+// NewAtomicBool returns a new AtomicBool13+func NewAtomicBool(initialState bool) *AtomicBool {14+ return &AtomicBool{15+ mutex: sync.Mutex{},16+ state: initialState}17+}18+19+// Get returns the current boolean value synchronously20+func (a *AtomicBool) Get() bool {21+ a.mutex.Lock()22+ defer a.mutex.Unlock()23+ return a.state24+}25+26+// Set updates the boolean value synchronously27+func (a *AtomicBool) Set(newState bool) bool {28+ a.mutex.Lock()29+ defer a.mutex.Unlock()30+ a.state = newState31+ return a.state32+}added:src/util/eventbox_test.go+61 added
1+package util2+3+import "testing"4+5+// fzf events6+const (7+ EvtReadNew EventType = iota8+ EvtReadFin9+ EvtSearchNew10+ EvtSearchProgress11+ EvtSearchFin12+ EvtClose13+)14+15+func TestEventBox(t *testing.T) {16+ eb := NewEventBox()17+18+ // Wait should return immediately19+ ch := make(chan bool)20+21+ go func() {22+ eb.Set(EvtReadNew, 10)23+ ch <- true24+ <-ch25+ eb.Set(EvtSearchNew, 10)26+ eb.Set(EvtSearchNew, 15)27+ eb.Set(EvtSearchNew, 20)28+ eb.Set(EvtSearchProgress, 30)29+ ch <- true30+ <-ch31+ eb.Set(EvtSearchFin, 40)32+ ch <- true33+ <-ch34+ }()35+36+ count := 037+ sum := 038+ looping := true39+ for looping {40+ <-ch41+ eb.Wait(func(events *Events) {42+ for _, value := range *events {43+ switch val := value.(type) {44+ case int:45+ sum += val46+ looping = sum < 10047+ }48+ }49+ events.Clear()50+ })51+ ch <- true52+ count++53+ }54+55+ if count != 3 {56+ t.Error("Invalid number of events", count)57+ }58+ if sum != 100 {59+ t.Error("Invalid sum", sum)60+ }61+}added:src/util/eventbox.go+80 added
1+package util2+3+import "sync"4+5+// EventType is the type for fzf events6+type EventType int7+8+// Events is a type that associates EventType to any data9+type Events map[EventType]interface{}10+11+// EventBox is used for coordinating events12+type EventBox struct {13+ events Events14+ cond *sync.Cond15+ ignore map[EventType]bool16+}17+18+// NewEventBox returns a new EventBox19+func NewEventBox() *EventBox {20+ return &EventBox{21+ events: make(Events),22+ cond: sync.NewCond(&sync.Mutex{}),23+ ignore: make(map[EventType]bool)}24+}25+26+// Wait blocks the goroutine until signaled27+func (b *EventBox) Wait(callback func(*Events)) {28+ b.cond.L.Lock()29+ defer b.cond.L.Unlock()30+31+ if len(b.events) == 0 {32+ b.cond.Wait()33+ }34+35+ callback(&b.events)36+}37+38+// Set turns on the event type on the box39+func (b *EventBox) Set(event EventType, value interface{}) {40+ b.cond.L.Lock()41+ defer b.cond.L.Unlock()42+ b.events[event] = value43+ if _, found := b.ignore[event]; !found {44+ b.cond.Broadcast()45+ }46+}47+48+// Clear clears the events49+// Unsynchronized; should be called within Wait routine50+func (events *Events) Clear() {51+ for event := range *events {52+ delete(*events, event)53+ }54+}55+56+// Peak peaks at the event box if the given event is set57+func (b *EventBox) Peak(event EventType) bool {58+ b.cond.L.Lock()59+ defer b.cond.L.Unlock()60+ _, ok := b.events[event]61+ return ok62+}63+64+// Watch deletes the events from the ignore list65+func (b *EventBox) Watch(events ...EventType) {66+ b.cond.L.Lock()67+ defer b.cond.L.Unlock()68+ for _, event := range events {69+ delete(b.ignore, event)70+ }71+}72+73+// Unwatch adds the events to the ignore list74+func (b *EventBox) Unwatch(events ...EventType) {75+ b.cond.L.Lock()76+ defer b.cond.L.Unlock()77+ for _, event := range events {78+ b.ignore[event] = true79+ }80+}added:src/util/util_test.go+22 added
1+package util2+3+import "testing"4+5+func TestMax(t *testing.T) {6+ if Max(-2, 5, 1, 4, 3) != 5 {7+ t.Error("Invalid result")8+ }9+}10+11+func TestContrain(t *testing.T) {12+ if Constrain(-3, -1, 3) != -1 {13+ t.Error("Expected", -1)14+ }15+ if Constrain(2, -1, 3) != 2 {16+ t.Error("Expected", 2)17+ }18+19+ if Constrain(5, -1, 3) != 3 {20+ t.Error("Expected", 3)21+ }22+}added:src/util/util.go+56 added
1+package util2+3+// #include <unistd.h>4+import "C"5+6+import (7+ "os"8+ "time"9+)10+11+// Max returns the largest integer12+func Max(first int, items ...int) int {13+ max := first14+ for _, item := range items {15+ if item > max {16+ max = item17+ }18+ }19+ return max20+}21+22+// Max32 returns the largest 32-bit integer23+func Max32(first int32, second int32) int32 {24+ if first > second {25+ return first26+ }27+ return second28+}29+30+// Constrain limits the given integer with the upper and lower bounds31+func Constrain(val int, min int, max int) int {32+ if val < min {33+ return min34+ }35+ if val > max {36+ return max37+ }38+ return val39+}40+41+// DurWithin limits the given time.Duration with the upper and lower bounds42+func DurWithin(43+ val time.Duration, min time.Duration, max time.Duration) time.Duration {44+ if val < min {45+ return min46+ }47+ if val > max {48+ return max49+ }50+ return val51+}52+53+// IsTty returns true is stdin is a terminal54+func IsTty() bool {55+ return int(C.isatty(C.int(os.Stdin.Fd()))) != 056+}added:src/cache_test.go+40 added
1+package fzf2+3+import "testing"4+5+func TestChunkCache(t *testing.T) {6+ cache := NewChunkCache()7+ chunk2 := make(Chunk, ChunkSize)8+ chunk1p := &Chunk{}9+ chunk2p := &chunk210+ items1 := []*Item{&Item{}}11+ items2 := []*Item{&Item{}, &Item{}}12+ cache.Add(chunk1p, "foo", items1)13+ cache.Add(chunk2p, "foo", items1)14+ cache.Add(chunk2p, "bar", items2)15+16+ { // chunk1 is not full17+ cached, found := cache.Find(chunk1p, "foo")18+ if found {19+ t.Error("Cached disabled for non-empty chunks", found, cached)20+ }21+ }22+ {23+ cached, found := cache.Find(chunk2p, "foo")24+ if !found || len(cached) != 1 {25+ t.Error("Expected 1 item cached", found, cached)26+ }27+ }28+ {29+ cached, found := cache.Find(chunk2p, "bar")30+ if !found || len(cached) != 2 {31+ t.Error("Expected 2 items cached", found, cached)32+ }33+ }34+ {35+ cached, found := cache.Find(chunk1p, "foobar")36+ if found {37+ t.Error("Expected 0 item cached", found, cached)38+ }39+ }40+}added:src/cache.go+53 added
1+package fzf2+3+import "sync"4+5+// QueryCache associates strings to lists of items6+type QueryCache map[string][]*Item7+8+// ChunkCache associates Chunk and query string to lists of items9+type ChunkCache struct {10+ mutex sync.Mutex11+ cache map[*Chunk]*QueryCache12+}13+14+// NewChunkCache returns a new ChunkCache15+func NewChunkCache() ChunkCache {16+ return ChunkCache{sync.Mutex{}, make(map[*Chunk]*QueryCache)}17+}18+19+// Add adds the list to the cache20+func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {21+ if len(key) == 0 || !chunk.IsFull() {22+ return23+ }24+25+ cc.mutex.Lock()26+ defer cc.mutex.Unlock()27+28+ qc, ok := cc.cache[chunk]29+ if !ok {30+ cc.cache[chunk] = &QueryCache{}31+ qc = cc.cache[chunk]32+ }33+ (*qc)[key] = list34+}35+36+// Find is called to lookup ChunkCache37+func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Item, bool) {38+ if len(key) == 0 || !chunk.IsFull() {39+ return nil, false40+ }41+42+ cc.mutex.Lock()43+ defer cc.mutex.Unlock()44+45+ qc, ok := cc.cache[chunk]46+ if ok {47+ list, ok := (*qc)[key]48+ if ok {49+ return list, true50+ }51+ }52+ return nil, false53+}added:src/chunklist_test.go+74 added
1+package fzf2+3+import (4+ "fmt"5+ "testing"6+)7+8+func TestChunkList(t *testing.T) {9+ cl := NewChunkList(func(s *string, i int) *Item {10+ return &Item{text: s, rank: Rank{0, 0, uint32(i * 2)}}11+ })12+13+ // Snapshot14+ snapshot, count := cl.Snapshot()15+ if len(snapshot) > 0 || count > 0 {16+ t.Error("Snapshot should be empty now")17+ }18+19+ // Add some data20+ cl.Push("hello")21+ cl.Push("world")22+23+ // Previously created snapshot should remain the same24+ if len(snapshot) > 0 {25+ t.Error("Snapshot should not have changed")26+ }27+28+ // But the new snapshot should contain the added items29+ snapshot, count = cl.Snapshot()30+ if len(snapshot) != 1 && count != 2 {31+ t.Error("Snapshot should not be empty now")32+ }33+34+ // Check the content of the ChunkList35+ chunk1 := snapshot[0]36+ if len(*chunk1) != 2 {37+ t.Error("Snapshot should contain only two items")38+ }39+ if *(*chunk1)[0].text != "hello" || (*chunk1)[0].rank.index != 0 ||40+ *(*chunk1)[1].text != "world" || (*chunk1)[1].rank.index != 2 {41+ t.Error("Invalid data")42+ }43+ if chunk1.IsFull() {44+ t.Error("Chunk should not have been marked full yet")45+ }46+47+ // Add more data48+ for i := 0; i < ChunkSize*2; i++ {49+ cl.Push(fmt.Sprintf("item %d", i))50+ }51+52+ // Previous snapshot should remain the same53+ if len(snapshot) != 1 {54+ t.Error("Snapshot should stay the same")55+ }56+57+ // New snapshot58+ snapshot, count = cl.Snapshot()59+ if len(snapshot) != 3 || !snapshot[0].IsFull() ||60+ !snapshot[1].IsFull() || snapshot[2].IsFull() || count != ChunkSize*2+2 {61+ t.Error("Expected two full chunks and one more chunk")62+ }63+ if len(*snapshot[2]) != 2 {64+ t.Error("Unexpected number of items")65+ }66+67+ cl.Push("hello")68+ cl.Push("world")69+70+ lastChunkCount := len(*snapshot[len(snapshot)-1])71+ if lastChunkCount != 2 {72+ t.Error("Unexpected number of items:", lastChunkCount)73+ }74+}added:src/chunklist.go+88 added
1+package fzf2+3+import "sync"4+5+// Capacity of each chunk6+const ChunkSize int = 1007+8+// Chunk is a list of Item pointers whose size has the upper limit of ChunkSize9+type Chunk []*Item // >>> []Item10+11+// ItemBuilder is a closure type that builds Item object from a pointer to a12+// string and an integer13+type ItemBuilder func(*string, int) *Item14+15+// ChunkList is a list of Chunks16+type ChunkList struct {17+ chunks []*Chunk18+ count int19+ mutex sync.Mutex20+ trans ItemBuilder21+}22+23+// NewChunkList returns a new ChunkList24+func NewChunkList(trans ItemBuilder) *ChunkList {25+ return &ChunkList{26+ chunks: []*Chunk{},27+ count: 0,28+ mutex: sync.Mutex{},29+ trans: trans}30+}31+32+func (c *Chunk) push(trans ItemBuilder, data *string, index int) {33+ *c = append(*c, trans(data, index))34+}35+36+// IsFull returns true if the Chunk is full37+func (c *Chunk) IsFull() bool {38+ return len(*c) == ChunkSize39+}40+41+func (cl *ChunkList) lastChunk() *Chunk {42+ return cl.chunks[len(cl.chunks)-1]43+}44+45+// CountItems returns the total number of Items46+func CountItems(cs []*Chunk) int {47+ if len(cs) == 0 {48+ return 049+ }50+ return ChunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))51+}52+53+// Push adds the item to the list54+func (cl *ChunkList) Push(data string) {55+ cl.mutex.Lock()56+ defer cl.mutex.Unlock()57+58+ if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {59+ newChunk := Chunk(make([]*Item, 0, ChunkSize))60+ cl.chunks = append(cl.chunks, &newChunk)61+ }62+63+ cl.lastChunk().push(cl.trans, &data, cl.count)64+ cl.count++65+}66+67+// Snapshot returns immutable snapshot of the ChunkList68+func (cl *ChunkList) Snapshot() ([]*Chunk, int) {69+ cl.mutex.Lock()70+ defer cl.mutex.Unlock()71+72+ ret := make([]*Chunk, len(cl.chunks))73+ copy(ret, cl.chunks)74+75+ // Duplicate the last chunk76+ if cnt := len(ret); cnt > 0 {77+ ret[cnt-1] = ret[cnt-1].dupe()78+ }79+ return ret, cl.count80+}81+82+func (c *Chunk) dupe() *Chunk {83+ newChunk := make(Chunk, len(*c))84+ for idx, ptr := range *c {85+ newChunk[idx] = ptr86+ }87+ return &newChunk88+}added:src/constants.go+18 added
1+package fzf2+3+import (4+ "github.com/junegunn/fzf/src/util"5+)6+7+// Current version8+const Version = "0.9.0"9+10+// fzf events11+const (12+ EvtReadNew util.EventType = iota13+ EvtReadFin14+ EvtSearchNew15+ EvtSearchProgress16+ EvtSearchFin17+ EvtClose18+)added:src/core.go+196 added
1+/*2+Package fzf implements fzf, a command-line fuzzy finder.3+4+The MIT License (MIT)5+6+Copyright (c) 2015 Junegunn Choi7+8+Permission is hereby granted, free of charge, to any person obtaining a copy9+of this software and associated documentation files (the "Software"), to deal10+in the Software without restriction, including without limitation the rights11+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell12+copies of the Software, and to permit persons to whom the Software is13+furnished to do so, subject to the following conditions:14+15+The above copyright notice and this permission notice shall be included in16+all copies or substantial portions of the Software.17+18+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR19+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,20+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE21+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER22+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,23+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN24+THE SOFTWARE.25+*/26+package fzf27+28+import (29+ "fmt"30+ "os"31+ "runtime"32+ "time"33+34+ "github.com/junegunn/fzf/src/util"35+)36+37+const coordinatorDelayMax time.Duration = 100 * time.Millisecond38+const coordinatorDelayStep time.Duration = 10 * time.Millisecond39+40+func initProcs() {41+ runtime.GOMAXPROCS(runtime.NumCPU())42+}43+44+/*45+Reader -> EvtReadFin46+Reader -> EvtReadNew -> Matcher (restart)47+Terminal -> EvtSearchNew -> Matcher (restart)48+Matcher -> EvtSearchProgress -> Terminal (update info)49+Matcher -> EvtSearchFin -> Terminal (update list)50+*/51+52+// Run starts fzf53+func Run(options *Options) {54+ initProcs()55+56+ opts := ParseOptions()57+58+ if opts.Version {59+ fmt.Println(Version)60+ os.Exit(0)61+ }62+63+ // Event channel64+ eventBox := util.NewEventBox()65+66+ // Chunk list67+ var chunkList *ChunkList68+ if len(opts.WithNth) == 0 {69+ chunkList = NewChunkList(func(data *string, index int) *Item {70+ return &Item{71+ text: data,72+ index: uint32(index),73+ rank: Rank{0, 0, uint32(index)}}74+ })75+ } else {76+ chunkList = NewChunkList(func(data *string, index int) *Item {77+ tokens := Tokenize(data, opts.Delimiter)78+ item := Item{79+ text: Transform(tokens, opts.WithNth).whole,80+ origText: data,81+ index: uint32(index),82+ rank: Rank{0, 0, uint32(index)}}83+ return &item84+ })85+ }86+87+ // Reader88+ reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}89+ go reader.ReadSource()90+91+ // Matcher92+ patternBuilder := func(runes []rune) *Pattern {93+ return BuildPattern(94+ opts.Mode, opts.Case, opts.Nth, opts.Delimiter, runes)95+ }96+ matcher := NewMatcher(patternBuilder, opts.Sort > 0, eventBox)97+98+ // Defered-interactive / Non-interactive99+ // --select-1 | --exit-0 | --filter100+ if filtering := opts.Filter != nil; filtering || opts.Select1 || opts.Exit0 {101+ limit := 0102+ var patternString string103+ if filtering {104+ patternString = *opts.Filter105+ } else {106+ if opts.Select1 || opts.Exit0 {107+ limit = 1108+ }109+ patternString = opts.Query110+ }111+ pattern := patternBuilder([]rune(patternString))112+113+ looping := true114+ eventBox.Unwatch(EvtReadNew)115+ for looping {116+ eventBox.Wait(func(events *util.Events) {117+ for evt := range *events {118+ switch evt {119+ case EvtReadFin:120+ looping = false121+ return122+ }123+ }124+ })125+ }126+127+ snapshot, _ := chunkList.Snapshot()128+ merger, cancelled := matcher.scan(MatchRequest{129+ chunks: snapshot,130+ pattern: pattern}, limit)131+132+ if !cancelled && (filtering ||133+ opts.Exit0 && merger.Length() == 0 ||134+ opts.Select1 && merger.Length() == 1) {135+ if opts.PrintQuery {136+ fmt.Println(patternString)137+ }138+ for i := 0; i < merger.Length(); i++ {139+ fmt.Println(merger.Get(i).AsString())140+ }141+ os.Exit(0)142+ }143+ }144+145+ // Go interactive146+ go matcher.Loop()147+148+ // Terminal I/O149+ terminal := NewTerminal(opts, eventBox)150+ go terminal.Loop()151+152+ // Event coordination153+ reading := true154+ ticks := 0155+ eventBox.Watch(EvtReadNew)156+ for {157+ delay := true158+ ticks++159+ eventBox.Wait(func(events *util.Events) {160+ defer events.Clear()161+ for evt, value := range *events {162+ switch evt {163+164+ case EvtReadNew, EvtReadFin:165+ reading = reading && evt == EvtReadNew166+ snapshot, count := chunkList.Snapshot()167+ terminal.UpdateCount(count, !reading)168+ matcher.Reset(snapshot, terminal.Input(), false)169+170+ case EvtSearchNew:171+ snapshot, _ := chunkList.Snapshot()172+ matcher.Reset(snapshot, terminal.Input(), true)173+ delay = false174+175+ case EvtSearchProgress:176+ switch val := value.(type) {177+ case float32:178+ terminal.UpdateProgress(val)179+ }180+181+ case EvtSearchFin:182+ switch val := value.(type) {183+ case *Merger:184+ terminal.UpdateList(val)185+ }186+ }187+ }188+ })189+ if delay && reading {190+ dur := util.DurWithin(191+ time.Duration(ticks)*coordinatorDelayStep,192+ 0, coordinatorDelayMax)193+ time.Sleep(dur)194+ }195+ }196+}added:src/Dockerfile.arch+27 added
1+FROM base/archlinux:2014.07.032+MAINTAINER Junegunn Choi <junegunn.c@gmail.com>3+4+# apt-get5+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.linux-amd64.tar.gz | \10+ tar -xz && mv go go1.411+12+ENV GOPATH /go13+ENV GOROOT /go1.414+ENV PATH /go1.4/bin:$PATH15+16+# For i386 build17+RUN echo '[multilib]' >> /etc/pacman.conf && \18+ echo 'Include = /etc/pacman.d/mirrorlist' >> /etc/pacman.conf && \19+ pacman-db-upgrade && yes | pacman -Sy gcc-multilib lib32-ncurses && \20+ cd $GOROOT/src && GOARCH=386 ./make.bash21+22+# Volume23+VOLUME /go24+25+# Default CMD26+CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash27+added:src/Dockerfile.centos+21 added
1+FROM centos:centos72+MAINTAINER Junegunn Choi <junegunn.c@gmail.com>3+4+# yum5+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.linux-amd64.tar.gz | \10+ tar -xz && mv go go1.411+12+ENV GOPATH /go13+ENV GOROOT /go1.414+ENV PATH /go1.4/bin:$PATH15+16+# Volume17+VOLUME /go18+19+# Default CMD20+CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash21+added:src/Dockerfile.ubuntu+26 added
1+FROM ubuntu:14.042+MAINTAINER Junegunn Choi <junegunn.c@gmail.com>3+4+# apt-get5+RUN apt-get update && apt-get -y upgrade && \6+ 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.linux-amd64.tar.gz | \11+ tar -xz && mv go go1.412+13+ENV GOPATH /go14+ENV GOROOT /go1.415+ENV PATH /go1.4/bin:$PATH16+17+# For i386 build18+RUN apt-get install -y lib32ncurses5-dev && \19+ cd $GOROOT/src && GOARCH=386 ./make.bash20+21+# Volume22+VOLUME /go23+24+# Default CMD25+CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash26+added:src/item_test.go+67 added
1+package fzf2+3+import (4+ "sort"5+ "testing"6+)7+8+func TestOffsetSort(t *testing.T) {9+ offsets := []Offset{10+ Offset{3, 5}, Offset{2, 7},11+ Offset{1, 3}, Offset{2, 9}}12+ sort.Sort(ByOrder(offsets))13+14+ if offsets[0][0] != 1 || offsets[0][1] != 3 ||15+ offsets[1][0] != 2 || offsets[1][1] != 7 ||16+ offsets[2][0] != 2 || offsets[2][1] != 9 ||17+ offsets[3][0] != 3 || offsets[3][1] != 5 {18+ t.Error("Invalid order:", offsets)19+ }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}) {27+ t.Error("Invalid order")28+ }29+}30+31+// Match length, string length, index32+func TestItemRank(t *testing.T) {33+ strs := []string{"foo", "foobar", "bar", "baz"}34+ item1 := Item{text: &strs[0], index: 1, offsets: []Offset{}}35+ rank1 := item1.Rank(true)36+ if rank1.matchlen != 0 || rank1.strlen != 3 || rank1.index != 1 {37+ t.Error(item1.Rank(true))38+ }39+ // Only differ in index40+ item2 := Item{text: &strs[0], index: 0, offsets: []Offset{}}41+42+ items := []*Item{&item1, &item2}43+ sort.Sort(ByRelevance(items))44+ if items[0] != &item2 || items[1] != &item1 {45+ t.Error(items)46+ }47+48+ items = []*Item{&item2, &item1, &item1, &item2}49+ sort.Sort(ByRelevance(items))50+ if items[0] != &item2 || items[1] != &item2 ||51+ items[2] != &item1 || items[3] != &item1 {52+ t.Error(items)53+ }54+55+ // Sort by relevance56+ item3 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}57+ item4 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}58+ item5 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}59+ item6 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}60+ items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}61+ sort.Sort(ByRelevance(items))62+ if items[0] != &item2 || items[1] != &item1 ||63+ items[2] != &item6 || items[3] != &item4 ||64+ items[4] != &item5 || items[5] != &item3 {65+ t.Error(items)66+ }67+}added:src/item.go+110 added
1+package fzf2+3+// Offset holds two 32-bit integers denoting the offsets of a matched substring4+type Offset [2]int325+6+// Item represents each input line7+type Item struct {8+ text *string9+ origText *string10+ transformed *Transformed11+ index uint3212+ offsets []Offset13+ rank Rank14+}15+16+// Rank is used to sort the search result17+type Rank struct {18+ matchlen uint1619+ strlen uint1620+ index uint3221+}22+23+// Rank calculates rank of the Item24+func (i *Item) Rank(cache bool) Rank {25+ if cache && (i.rank.matchlen > 0 || i.rank.strlen > 0) {26+ return i.rank27+ }28+ matchlen := 029+ prevEnd := 030+ for _, offset := range i.offsets {31+ begin := int(offset[0])32+ end := int(offset[1])33+ if prevEnd > begin {34+ begin = prevEnd35+ }36+ if end > prevEnd {37+ prevEnd = end38+ }39+ if end > begin {40+ matchlen += end - begin41+ }42+ }43+ rank := Rank{uint16(matchlen), uint16(len(*i.text)), i.index}44+ if cache {45+ i.rank = rank46+ }47+ return rank48+}49+50+// AsString returns the original string51+func (i *Item) AsString() string {52+ if i.origText != nil {53+ return *i.origText54+ }55+ return *i.text56+}57+58+// ByOrder is for sorting substring offsets59+type ByOrder []Offset60+61+func (a ByOrder) Len() int {62+ return len(a)63+}64+65+func (a ByOrder) Swap(i, j int) {66+ a[i], a[j] = a[j], a[i]67+}68+69+func (a ByOrder) Less(i, j int) bool {70+ ioff := a[i]71+ joff := a[j]72+ return (ioff[0] < joff[0]) || (ioff[0] == joff[0]) && (ioff[1] <= joff[1])73+}74+75+// ByRelevance is for sorting Items76+type ByRelevance []*Item77+78+func (a ByRelevance) Len() int {79+ return len(a)80+}81+82+func (a ByRelevance) Swap(i, j int) {83+ a[i], a[j] = a[j], a[i]84+}85+86+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)91+}92+93+func compareRanks(irank Rank, jrank Rank) bool {94+ if irank.matchlen < jrank.matchlen {95+ return true96+ } else if irank.matchlen > jrank.matchlen {97+ return false98+ }99+100+ if irank.strlen < jrank.strlen {101+ return true102+ } else if irank.strlen > jrank.strlen {103+ return false104+ }105+106+ if irank.index <= jrank.index {107+ return true108+ }109+ return false110+}added:src/LICENSE+21 added
1+The MIT License (MIT)2+3+Copyright (c) 2015 Junegunn Choi4+5+Permission is hereby granted, free of charge, to any person obtaining a copy6+of this software and associated documentation files (the "Software"), to deal7+in the Software without restriction, including without limitation the rights8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9+copies of the Software, and to permit persons to whom the Software is10+furnished to do so, subject to the following conditions:11+12+The above copyright notice and this permission notice shall be included in13+all copies or substantial portions of the Software.14+15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN21+THE SOFTWARE.added:src/Makefile+73 added
1+ifndef GOPATH2+$(error GOPATH is undefined)3+endif4+5+UNAME_S := $(shell uname -s)6+ifeq ($(UNAME_S),Darwin)7+ GOOS := darwin8+else ifeq ($(UNAME_S),Linux)9+ GOOS := linux10+endif11+12+ifneq ($(shell uname -m),x86_64)13+$(error "Build on $(UNAME_M) is not supported, yet.")14+endif15+16+SOURCES := $(wildcard *.go */*.go)17+BINDIR := ../bin18+19+BINARY32 := fzf-$(GOOS)_38620+BINARY64 := fzf-$(GOOS)_amd6421+RELEASE32 = fzf-$(shell fzf/$(BINARY64) --version)-$(GOOS)_38622+RELEASE64 = fzf-$(shell fzf/$(BINARY64) --version)-$(GOOS)_amd6423+24+all: test release25+26+release: build27+ cd fzf && \28+ cp $(BINARY32) $(RELEASE32) && tar -czf $(RELEASE32).tgz $(RELEASE32) && \29+ cp $(BINARY64) $(RELEASE64) && tar -czf $(RELEASE64).tgz $(RELEASE64) && \30+ rm $(RELEASE32) $(RELEASE64)31+32+build: fzf/$(BINARY32) fzf/$(BINARY64)33+34+test:35+ go get36+ go test -v ./...37+38+install: $(BINDIR)/fzf39+40+uninstall:41+ rm -f $(BINDIR)/fzf $(BINDIR)/$(BINARY64)42+43+clean:44+ cd fzf && rm -f $(BINARY32) $(BINARY64) $(RELEASE32).tgz $(RELEASE64).tgz45+46+fzf/$(BINARY32): $(SOURCES)47+ cd fzf && GOARCH=386 CGO_ENABLED=1 go build -o $(BINARY32)48+49+fzf/$(BINARY64): $(SOURCES)50+ cd fzf && go build -o $(BINARY64)51+52+$(BINDIR)/fzf: fzf/$(BINARY64) | $(BINDIR)53+ cp -f fzf/$(BINARY64) $(BINDIR)54+ cd $(BINDIR) && ln -sf $(BINARY64) fzf55+56+$(BINDIR):57+ mkdir -p $@58+59+# Linux distribution to build fzf on60+DISTRO := arch61+62+docker:63+ docker build -t junegunn/$(DISTRO)-sandbox - < Dockerfile.$(DISTRO)64+65+linux: docker66+ docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \67+ /bin/bash -ci 'cd /go/src/github.com/junegunn/fzf/src; make'68+69+$(DISTRO): docker70+ docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \71+ sh -c 'cd /go/src/github.com/junegunn/fzf/src; /bin/bash'72+73+.PHONY: all build release test install uninstall clean docker linux $(DISTRO)added:src/matcher.go+214 added
1+package fzf2+3+import (4+ "fmt"5+ "runtime"6+ "sort"7+ "sync"8+ "time"9+10+ "github.com/junegunn/fzf/src/util"11+)12+13+// MatchRequest represents a search request14+type MatchRequest struct {15+ chunks []*Chunk16+ pattern *Pattern17+}18+19+// Matcher is responsible for performing search20+type Matcher struct {21+ patternBuilder func([]rune) *Pattern22+ sort bool23+ eventBox *util.EventBox24+ reqBox *util.EventBox25+ partitions int26+ mergerCache map[string]*Merger27+}28+29+const (30+ reqRetry util.EventType = iota31+ reqReset32+)33+34+const (35+ progressMinDuration = 200 * time.Millisecond36+)37+38+// NewMatcher returns a new Matcher39+func NewMatcher(patternBuilder func([]rune) *Pattern,40+ sort bool, eventBox *util.EventBox) *Matcher {41+ return &Matcher{42+ patternBuilder: patternBuilder,43+ sort: sort,44+ eventBox: eventBox,45+ reqBox: util.NewEventBox(),46+ partitions: runtime.NumCPU(),47+ mergerCache: make(map[string]*Merger)}48+}49+50+// Loop puts Matcher in action51+func (m *Matcher) Loop() {52+ prevCount := 053+54+ for {55+ var request MatchRequest56+57+ m.reqBox.Wait(func(events *util.Events) {58+ for _, val := range *events {59+ switch val := val.(type) {60+ case MatchRequest:61+ request = val62+ default:63+ panic(fmt.Sprintf("Unexpected type: %T", val))64+ }65+ }66+ events.Clear()67+ })68+69+ // Restart search70+ patternString := request.pattern.AsString()71+ var merger *Merger72+ cancelled := false73+ count := CountItems(request.chunks)74+75+ foundCache := false76+ if count == prevCount {77+ // Look up mergerCache78+ if cached, found := m.mergerCache[patternString]; found {79+ foundCache = true80+ merger = cached81+ }82+ } else {83+ // Invalidate mergerCache84+ prevCount = count85+ m.mergerCache = make(map[string]*Merger)86+ }87+88+ if !foundCache {89+ merger, cancelled = m.scan(request, 0)90+ }91+92+ if !cancelled {93+ m.mergerCache[patternString] = merger94+ m.eventBox.Set(EvtSearchFin, merger)95+ }96+ }97+}98+99+func (m *Matcher) sliceChunks(chunks []*Chunk) [][]*Chunk {100+ perSlice := len(chunks) / m.partitions101+102+ // No need to parallelize103+ if perSlice == 0 {104+ return [][]*Chunk{chunks}105+ }106+107+ slices := make([][]*Chunk, m.partitions)108+ for i := 0; i < m.partitions; i++ {109+ start := i * perSlice110+ end := start + perSlice111+ if i == m.partitions-1 {112+ end = len(chunks)113+ }114+ slices[i] = chunks[start:end]115+ }116+ return slices117+}118+119+type partialResult struct {120+ index int121+ matches []*Item122+}123+124+func (m *Matcher) scan(request MatchRequest, limit int) (*Merger, bool) {125+ startedAt := time.Now()126+127+ numChunks := len(request.chunks)128+ if numChunks == 0 {129+ return EmptyMerger, false130+ }131+ pattern := request.pattern132+ empty := pattern.IsEmpty()133+ cancelled := util.NewAtomicBool(false)134+135+ slices := m.sliceChunks(request.chunks)136+ numSlices := len(slices)137+ resultChan := make(chan partialResult, numSlices)138+ countChan := make(chan int, numChunks)139+ waitGroup := sync.WaitGroup{}140+141+ for idx, chunks := range slices {142+ waitGroup.Add(1)143+ go func(idx int, chunks []*Chunk) {144+ defer func() { waitGroup.Done() }()145+ sliceMatches := []*Item{}146+ for _, chunk := range chunks {147+ var matches []*Item148+ if empty {149+ matches = *chunk150+ } else {151+ matches = request.pattern.Match(chunk)152+ }153+ sliceMatches = append(sliceMatches, matches...)154+ if cancelled.Get() {155+ return156+ }157+ countChan <- len(matches)158+ }159+ if !empty && m.sort {160+ sort.Sort(ByRelevance(sliceMatches))161+ }162+ resultChan <- partialResult{idx, sliceMatches}163+ }(idx, chunks)164+ }165+166+ wait := func() bool {167+ cancelled.Set(true)168+ waitGroup.Wait()169+ return true170+ }171+172+ count := 0173+ matchCount := 0174+ for matchesInChunk := range countChan {175+ count++176+ matchCount += matchesInChunk177+178+ if limit > 0 && matchCount > limit {179+ return nil, wait() // For --select-1 and --exit-0180+ }181+182+ if count == numChunks {183+ break184+ }185+186+ if !empty && m.reqBox.Peak(reqReset) {187+ return nil, wait()188+ }189+190+ if time.Now().Sub(startedAt) > progressMinDuration {191+ m.eventBox.Set(EvtSearchProgress, float32(count)/float32(numChunks))192+ }193+ }194+195+ partialResults := make([][]*Item, numSlices)196+ for range slices {197+ partialResult := <-resultChan198+ partialResults[partialResult.index] = partialResult.matches199+ }200+ return NewMerger(partialResults, !empty && m.sort), false201+}202+203+// Reset is called to interrupt/signal the ongoing search204+func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool) {205+ pattern := m.patternBuilder(patternRunes)206+207+ var event util.EventType208+ if cancel {209+ event = reqReset210+ } else {211+ event = reqRetry212+ }213+ m.reqBox.Set(event, MatchRequest{chunks, pattern})214+}added:src/merger_test.go+93 added
1+package fzf2+3+import (4+ "fmt"5+ "math/rand"6+ "sort"7+ "testing"8+)9+10+func assert(t *testing.T, cond bool, msg ...string) {11+ if !cond {12+ t.Error(msg)13+ }14+}15+16+func randItem() *Item {17+ str := fmt.Sprintf("%d", rand.Uint32())18+ offsets := make([]Offset, rand.Int()%3)19+ for idx := range offsets {20+ sidx := int32(rand.Uint32() % 20)21+ eidx := sidx + int32(rand.Uint32()%20)22+ offsets[idx] = Offset{sidx, eidx}23+ }24+ return &Item{25+ text: &str,26+ index: rand.Uint32(),27+ offsets: offsets}28+}29+30+func TestEmptyMerger(t *testing.T) {31+ assert(t, EmptyMerger.Length() == 0, "Not empty")32+ assert(t, EmptyMerger.count == 0, "Invalid count")33+ assert(t, len(EmptyMerger.lists) == 0, "Invalid lists")34+ assert(t, len(EmptyMerger.merged) == 0, "Invalid merged list")35+}36+37+func buildLists(partiallySorted bool) ([][]*Item, []*Item) {38+ numLists := 439+ lists := make([][]*Item, numLists)40+ cnt := 041+ for i := 0; i < numLists; i++ {42+ numItems := rand.Int() % 2043+ cnt += numItems44+ lists[i] = make([]*Item, numItems)45+ for j := 0; j < numItems; j++ {46+ item := randItem()47+ lists[i][j] = item48+ }49+ if partiallySorted {50+ sort.Sort(ByRelevance(lists[i]))51+ }52+ }53+ items := []*Item{}54+ for _, list := range lists {55+ items = append(items, list...)56+ }57+ return lists, items58+}59+60+func TestMergerUnsorted(t *testing.T) {61+ lists, items := buildLists(false)62+ cnt := len(items)63+64+ // Not sorted: same order65+ mg := NewMerger(lists, 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+ }70+}71+72+func TestMergerSorted(t *testing.T) {73+ lists, items := buildLists(true)74+ cnt := len(items)75+76+ // Sorted sorted order77+ mg := NewMerger(lists, true)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) {82+ t.Error("Not sorted", items[i], mg.Get(i))83+ }84+ }85+86+ // Inverse order87+ mg2 := NewMerger(lists, true)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+ }92+ }93+}added:src/merger.go+84 added
1+package fzf2+3+import "fmt"4+5+// Merger with no data6+var EmptyMerger = NewMerger([][]*Item{}, 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+ count int16+}17+18+// NewMerger returns a new Merger19+func NewMerger(lists [][]*Item, sorted bool) *Merger {20+ mg := Merger{21+ lists: lists,22+ merged: []*Item{},23+ cursors: make([]int, len(lists)),24+ sorted: sorted,25+ count: 0}26+27+ for _, list := range mg.lists {28+ mg.count += len(list)29+ }30+ return &mg31+}32+33+// Length returns the number of items34+func (mg *Merger) Length() int {35+ return mg.count36+}37+38+// Get returns the pointer to the Item object indexed by the given integer39+func (mg *Merger) Get(idx int) *Item {40+ if len(mg.lists) == 1 {41+ return mg.lists[0][idx]42+ } else if !mg.sorted {43+ for _, list := range mg.lists {44+ numItems := len(list)45+ if idx < numItems {46+ return list[idx]47+ }48+ idx -= numItems49+ }50+ panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))51+ }52+ return mg.mergedGet(idx)53+}54+55+func (mg *Merger) mergedGet(idx int) *Item {56+ for i := len(mg.merged); i <= idx; i++ {57+ minRank := Rank{0, 0, 0}58+ minIdx := -159+ for listIdx, list := range mg.lists {60+ cursor := mg.cursors[listIdx]61+ if cursor < 0 || cursor == len(list) {62+ mg.cursors[listIdx] = -163+ continue64+ }65+ if cursor >= 0 {66+ rank := list[cursor].Rank(false)67+ if minIdx < 0 || compareRanks(rank, minRank) {68+ minRank = rank69+ minIdx = listIdx70+ }71+ }72+ mg.cursors[listIdx] = cursor73+ }74+75+ if minIdx >= 0 {76+ chosen := mg.lists[minIdx]77+ mg.merged = append(mg.merged, chosen[mg.cursors[minIdx]])78+ mg.cursors[minIdx]++79+ } else {80+ panic(fmt.Sprintf("Index out of bounds (sorted, %d/%d)", i, mg.count))81+ }82+ }83+ return mg.merged[idx]84+}added:src/options_test.go+37 added
1+package fzf2+3+import "testing"4+5+func TestDelimiterRegex(t *testing.T) {6+ rx := delimiterRegexp("*")7+ tokens := rx.FindAllString("-*--*---**---", -1)8+ if tokens[0] != "-*" || tokens[1] != "--*" || tokens[2] != "---*" ||9+ tokens[3] != "*" || tokens[4] != "---" {10+ t.Errorf("%s %s %d", rx, tokens, len(tokens))11+ }12+}13+14+func TestSplitNth(t *testing.T) {15+ {16+ ranges := splitNth("..")17+ if len(ranges) != 1 ||18+ ranges[0].begin != rangeEllipsis ||19+ ranges[0].end != rangeEllipsis {20+ t.Errorf("%s", ranges)21+ }22+ }23+ {24+ ranges := splitNth("..3,1..,2..3,4..-1,-3..-2,..,2,-2")25+ if len(ranges) != 8 ||26+ ranges[0].begin != rangeEllipsis || ranges[0].end != 3 ||27+ ranges[1].begin != 1 || ranges[1].end != rangeEllipsis ||28+ ranges[2].begin != 2 || ranges[2].end != 3 ||29+ ranges[3].begin != 4 || ranges[3].end != -1 ||30+ ranges[4].begin != -3 || ranges[4].end != -2 ||31+ ranges[5].begin != rangeEllipsis || ranges[5].end != rangeEllipsis ||32+ ranges[6].begin != 2 || ranges[6].end != 2 ||33+ ranges[7].begin != -2 || ranges[7].end != -2 {34+ t.Errorf("%s", ranges)35+ }36+ }37+}added:src/options.go+282 added
1+package fzf2+3+import (4+ "fmt"5+ "os"6+ "regexp"7+ "strings"8+9+ "github.com/junegunn/go-shellwords"10+)11+12+const usage = `usage: fzf [options]13+14+ Search15+ -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 match19+ -n, --nth=N[,..] Comma-separated list of field index expressions20+ for limiting search scope. Each can be a non-zero21+ integer or a range expression ([BEGIN]..[END])22+ --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.28+29+ Interface30+ -m, --multi Enable multi-select with tab/shift-tab31+ --no-mouse Disable mouse32+ +c, --no-color Disable colors33+ +2, --no-256 Disable 256-color34+ --black Use black background35+ --reverse Reverse orientation36+ --prompt=STR Input prompt (default: '> ')37+38+ Scripting39+ -q, --query=STR Start the finder with the given query40+ -1, --select-1 Automatically select the only match41+ -0, --exit-0 Exit immediately when there's no match42+ -f, --filter=STR Filter mode. Do not start interactive finder.43+ --print-query Print query as the first line44+45+ Environment variables46+ FZF_DEFAULT_COMMAND Default command to use when input is tty47+ FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m")48+49+`50+51+// Mode denotes the current search mode52+type Mode int53+54+// Search modes55+const (56+ ModeFuzzy Mode = iota57+ ModeExtended58+ ModeExtendedExact59+)60+61+// Case denotes case-sensitivity of search62+type Case int63+64+// Case-sensitivities65+const (66+ CaseSmart Case = iota67+ CaseIgnore68+ CaseRespect69+)70+71+// Options stores the values of command-line options72+type Options struct {73+ Mode Mode74+ Case Case75+ Nth []Range76+ WithNth []Range77+ Delimiter *regexp.Regexp78+ Sort int79+ Multi bool80+ Mouse bool81+ Color bool82+ Color256 bool83+ Black bool84+ Reverse bool85+ Prompt string86+ Query string87+ Select1 bool88+ Exit0 bool89+ Filter *string90+ PrintQuery bool91+ Version bool92+}93+94+func defaultOptions() *Options {95+ return &Options{96+ Mode: ModeFuzzy,97+ Case: CaseSmart,98+ Nth: make([]Range, 0),99+ WithNth: make([]Range, 0),100+ Delimiter: nil,101+ Sort: 1000,102+ Multi: false,103+ Mouse: true,104+ Color: true,105+ Color256: strings.Contains(os.Getenv("TERM"), "256"),106+ Black: false,107+ Reverse: false,108+ Prompt: "> ",109+ Query: "",110+ Select1: false,111+ Exit0: false,112+ Filter: nil,113+ PrintQuery: false,114+ Version: false}115+}116+117+func help(ok int) {118+ os.Stderr.WriteString(usage)119+ os.Exit(ok)120+}121+122+func errorExit(msg string) {123+ os.Stderr.WriteString(msg + "\n")124+ help(1)125+}126+127+func optString(arg string, prefix string) (bool, string) {128+ rx, _ := regexp.Compile(fmt.Sprintf("^(?:%s)(.*)$", prefix))129+ matches := rx.FindStringSubmatch(arg)130+ if len(matches) > 1 {131+ return true, matches[1]132+ }133+ return false, ""134+}135+136+func nextString(args []string, i *int, message string) string {137+ if len(args) > *i+1 {138+ *i++139+ } else {140+ errorExit(message)141+ }142+ return args[*i]143+}144+145+func optionalNumeric(args []string, i *int) int {146+ if len(args) > *i+1 {147+ if strings.IndexAny(args[*i+1], "0123456789") == 0 {148+ *i++149+ }150+ }151+ return 1 // Don't care152+}153+154+func splitNth(str string) []Range {155+ if match, _ := regexp.MatchString("^[0-9,-.]+$", str); !match {156+ errorExit("invalid format: " + str)157+ }158+159+ tokens := strings.Split(str, ",")160+ ranges := make([]Range, len(tokens))161+ for idx, s := range tokens {162+ r, ok := ParseRange(&s)163+ if !ok {164+ errorExit("invalid format: " + str)165+ }166+ ranges[idx] = r167+ }168+ return ranges169+}170+171+func delimiterRegexp(str string) *regexp.Regexp {172+ rx, e := regexp.Compile(str)173+ if e != nil {174+ str = regexp.QuoteMeta(str)175+ }176+177+ rx, e = regexp.Compile(fmt.Sprintf("(?:.*?%s)|(?:.+?$)", str))178+ if e != nil {179+ errorExit("invalid regular expression: " + e.Error())180+ }181+ return rx182+}183+184+func parseOptions(opts *Options, allArgs []string) {185+ for i := 0; i < len(allArgs); i++ {186+ arg := allArgs[i]187+ switch arg {188+ case "-h", "--help":189+ help(0)190+ case "-x", "--extended":191+ opts.Mode = ModeExtended192+ case "-e", "--extended-exact":193+ opts.Mode = ModeExtendedExact194+ case "+x", "--no-extended", "+e", "--no-extended-exact":195+ opts.Mode = ModeFuzzy196+ case "-q", "--query":197+ opts.Query = nextString(allArgs, &i, "query string required")198+ case "-f", "--filter":199+ filter := nextString(allArgs, &i, "query string required")200+ opts.Filter = &filter201+ case "-d", "--delimiter":202+ opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))203+ case "-n", "--nth":204+ opts.Nth = splitNth(nextString(allArgs, &i, "nth expression required"))205+ case "--with-nth":206+ opts.WithNth = splitNth(nextString(allArgs, &i, "nth expression required"))207+ case "-s", "--sort":208+ opts.Sort = optionalNumeric(allArgs, &i)209+ case "+s", "--no-sort":210+ opts.Sort = 0211+ case "-i":212+ opts.Case = CaseIgnore213+ case "+i":214+ opts.Case = CaseRespect215+ case "-m", "--multi":216+ opts.Multi = true217+ case "+m", "--no-multi":218+ opts.Multi = false219+ case "--no-mouse":220+ opts.Mouse = false221+ case "+c", "--no-color":222+ opts.Color = false223+ case "+2", "--no-256":224+ opts.Color256 = false225+ case "--black":226+ opts.Black = true227+ case "--no-black":228+ opts.Black = false229+ case "--reverse":230+ opts.Reverse = true231+ case "--no-reverse":232+ opts.Reverse = false233+ case "-1", "--select-1":234+ opts.Select1 = true235+ case "+1", "--no-select-1":236+ opts.Select1 = false237+ case "-0", "--exit-0":238+ opts.Exit0 = true239+ case "+0", "--no-exit-0":240+ opts.Exit0 = false241+ case "--print-query":242+ opts.PrintQuery = true243+ case "--no-print-query":244+ opts.PrintQuery = false245+ case "--prompt":246+ opts.Prompt = nextString(allArgs, &i, "prompt string required")247+ case "--version":248+ opts.Version = true249+ default:250+ if match, value := optString(arg, "-q|--query="); match {251+ opts.Query = value252+ } else if match, value := optString(arg, "-f|--filter="); match {253+ opts.Filter = &value254+ } else if match, value := optString(arg, "-d|--delimiter="); match {255+ opts.Delimiter = delimiterRegexp(value)256+ } else if match, value := optString(arg, "--prompt="); match {257+ opts.Prompt = value258+ } else if match, value := optString(arg, "-n|--nth="); match {259+ opts.Nth = splitNth(value)260+ } else if match, value := optString(arg, "--with-nth="); match {261+ opts.WithNth = splitNth(value)262+ } else if match, _ := optString(arg, "-s|--sort="); match {263+ opts.Sort = 1 // Don't care264+ } else {265+ errorExit("unknown option: " + arg)266+ }267+ }268+ }269+}270+271+// ParseOptions parses command-line options272+func ParseOptions() *Options {273+ opts := defaultOptions()274+275+ // Options from Env var276+ words, _ := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))277+ parseOptions(opts, words)278+279+ // Options from command-line arguments280+ parseOptions(opts, os.Args[1:])281+ return opts282+}added:src/pattern_test.go+115 added
1+package fzf2+3+import (4+ "testing"5+6+ "github.com/junegunn/fzf/src/algo"7+)8+9+func TestParseTermsExtended(t *testing.T) {10+ terms := parseTerms(ModeExtended,11+ "aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")12+ if len(terms) != 8 ||13+ terms[0].typ != termFuzzy || terms[0].inv ||14+ terms[1].typ != termExact || terms[1].inv ||15+ terms[2].typ != termPrefix || terms[2].inv ||16+ terms[3].typ != termSuffix || terms[3].inv ||17+ terms[4].typ != termFuzzy || !terms[4].inv ||18+ terms[5].typ != termExact || !terms[5].inv ||19+ terms[6].typ != termPrefix || !terms[6].inv ||20+ terms[7].typ != termSuffix || !terms[7].inv {21+ t.Errorf("%s", terms)22+ }23+ for idx, term := range terms {24+ if len(term.text) != 3 {25+ t.Errorf("%s", term)26+ }27+ if idx > 0 && len(term.origText) != 4+idx/5 {28+ t.Errorf("%s", term)29+ }30+ }31+}32+33+func TestParseTermsExtendedExact(t *testing.T) {34+ terms := parseTerms(ModeExtendedExact,35+ "aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")36+ if len(terms) != 8 ||37+ terms[0].typ != termExact || terms[0].inv || len(terms[0].text) != 3 ||38+ terms[1].typ != termExact || terms[1].inv || len(terms[1].text) != 4 ||39+ terms[2].typ != termPrefix || terms[2].inv || len(terms[2].text) != 3 ||40+ terms[3].typ != termSuffix || terms[3].inv || len(terms[3].text) != 3 ||41+ terms[4].typ != termExact || !terms[4].inv || len(terms[4].text) != 3 ||42+ terms[5].typ != termExact || !terms[5].inv || len(terms[5].text) != 4 ||43+ terms[6].typ != termPrefix || !terms[6].inv || len(terms[6].text) != 3 ||44+ terms[7].typ != termSuffix || !terms[7].inv || len(terms[7].text) != 3 {45+ t.Errorf("%s", terms)46+ }47+}48+49+func TestParseTermsEmpty(t *testing.T) {50+ terms := parseTerms(ModeExtended, "' $ ^ !' !^ !$")51+ if len(terms) != 0 {52+ t.Errorf("%s", terms)53+ }54+}55+56+func TestExact(t *testing.T) {57+ defer clearPatternCache()58+ clearPatternCache()59+ pattern := BuildPattern(ModeExtended, CaseSmart,60+ []Range{}, nil, []rune("'abc"))61+ str := "aabbcc abc"62+ sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &str, pattern.terms[0].text)63+ if sidx != 7 || eidx != 10 {64+ t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)65+ }66+}67+68+func TestCaseSensitivity(t *testing.T) {69+ defer clearPatternCache()70+ clearPatternCache()71+ pat1 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, nil, []rune("abc"))72+ clearPatternCache()73+ pat2 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, nil, []rune("Abc"))74+ clearPatternCache()75+ pat3 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, nil, []rune("abc"))76+ clearPatternCache()77+ pat4 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, nil, []rune("Abc"))78+ clearPatternCache()79+ pat5 := BuildPattern(ModeFuzzy, CaseRespect, []Range{}, nil, []rune("abc"))80+ clearPatternCache()81+ pat6 := BuildPattern(ModeFuzzy, CaseRespect, []Range{}, nil, []rune("Abc"))82+83+ if string(pat1.text) != "abc" || pat1.caseSensitive != false ||84+ string(pat2.text) != "Abc" || pat2.caseSensitive != true ||85+ string(pat3.text) != "abc" || pat3.caseSensitive != false ||86+ string(pat4.text) != "abc" || pat4.caseSensitive != false ||87+ string(pat5.text) != "abc" || pat5.caseSensitive != true ||88+ string(pat6.text) != "Abc" || pat6.caseSensitive != true {89+ t.Error("Invalid case conversion")90+ }91+}92+93+func TestOrigTextAndTransformed(t *testing.T) {94+ strptr := func(str string) *string {95+ return &str96+ }97+ 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} {102+ chunk := Chunk{103+ &Item{104+ text: strptr("junegunn"),105+ origText: strptr("junegunn.choi"),106+ transformed: trans},107+ }108+ matches := fun(&chunk)109+ if *matches[0].text != "junegunn" || *matches[0].origText != "junegunn.choi" ||110+ matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||111+ matches[0].transformed != trans {112+ t.Error("Invalid match result", matches)113+ }114+ }115+}added:src/pattern.go+309 added
1+package fzf2+3+import (4+ "regexp"5+ "sort"6+ "strings"7+8+ "github.com/junegunn/fzf/src/algo"9+)10+11+const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"12+13+// fuzzy14+// 'exact15+// ^exact-prefix16+// exact-suffix$17+// !not-fuzzy18+// !'not-exact19+// !^not-exact-prefix20+// !not-exact-suffix$21+22+type termType int23+24+const (25+ termFuzzy termType = iota26+ termExact27+ termPrefix28+ termSuffix29+)30+31+type term struct {32+ typ termType33+ inv bool34+ text []rune35+ origText []rune36+}37+38+// Pattern represents search pattern39+type Pattern struct {40+ mode Mode41+ caseSensitive bool42+ text []rune43+ terms []term44+ hasInvTerm bool45+ delimiter *regexp.Regexp46+ nth []Range47+ procFun map[termType]func(bool, *string, []rune) (int, int)48+}49+50+var (51+ _patternCache map[string]*Pattern52+ _splitRegex *regexp.Regexp53+ _cache ChunkCache54+)55+56+func init() {57+ // We can uniquely identify the pattern for a given string since58+ // mode and caseMode do not change while the program is running59+ _patternCache = make(map[string]*Pattern)60+ _splitRegex = regexp.MustCompile("\\s+")61+ _cache = NewChunkCache()62+}63+64+func clearPatternCache() {65+ _patternCache = make(map[string]*Pattern)66+}67+68+// BuildPattern builds Pattern object from the given arguments69+func BuildPattern(mode Mode, caseMode Case,70+ nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {71+72+ var asString string73+ switch mode {74+ case ModeExtended, ModeExtendedExact:75+ asString = strings.Trim(string(runes), " ")76+ default:77+ asString = string(runes)78+ }79+80+ cached, found := _patternCache[asString]81+ if found {82+ return cached83+ }84+85+ caseSensitive, hasInvTerm := true, false86+ terms := []term{}87+88+ switch caseMode {89+ case CaseSmart:90+ if !strings.ContainsAny(asString, uppercaseLetters) {91+ runes, caseSensitive = []rune(strings.ToLower(asString)), false92+ }93+ case CaseIgnore:94+ runes, caseSensitive = []rune(strings.ToLower(asString)), false95+ }96+97+ switch mode {98+ case ModeExtended, ModeExtendedExact:99+ terms = parseTerms(mode, string(runes))100+ for _, term := range terms {101+ if term.inv {102+ hasInvTerm = true103+ }104+ }105+ }106+107+ ptr := &Pattern{108+ mode: mode,109+ caseSensitive: caseSensitive,110+ text: runes,111+ terms: terms,112+ hasInvTerm: hasInvTerm,113+ nth: nth,114+ delimiter: delimiter,115+ procFun: make(map[termType]func(bool, *string, []rune) (int, int))}116+117+ ptr.procFun[termFuzzy] = algo.FuzzyMatch118+ ptr.procFun[termExact] = algo.ExactMatchNaive119+ ptr.procFun[termPrefix] = algo.PrefixMatch120+ ptr.procFun[termSuffix] = algo.SuffixMatch121+122+ _patternCache[asString] = ptr123+ return ptr124+}125+126+func parseTerms(mode Mode, str string) []term {127+ tokens := _splitRegex.Split(str, -1)128+ terms := []term{}129+ for _, token := range tokens {130+ typ, inv, text := termFuzzy, false, token131+ origText := []rune(text)132+ if mode == ModeExtendedExact {133+ typ = termExact134+ }135+136+ if strings.HasPrefix(text, "!") {137+ inv = true138+ text = text[1:]139+ }140+141+ if strings.HasPrefix(text, "'") {142+ if mode == ModeExtended {143+ typ = termExact144+ text = text[1:]145+ }146+ } else if strings.HasPrefix(text, "^") {147+ typ = termPrefix148+ text = text[1:]149+ } else if strings.HasSuffix(text, "$") {150+ typ = termSuffix151+ text = text[:len(text)-1]152+ }153+154+ if len(text) > 0 {155+ terms = append(terms, term{156+ typ: typ,157+ inv: inv,158+ text: []rune(text),159+ origText: origText})160+ }161+ }162+ return terms163+}164+165+// IsEmpty returns true if the pattern is effectively empty166+func (p *Pattern) IsEmpty() bool {167+ if p.mode == ModeFuzzy {168+ return len(p.text) == 0169+ }170+ return len(p.terms) == 0171+}172+173+// AsString returns the search query in string type174+func (p *Pattern) AsString() string {175+ return string(p.text)176+}177+178+// CacheKey is used to build string to be used as the key of result cache179+func (p *Pattern) CacheKey() string {180+ if p.mode == ModeFuzzy {181+ return p.AsString()182+ }183+ cacheableTerms := []string{}184+ for _, term := range p.terms {185+ if term.inv {186+ continue187+ }188+ cacheableTerms = append(cacheableTerms, string(term.origText))189+ }190+ return strings.Join(cacheableTerms, " ")191+}192+193+// Match returns the list of matches Items in the given Chunk194+func (p *Pattern) Match(chunk *Chunk) []*Item {195+ space := chunk196+197+ // ChunkCache: Exact match198+ cacheKey := p.CacheKey()199+ if !p.hasInvTerm { // Because we're excluding Inv-term from cache key200+ if cached, found := _cache.Find(chunk, cacheKey); found {201+ return cached202+ }203+ }204+205+ // ChunkCache: Prefix/suffix match206+Loop:207+ for idx := 1; idx < len(cacheKey); idx++ {208+ // [---------| ] | [ |---------]209+ // [--------| ] | [ |--------]210+ // [-------| ] | [ |-------]211+ prefix := cacheKey[:len(cacheKey)-idx]212+ suffix := cacheKey[idx:]213+ for _, substr := range [2]*string{&prefix, &suffix} {214+ if cached, found := _cache.Find(chunk, *substr); found {215+ cachedChunk := Chunk(cached)216+ space = &cachedChunk217+ break Loop218+ }219+ }220+ }221+222+ var matches []*Item223+ if p.mode == ModeFuzzy {224+ matches = p.fuzzyMatch(space)225+ } else {226+ matches = p.extendedMatch(space)227+ }228+229+ if !p.hasInvTerm {230+ _cache.Add(chunk, cacheKey, matches)231+ }232+ return matches233+}234+235+func dupItem(item *Item, offsets []Offset) *Item {236+ sort.Sort(ByOrder(offsets))237+ return &Item{238+ text: item.text,239+ origText: item.origText,240+ transformed: item.transformed,241+ index: item.index,242+ offsets: offsets,243+ rank: Rank{0, 0, item.index}}244+}245+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 matches256+}257+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+ break268+ }269+ offsets = append(offsets, Offset{int32(sidx), int32(eidx)})270+ } else if term.inv {271+ offsets = append(offsets, Offset{0, 0})272+ }273+ }274+ if len(offsets) == len(p.terms) {275+ matches = append(matches, dupItem(item, offsets))276+ }277+ }278+ return matches279+}280+281+func (p *Pattern) prepareInput(item *Item) *Transformed {282+ if item.transformed != nil {283+ return item.transformed284+ }285+286+ var ret *Transformed287+ if len(p.nth) > 0 {288+ tokens := Tokenize(item.text, p.delimiter)289+ ret = Transform(tokens, p.nth)290+ } else {291+ trans := Transformed{292+ whole: item.text,293+ parts: []Token{Token{text: item.text, prefixLength: 0}}}294+ ret = &trans295+ }296+ item.transformed = ret297+ return ret298+}299+300+func (p *Pattern) iter(pfun func(bool, *string, []rune) (int, int),301+ inputs *Transformed, pattern []rune) (int, int) {302+ for _, part := range inputs.parts {303+ prefixLength := part.prefixLength304+ if sidx, eidx := pfun(p.caseSensitive, part.text, pattern); sidx >= 0 {305+ return sidx + prefixLength, eidx + prefixLength306+ }307+ }308+ return -1, -1309+}added:src/reader_test.go+56 added
1+package fzf2+3+import (4+ "testing"5+6+ "github.com/junegunn/fzf/src/util"7+)8+9+func TestReadFromCommand(t *testing.T) {10+ strs := []string{}11+ eb := util.NewEventBox()12+ reader := Reader{13+ pusher: func(s string) { strs = append(strs, s) },14+ eventBox: eb}15+16+ // Check EventBox17+ if eb.Peak(EvtReadNew) {18+ t.Error("EvtReadNew should not be set yet")19+ }20+21+ // Normal command22+ reader.readFromCommand(`echo abc && echo def`)23+ if len(strs) != 2 || strs[0] != "abc" || strs[1] != "def" {24+ t.Errorf("%s", strs)25+ }26+27+ // Check EventBox again28+ if !eb.Peak(EvtReadNew) {29+ t.Error("EvtReadNew should be set yet")30+ }31+32+ // Wait should return immediately33+ eb.Wait(func(events *util.Events) {34+ if _, found := (*events)[EvtReadNew]; !found {35+ t.Errorf("%s", events)36+ }37+ events.Clear()38+ })39+40+ // EventBox is cleared41+ if eb.Peak(EvtReadNew) {42+ t.Error("EvtReadNew should not be set yet")43+ }44+45+ // Failing command46+ reader.readFromCommand(`no-such-command`)47+ strs = []string{}48+ if len(strs) > 0 {49+ t.Errorf("%s", strs)50+ }51+52+ // Check EventBox again53+ if eb.Peak(EvtReadNew) {54+ t.Error("Command failed. EvtReadNew should be set")55+ }56+}added:src/reader.go+59 added
1+package fzf2+3+import (4+ "bufio"5+ "io"6+ "os"7+ "os/exec"8+9+ "github.com/junegunn/fzf/src/util"10+)11+12+const defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`13+14+// Reader reads from command or standard input15+type Reader struct {16+ pusher func(string)17+ eventBox *util.EventBox18+}19+20+// ReadSource reads data from the default command or from standard input21+func (r *Reader) ReadSource() {22+ if util.IsTty() {23+ cmd := os.Getenv("FZF_DEFAULT_COMMAND")24+ if len(cmd) == 0 {25+ cmd = defaultCommand26+ }27+ r.readFromCommand(cmd)28+ } else {29+ r.readFromStdin()30+ }31+ r.eventBox.Set(EvtReadFin, nil)32+}33+34+func (r *Reader) feed(src io.Reader) {35+ if scanner := bufio.NewScanner(src); scanner != nil {36+ for scanner.Scan() {37+ r.pusher(scanner.Text())38+ r.eventBox.Set(EvtReadNew, nil)39+ }40+ }41+}42+43+func (r *Reader) readFromStdin() {44+ r.feed(os.Stdin)45+}46+47+func (r *Reader) readFromCommand(cmd string) {48+ listCommand := exec.Command("sh", "-c", cmd)49+ out, err := listCommand.StdoutPipe()50+ if err != nil {51+ return52+ }53+ err = listCommand.Start()54+ if err != nil {55+ return56+ }57+ defer listCommand.Wait()58+ r.feed(out)59+}added:src/README.md+115 added
1+fzf in Go2+=========3+4+This directory contains the source code for the new fzf implementation in5+[Go][go].6+7+Upgrade from Ruby version8+-------------------------9+10+The install script has been updated to download the right binary for your11+system. If you already have installed fzf, simply git-pull the repository and12+rerun the install script.13+14+```sh15+cd ~/.fzf16+git pull17+./install18+```19+20+Motivations21+-----------22+23+### No Ruby dependency24+25+There have always been complaints about fzf being a Ruby script. To make26+matters worse, Ruby 2.1 removed ncurses binding from its standard libary.27+Because of the change, users running Ruby 2.1 or above are forced to build C28+extensions of curses gem to meet the requirement of fzf. The new Go version29+will be distributed as an executable binary so it will be much more accessible30+and should be easier to setup.31+32+### Performance33+34+Many people have been surprised to see how fast fzf is even when it was35+written in Ruby. It stays quite responsive even for 100k+ lines, which is36+well above the size of the usual input.37+38+The new Go version, of course, is significantly faster than that. It has all39+the performance optimization techniques used in Ruby implementation and more.40+It also doesn't suffer from [GIL][gil], so the search performance scales41+proportional to the number of CPU cores. On my MacBook Pro (Mid 2012), the new42+version was shown to be an order of magnitude faster on certain cases. It also43+starts much faster though the difference may not be noticeable.44+45+Differences with Ruby version46+-----------------------------47+48+The Go version is designed to be perfectly compatible with the previous Ruby49+version. The only behavioral difference is that the new version ignores the50+numeric argument to `--sort=N` option and always sorts the result regardless51+of the number of matches. The value was introduced to limit the response time52+of the query, but the Go version is blazingly fast (almost instant response53+even for 1M+ items) so I decided that it's no longer required.54+55+System requirements56+-------------------57+58+Currently, prebuilt binaries are provided only for OS X and Linux. The install59+script will fall back to the legacy Ruby version on the other systems, but if60+you have Go 1.4 installed, you can try building it yourself.61+62+However, as pointed out in [golang.org/doc/install][req], the Go version may63+not run on CentOS/RHEL 5.x, and if that's the case, the install script will64+choose the Ruby version instead.65+66+The Go version depends on [ncurses][ncurses] and some Unix system calls, so it67+shouldn't run natively on Windows at the moment. But it won't be impossible to68+support Windows by falling back to a cross-platform alternative such as69+[termbox][termbox] only on Windows. If you're interested in making fzf work on70+Windows, please let me know.71+72+Build73+-----74+75+```sh76+# Build fzf executables and tarballs77+make78+79+# Install the executable to ../bin directory80+make install81+82+# Build executables and tarballs for Linux using Docker83+make linux84+```85+86+Contribution87+------------88+89+For the time being, I will not add or accept any new features until we can be90+sure that the implementation is stable and we have a sufficient number of test91+cases. However, fixes for obvious bugs and new test cases are welcome.92+93+I also care much about the performance of the implementation, so please make94+sure that your change does not result in performance regression. And please be95+noted that we don't have a quantitative measure of the performance yet.96+97+Third-party libraries used98+--------------------------99+100+- [ncurses][ncurses]101+- [mattn/go-runewidth](https://github.com/mattn/go-runewidth)102+ - Licensed under [MIT](http://mattn.mit-license.org/2013)103+- [mattn/go-shellwords](https://github.com/mattn/go-shellwords)104+ - Licensed under [MIT](http://mattn.mit-license.org/2014)105+106+License107+-------108+109+[MIT](LICENSE)110+111+[go]: https://golang.org/112+[gil]: http://en.wikipedia.org/wiki/Global_Interpreter_Lock113+[ncurses]: https://www.gnu.org/software/ncurses/114+[req]: http://golang.org/doc/install115+[termbox]: https://github.com/nsf/termbox-goadded:src/terminal.go+626 added
1+package fzf2+3+import (4+ "fmt"5+ "os"6+ "regexp"7+ "sort"8+ "sync"9+ "time"10+11+ C "github.com/junegunn/fzf/src/curses"12+ "github.com/junegunn/fzf/src/util"13+14+ "github.com/junegunn/go-runewidth"15+)16+17+// Terminal represents terminal input/output18+type Terminal struct {19+ prompt string20+ reverse bool21+ tac bool22+ cx int23+ cy int24+ offset int25+ yanked []rune26+ input []rune27+ multi bool28+ printQuery bool29+ count int30+ progress int31+ reading bool32+ merger *Merger33+ selected map[*string]*string34+ reqBox *util.EventBox35+ eventBox *util.EventBox36+ mutex sync.Mutex37+ initFunc func()38+ suppress bool39+}40+41+var _spinner = []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`}42+43+const (44+ reqPrompt util.EventType = iota45+ reqInfo46+ reqList47+ reqRefresh48+ reqRedraw49+ reqClose50+ reqQuit51+)52+53+const (54+ initialDelay = 100 * time.Millisecond55+ spinnerDuration = 200 * time.Millisecond56+)57+58+// NewTerminal returns new Terminal object59+func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {60+ input := []rune(opts.Query)61+ return &Terminal{62+ prompt: opts.Prompt,63+ tac: opts.Sort == 0,64+ reverse: opts.Reverse,65+ cx: displayWidth(input),66+ cy: 0,67+ offset: 0,68+ yanked: []rune{},69+ input: input,70+ multi: opts.Multi,71+ printQuery: opts.PrintQuery,72+ merger: EmptyMerger,73+ selected: make(map[*string]*string),74+ reqBox: util.NewEventBox(),75+ eventBox: eventBox,76+ mutex: sync.Mutex{},77+ suppress: true,78+ initFunc: func() {79+ C.Init(opts.Color, opts.Color256, opts.Black, opts.Mouse)80+ }}81+}82+83+// Input returns current query string84+func (t *Terminal) Input() []rune {85+ t.mutex.Lock()86+ defer t.mutex.Unlock()87+ return copySlice(t.input)88+}89+90+// UpdateCount updates the count information91+func (t *Terminal) UpdateCount(cnt int, final bool) {92+ t.mutex.Lock()93+ t.count = cnt94+ t.reading = !final95+ t.mutex.Unlock()96+ t.reqBox.Set(reqInfo, nil)97+ if final {98+ t.reqBox.Set(reqRefresh, nil)99+ }100+}101+102+// UpdateProgress updates the search progress103+func (t *Terminal) UpdateProgress(progress float32) {104+ t.mutex.Lock()105+ newProgress := int(progress * 100)106+ changed := t.progress != newProgress107+ t.progress = newProgress108+ t.mutex.Unlock()109+110+ if changed {111+ t.reqBox.Set(reqInfo, nil)112+ }113+}114+115+// UpdateList updates Merger to display the list116+func (t *Terminal) UpdateList(merger *Merger) {117+ t.mutex.Lock()118+ t.progress = 100119+ t.merger = merger120+ t.mutex.Unlock()121+ t.reqBox.Set(reqInfo, nil)122+ t.reqBox.Set(reqList, nil)123+}124+125+func (t *Terminal) listIndex(y int) int {126+ if t.tac {127+ return t.merger.Length() - y - 1128+ }129+ return y130+}131+132+func (t *Terminal) output() {133+ if t.printQuery {134+ fmt.Println(string(t.input))135+ }136+ if len(t.selected) == 0 {137+ if t.merger.Length() > t.cy {138+ fmt.Println(t.merger.Get(t.listIndex(t.cy)).AsString())139+ }140+ } else {141+ for ptr, orig := range t.selected {142+ if orig != nil {143+ fmt.Println(*orig)144+ } else {145+ fmt.Println(*ptr)146+ }147+ }148+ }149+}150+151+func displayWidth(runes []rune) int {152+ l := 0153+ for _, r := range runes {154+ l += runewidth.RuneWidth(r)155+ }156+ return l157+}158+159+func (t *Terminal) move(y int, x int, clear bool) {160+ maxy := C.MaxY()161+ if !t.reverse {162+ y = maxy - y - 1163+ }164+165+ if clear {166+ C.MoveAndClear(y, x)167+ } else {168+ C.Move(y, x)169+ }170+}171+172+func (t *Terminal) placeCursor() {173+ t.move(0, len(t.prompt)+displayWidth(t.input[:t.cx]), false)174+}175+176+func (t *Terminal) printPrompt() {177+ t.move(0, 0, true)178+ C.CPrint(C.ColPrompt, true, t.prompt)179+ C.CPrint(C.ColNormal, true, string(t.input))180+}181+182+func (t *Terminal) printInfo() {183+ t.move(1, 0, true)184+ if t.reading {185+ duration := int64(spinnerDuration)186+ idx := (time.Now().UnixNano() % (duration * int64(len(_spinner)))) / duration187+ C.CPrint(C.ColSpinner, true, _spinner[idx])188+ }189+190+ t.move(1, 2, false)191+ output := fmt.Sprintf("%d/%d", t.merger.Length(), t.count)192+ if t.multi && len(t.selected) > 0 {193+ output += fmt.Sprintf(" (%d)", len(t.selected))194+ }195+ if t.progress > 0 && t.progress < 100 {196+ output += fmt.Sprintf(" (%d%%)", t.progress)197+ }198+ C.CPrint(C.ColInfo, false, output)199+}200+201+func (t *Terminal) printList() {202+ t.constrain()203+204+ maxy := maxItems()205+ count := t.merger.Length() - t.offset206+ for i := 0; i < maxy; i++ {207+ t.move(i+2, 0, true)208+ if i < count {209+ t.printItem(t.merger.Get(t.listIndex(i+t.offset)), i == t.cy-t.offset)210+ }211+ }212+}213+214+func (t *Terminal) printItem(item *Item, current bool) {215+ _, selected := t.selected[item.text]216+ if current {217+ C.CPrint(C.ColCursor, true, ">")218+ if selected {219+ C.CPrint(C.ColCurrent, true, ">")220+ } else {221+ C.CPrint(C.ColCurrent, true, " ")222+ }223+ t.printHighlighted(item, true, C.ColCurrent, C.ColCurrentMatch)224+ } else {225+ C.CPrint(C.ColCursor, true, " ")226+ if selected {227+ C.CPrint(C.ColSelected, true, ">")228+ } else {229+ C.Print(" ")230+ }231+ t.printHighlighted(item, false, 0, C.ColMatch)232+ }233+}234+235+func trimRight(runes []rune, width int) ([]rune, int) {236+ currentWidth := displayWidth(runes)237+ trimmed := 0238+239+ for currentWidth > width && len(runes) > 0 {240+ sz := len(runes)241+ currentWidth -= runewidth.RuneWidth(runes[sz-1])242+ runes = runes[:sz-1]243+ trimmed++244+ }245+ return runes, trimmed246+}247+248+func trimLeft(runes []rune, width int) ([]rune, int32) {249+ currentWidth := displayWidth(runes)250+ var trimmed int32251+252+ for currentWidth > width && len(runes) > 0 {253+ currentWidth -= runewidth.RuneWidth(runes[0])254+ runes = runes[1:]255+ trimmed++256+ }257+ return runes, trimmed258+}259+260+func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int) {261+ var maxe int32262+ for _, offset := range item.offsets {263+ if offset[1] > maxe {264+ maxe = offset[1]265+ }266+ }267+268+ // Overflow269+ text := []rune(*item.text)270+ offsets := item.offsets271+ maxWidth := C.MaxX() - 3272+ fullWidth := displayWidth(text)273+ if fullWidth > maxWidth {274+ // Stri..275+ matchEndWidth := displayWidth(text[:maxe])276+ if matchEndWidth <= maxWidth-2 {277+ text, _ = trimRight(text, maxWidth-2)278+ text = append(text, []rune("..")...)279+ } else {280+ // Stri..281+ if matchEndWidth < fullWidth-2 {282+ text = append(text[:maxe], []rune("..")...)283+ }284+ // ..ri..285+ var diff int32286+ text, diff = trimLeft(text, maxWidth-2)287+288+ // Transform offsets289+ offsets = make([]Offset, len(item.offsets))290+ for idx, offset := range item.offsets {291+ b, e := offset[0], offset[1]292+ b += 2 - diff293+ e += 2 - diff294+ b = util.Max32(b, 2)295+ if b < e {296+ offsets[idx] = Offset{b, e}297+ }298+ }299+ text = append([]rune(".."), text...)300+ }301+ }302+303+ sort.Sort(ByOrder(offsets))304+ var index int32305+ for _, offset := range offsets {306+ b := util.Max32(index, offset[0])307+ e := util.Max32(index, offset[1])308+ C.CPrint(col1, bold, string(text[index:b]))309+ C.CPrint(col2, bold, string(text[b:e]))310+ index = e311+ }312+ if index < int32(len(text)) {313+ C.CPrint(col1, bold, string(text[index:]))314+ }315+}316+317+func (t *Terminal) printAll() {318+ t.printList()319+ t.printInfo()320+ t.printPrompt()321+}322+323+func (t *Terminal) refresh() {324+ if !t.suppress {325+ C.Refresh()326+ }327+}328+329+func (t *Terminal) delChar() bool {330+ if len(t.input) > 0 && t.cx < len(t.input) {331+ t.input = append(t.input[:t.cx], t.input[t.cx+1:]...)332+ return true333+ }334+ return false335+}336+337+func findLastMatch(pattern string, str string) int {338+ rx, err := regexp.Compile(pattern)339+ if err != nil {340+ return -1341+ }342+ locs := rx.FindAllStringIndex(str, -1)343+ if locs == nil {344+ return -1345+ }346+ return locs[len(locs)-1][0]347+}348+349+func findFirstMatch(pattern string, str string) int {350+ rx, err := regexp.Compile(pattern)351+ if err != nil {352+ return -1353+ }354+ loc := rx.FindStringIndex(str)355+ if loc == nil {356+ return -1357+ }358+ return loc[0]359+}360+361+func copySlice(slice []rune) []rune {362+ ret := make([]rune, len(slice))363+ copy(ret, slice)364+ return ret365+}366+367+func (t *Terminal) rubout(pattern string) {368+ pcx := t.cx369+ after := t.input[t.cx:]370+ t.cx = findLastMatch(pattern, string(t.input[:t.cx])) + 1371+ t.yanked = copySlice(t.input[t.cx:pcx])372+ t.input = append(t.input[:t.cx], after...)373+}374+375+// Loop is called to start Terminal I/O376+func (t *Terminal) Loop() {377+ { // Late initialization378+ t.mutex.Lock()379+ t.initFunc()380+ t.printPrompt()381+ t.placeCursor()382+ C.Refresh()383+ t.printInfo()384+ t.mutex.Unlock()385+ go func() {386+ timer := time.NewTimer(initialDelay)387+ <-timer.C388+ t.reqBox.Set(reqRefresh, nil)389+ }()390+ }391+392+ go func() {393+ for {394+ t.reqBox.Wait(func(events *util.Events) {395+ defer events.Clear()396+ t.mutex.Lock()397+ for req := range *events {398+ switch req {399+ case reqPrompt:400+ t.printPrompt()401+ case reqInfo:402+ t.printInfo()403+ case reqList:404+ t.printList()405+ case reqRefresh:406+ t.suppress = false407+ case reqRedraw:408+ C.Clear()409+ t.printAll()410+ case reqClose:411+ C.Close()412+ t.output()413+ os.Exit(0)414+ case reqQuit:415+ C.Close()416+ os.Exit(1)417+ }418+ }419+ t.placeCursor()420+ t.mutex.Unlock()421+ })422+ t.refresh()423+ }424+ }()425+426+ looping := true427+ for looping {428+ event := C.GetChar()429+430+ t.mutex.Lock()431+ previousInput := t.input432+ events := []util.EventType{reqPrompt}433+ req := func(evts ...util.EventType) {434+ for _, event := range evts {435+ events = append(events, event)436+ if event == reqClose || event == reqQuit {437+ looping = false438+ }439+ }440+ }441+ toggle := func() {442+ idx := t.listIndex(t.cy)443+ if idx < t.merger.Length() {444+ item := t.merger.Get(idx)445+ if _, found := t.selected[item.text]; !found {446+ t.selected[item.text] = item.origText447+ } else {448+ delete(t.selected, item.text)449+ }450+ req(reqInfo)451+ }452+ }453+ switch event.Type {454+ case C.Invalid:455+ t.mutex.Unlock()456+ continue457+ case C.CtrlA:458+ t.cx = 0459+ case C.CtrlB:460+ if t.cx > 0 {461+ t.cx--462+ }463+ case C.CtrlC, C.CtrlG, C.CtrlQ, C.ESC:464+ req(reqQuit)465+ case C.CtrlD:466+ if !t.delChar() && t.cx == 0 {467+ req(reqQuit)468+ }469+ case C.CtrlE:470+ t.cx = len(t.input)471+ case C.CtrlF:472+ if t.cx < len(t.input) {473+ t.cx++474+ }475+ case C.CtrlH:476+ if t.cx > 0 {477+ t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)478+ t.cx--479+ }480+ case C.Tab:481+ if t.multi && t.merger.Length() > 0 {482+ toggle()483+ t.vmove(-1)484+ req(reqList)485+ }486+ case C.BTab:487+ if t.multi && t.merger.Length() > 0 {488+ toggle()489+ t.vmove(1)490+ req(reqList)491+ }492+ case C.CtrlJ, C.CtrlN:493+ t.vmove(-1)494+ req(reqList)495+ case C.CtrlK, C.CtrlP:496+ t.vmove(1)497+ req(reqList)498+ case C.CtrlM:499+ req(reqClose)500+ case C.CtrlL:501+ req(reqRedraw)502+ case C.CtrlU:503+ if t.cx > 0 {504+ t.yanked = copySlice(t.input[:t.cx])505+ t.input = t.input[t.cx:]506+ t.cx = 0507+ }508+ case C.CtrlW:509+ if t.cx > 0 {510+ t.rubout("\\s\\S")511+ }512+ case C.AltBS:513+ if t.cx > 0 {514+ t.rubout("[^[:alnum:]][[:alnum:]]")515+ }516+ case C.CtrlY:517+ t.input = append(append(t.input[:t.cx], t.yanked...), t.input[t.cx:]...)518+ t.cx += len(t.yanked)519+ case C.Del:520+ t.delChar()521+ case C.PgUp:522+ t.vmove(maxItems() - 1)523+ req(reqList)524+ case C.PgDn:525+ t.vmove(-(maxItems() - 1))526+ req(reqList)527+ case C.AltB:528+ t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1529+ case C.AltF:530+ t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1531+ case C.AltD:532+ ncx := t.cx +533+ findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1534+ if ncx > t.cx {535+ t.yanked = copySlice(t.input[t.cx:ncx])536+ t.input = append(t.input[:t.cx], t.input[ncx:]...)537+ }538+ case C.Rune:539+ prefix := copySlice(t.input[:t.cx])540+ t.input = append(append(prefix, event.Char), t.input[t.cx:]...)541+ t.cx++542+ case C.Mouse:543+ me := event.MouseEvent544+ mx, my := util.Constrain(me.X-len(t.prompt), 0, len(t.input)), me.Y545+ if !t.reverse {546+ my = C.MaxY() - my - 1547+ }548+ if me.S != 0 {549+ // Scroll550+ if t.merger.Length() > 0 {551+ if t.multi && me.Mod {552+ toggle()553+ }554+ t.vmove(me.S)555+ req(reqList)556+ }557+ } else if me.Double {558+ // Double-click559+ if my >= 2 {560+ if t.vset(my-2) && t.listIndex(t.cy) < t.merger.Length() {561+ req(reqClose)562+ }563+ }564+ } else if me.Down {565+ if my == 0 && mx >= 0 {566+ // Prompt567+ t.cx = mx568+ } else if my >= 2 {569+ // List570+ if t.vset(t.offset+my-2) && t.multi && me.Mod {571+ toggle()572+ }573+ req(reqList)574+ }575+ }576+ }577+ changed := string(previousInput) != string(t.input)578+ t.mutex.Unlock() // Must be unlocked before touching reqBox579+580+ if changed {581+ t.eventBox.Set(EvtSearchNew, nil)582+ }583+ for _, event := range events {584+ t.reqBox.Set(event, nil)585+ }586+ }587+}588+589+func (t *Terminal) constrain() {590+ count := t.merger.Length()591+ height := C.MaxY() - 2592+ diffpos := t.cy - t.offset593+594+ t.cy = util.Constrain(t.cy, 0, count-1)595+596+ if t.cy > t.offset+(height-1) {597+ // Ceil598+ t.offset = t.cy - (height - 1)599+ } else if t.offset > t.cy {600+ // Floor601+ t.offset = t.cy602+ }603+604+ // Adjustment605+ if count-t.offset < height {606+ t.offset = util.Max(0, count-height)607+ t.cy = util.Constrain(t.offset+diffpos, 0, count-1)608+ }609+}610+611+func (t *Terminal) vmove(o int) {612+ if t.reverse {613+ t.vset(t.cy - o)614+ } else {615+ t.vset(t.cy + o)616+ }617+}618+619+func (t *Terminal) vset(o int) bool {620+ t.cy = util.Constrain(o, 0, t.merger.Length()-1)621+ return t.cy == o622+}623+624+func maxItems() int {625+ return C.MaxY() - 2626+}added:src/tokenizer_test.go+101 added
1+package fzf2+3+import "testing"4+5+func TestParseRange(t *testing.T) {6+ {7+ i := ".."8+ r, _ := ParseRange(&i)9+ if r.begin != rangeEllipsis || r.end != rangeEllipsis {10+ t.Errorf("%s", r)11+ }12+ }13+ {14+ i := "3.."15+ r, _ := ParseRange(&i)16+ if r.begin != 3 || r.end != rangeEllipsis {17+ t.Errorf("%s", r)18+ }19+ }20+ {21+ i := "3..5"22+ r, _ := ParseRange(&i)23+ if r.begin != 3 || r.end != 5 {24+ t.Errorf("%s", r)25+ }26+ }27+ {28+ i := "-3..-5"29+ r, _ := ParseRange(&i)30+ if r.begin != -3 || r.end != -5 {31+ t.Errorf("%s", r)32+ }33+ }34+ {35+ i := "3"36+ r, _ := ParseRange(&i)37+ if r.begin != 3 || r.end != 3 {38+ t.Errorf("%s", r)39+ }40+ }41+}42+43+func TestTokenize(t *testing.T) {44+ // AWK-style45+ input := " abc: def: ghi "46+ tokens := Tokenize(&input, nil)47+ if *tokens[0].text != "abc: " || tokens[0].prefixLength != 2 {48+ t.Errorf("%s", tokens)49+ }50+51+ // With delimiter52+ tokens = Tokenize(&input, delimiterRegexp(":"))53+ if *tokens[0].text != " abc:" || tokens[0].prefixLength != 0 {54+ t.Errorf("%s", tokens)55+ }56+}57+58+func TestTransform(t *testing.T) {59+ input := " abc: def: ghi: jkl"60+ {61+ tokens := Tokenize(&input, nil)62+ {63+ ranges := splitNth("1,2,3")64+ tx := Transform(tokens, ranges)65+ if *tx.whole != "abc: def: ghi: " {66+ t.Errorf("%s", *tx)67+ }68+ }69+ {70+ ranges := splitNth("1..2,3,2..,1")71+ tx := Transform(tokens, ranges)72+ if *tx.whole != "abc: def: ghi: def: ghi: jklabc: " ||73+ len(tx.parts) != 4 ||74+ *tx.parts[0].text != "abc: def: " || tx.parts[0].prefixLength != 2 ||75+ *tx.parts[1].text != "ghi: " || tx.parts[1].prefixLength != 14 ||76+ *tx.parts[2].text != "def: ghi: jkl" || tx.parts[2].prefixLength != 8 ||77+ *tx.parts[3].text != "abc: " || tx.parts[3].prefixLength != 2 {78+ t.Errorf("%s", *tx)79+ }80+ }81+ }82+ {83+ tokens := Tokenize(&input, delimiterRegexp(":"))84+ {85+ ranges := splitNth("1..2,3,2..,1")86+ tx := Transform(tokens, ranges)87+ if *tx.whole != " abc: def: ghi: def: ghi: jkl abc:" ||88+ len(tx.parts) != 4 ||89+ *tx.parts[0].text != " abc: def:" || tx.parts[0].prefixLength != 0 ||90+ *tx.parts[1].text != " ghi:" || tx.parts[1].prefixLength != 12 ||91+ *tx.parts[2].text != " def: ghi: jkl" || tx.parts[2].prefixLength != 6 ||92+ *tx.parts[3].text != " abc:" || tx.parts[3].prefixLength != 0 {93+ t.Errorf("%s", *tx)94+ }95+ }96+ }97+}98+99+func TestTransformIndexOutOfBounds(t *testing.T) {100+ Transform([]Token{}, splitNth("1"))101+}added:src/tokenizer.go+204 added
1+package fzf2+3+import (4+ "regexp"5+ "strconv"6+ "strings"7+8+ "github.com/junegunn/fzf/src/util"9+)10+11+const rangeEllipsis = 012+13+// Range represents nth-expression14+type Range struct {15+ begin int16+ end int17+}18+19+// Transformed holds the result of tokenization and transformation20+type Transformed struct {21+ whole *string22+ parts []Token23+}24+25+// Token contains the tokenized part of the strings and its prefix length26+type Token struct {27+ text *string28+ prefixLength int29+}30+31+// ParseRange parses nth-expression and returns the corresponding Range object32+func ParseRange(str *string) (Range, bool) {33+ if (*str) == ".." {34+ return Range{rangeEllipsis, rangeEllipsis}, true35+ } else if strings.HasPrefix(*str, "..") {36+ end, err := strconv.Atoi((*str)[2:])37+ if err != nil || end == 0 {38+ return Range{}, false39+ }40+ return Range{rangeEllipsis, end}, true41+ } else if strings.HasSuffix(*str, "..") {42+ begin, err := strconv.Atoi((*str)[:len(*str)-2])43+ if err != nil || begin == 0 {44+ return Range{}, false45+ }46+ return Range{begin, rangeEllipsis}, true47+ } else if strings.Contains(*str, "..") {48+ ns := strings.Split(*str, "..")49+ if len(ns) != 2 {50+ return Range{}, false51+ }52+ begin, err1 := strconv.Atoi(ns[0])53+ end, err2 := strconv.Atoi(ns[1])54+ if err1 != nil || err2 != nil {55+ return Range{}, false56+ }57+ return Range{begin, end}, true58+ }59+60+ n, err := strconv.Atoi(*str)61+ if err != nil || n == 0 {62+ return Range{}, false63+ }64+ return Range{n, n}, true65+}66+67+func withPrefixLengths(tokens []string, begin int) []Token {68+ ret := make([]Token, len(tokens))69+70+ prefixLength := begin71+ for idx, token := range tokens {72+ // Need to define a new local variable instead of the reused token to take73+ // the pointer to it74+ str := token75+ ret[idx] = Token{text: &str, prefixLength: prefixLength}76+ prefixLength += len([]rune(token))77+ }78+ return ret79+}80+81+const (82+ awkNil = iota83+ awkBlack84+ awkWhite85+)86+87+func awkTokenizer(input *string) ([]string, int) {88+ // 9, 3289+ ret := []string{}90+ str := []rune{}91+ prefixLength := 092+ state := awkNil93+ for _, r := range []rune(*input) {94+ white := r == 9 || r == 3295+ switch state {96+ case awkNil:97+ if white {98+ prefixLength++99+ } else {100+ state = awkBlack101+ str = append(str, r)102+ }103+ case awkBlack:104+ str = append(str, r)105+ if white {106+ state = awkWhite107+ }108+ case awkWhite:109+ if white {110+ str = append(str, r)111+ } else {112+ ret = append(ret, string(str))113+ state = awkBlack114+ str = []rune{r}115+ }116+ }117+ }118+ if len(str) > 0 {119+ ret = append(ret, string(str))120+ }121+ return ret, prefixLength122+}123+124+// Tokenize tokenizes the given string with the delimiter125+func Tokenize(str *string, delimiter *regexp.Regexp) []Token {126+ if delimiter == nil {127+ // AWK-style (\S+\s*)128+ tokens, prefixLength := awkTokenizer(str)129+ return withPrefixLengths(tokens, prefixLength)130+ }131+ tokens := delimiter.FindAllString(*str, -1)132+ return withPrefixLengths(tokens, 0)133+}134+135+func joinTokens(tokens []Token) string {136+ ret := ""137+ for _, token := range tokens {138+ ret += *token.text139+ }140+ return ret141+}142+143+// Transform is used to transform the input when --with-nth option is given144+func Transform(tokens []Token, withNth []Range) *Transformed {145+ transTokens := make([]Token, len(withNth))146+ numTokens := len(tokens)147+ whole := ""148+ for idx, r := range withNth {149+ part := ""150+ minIdx := 0151+ if r.begin == r.end {152+ idx := r.begin153+ if idx == rangeEllipsis {154+ part += joinTokens(tokens)155+ } else {156+ if idx < 0 {157+ idx += numTokens + 1158+ }159+ if idx >= 1 && idx <= numTokens {160+ minIdx = idx - 1161+ part += *tokens[idx-1].text162+ }163+ }164+ } else {165+ var begin, end int166+ if r.begin == rangeEllipsis { // ..N167+ begin, end = 1, r.end168+ if end < 0 {169+ end += numTokens + 1170+ }171+ } else if r.end == rangeEllipsis { // N..172+ begin, end = r.begin, numTokens173+ if begin < 0 {174+ begin += numTokens + 1175+ }176+ } else {177+ begin, end = r.begin, r.end178+ if begin < 0 {179+ begin += numTokens + 1180+ }181+ if end < 0 {182+ end += numTokens + 1183+ }184+ }185+ minIdx = util.Max(0, begin-1)186+ for idx := begin; idx <= end; idx++ {187+ if idx >= 1 && idx <= numTokens {188+ part += *tokens[idx-1].text189+ }190+ }191+ }192+ whole += part193+ var prefixLength int194+ if minIdx < numTokens {195+ prefixLength = tokens[minIdx].prefixLength196+ } else {197+ prefixLength = 0198+ }199+ transTokens[idx] = Token{&part, prefixLength}200+ }201+ return &Transformed{202+ whole: &whole,203+ parts: transTokens}204+}modified:.gitignore+2 added
1+bin2+src/fzf/fzf_*3 pkg4 Gemfile.lock5 .DS_Storemodified:install+147 added-51 removed
1 #!/usr/bin/env bash2 3-cd `dirname $BASH_SOURCE`4-fzf_base=`pwd`3+version=0.9.04 6-# ruby executable7-echo -n "Checking Ruby executable ... "8-ruby=`which ruby`9-if [ $? -ne 0 ]; then10- echo "ruby executable not found!"11- exit 112-fi5+cd $(dirname $BASH_SOURCE)6+fzf_base=$(pwd)7 14-# System ruby is preferred15-system_ruby=/usr/bin/ruby16-if [ -x $system_ruby -a $system_ruby != "$ruby" ]; then17- $system_ruby --disable-gems -rcurses -e0 2> /dev/null18- [ $? -eq 0 ] && ruby=$system_ruby19-fi8+ask() {9+ read -p "$1 ([y]/n) " -n 1 -r10+ echo11+ [[ ! $REPLY =~ ^[Nn]$ ]]12+}13 21-echo "OK ($ruby)"14+check_binary() {15+ echo -n " - Checking fzf executable ... "16+ if ! "$fzf_base"/bin/fzf --version; then17+ rm -f "$fzf_base"/bin/fzf18+ binary_error="Error occurred"19+ fi20+}21 23-# Curses-support24-echo -n "Checking Curses support ... "25-"$ruby" -rcurses -e0 2> /dev/null26-if [ $? -eq 0 ]; then27- echo "OK"28-else29- echo "Not found"30- echo "Installing 'curses' gem ... "31- if (( EUID )); then32- /usr/bin/env gem install curses --user-install22+symlink() {23+ echo " - Creating symlink: bin/$1 -> bin/fzf"24+ rm -f "$fzf_base"/bin/fzf25+ ln -sf "$fzf_base"/bin/$1 "$fzf_base"/bin/fzf26+}27+28+download() {29+ echo "Downloading bin/$1 ..."30+ if [ -x "$fzf_base"/bin/$1 ]; then31+ echo " - Already exists"32+ symlink $133+ check_binary && return34+ fi35+ mkdir -p "$fzf_base"/bin && cd "$fzf_base"/bin36+ if [ $? -ne 0 ]; then37+ binary_error="Failed to create bin directory"38+ return39+ fi40+41+ local url=https://github.com/junegunn/fzf-bin/releases/download/$version/${1}.tgz42+ if which curl > /dev/null; then43+ curl -fL $url | tar -xz44+ elif which wget > /dev/null; then45+ wget -O - $url | tar -xz46 else34- /usr/bin/env gem install curses47+ binary_error="curl or wget not found"48+ return49 fi50+51+ if [ ! -f $1 ]; then52+ binary_error="Failed to download ${1}"53+ return54+ fi55+56+ chmod +x $1 && symlink $1 && check_binary57+}58+59+# Try to download binary executable60+archi=$(uname -sm)61+binary_available=162+binary_error=""63+case "$archi" in64+ Darwin\ x86_64) download fzf-$version-darwin_amd64 ;;65+ Darwin\ i*86) download fzf-$version-darwin_386 ;;66+ Linux\ x86_64) download fzf-$version-linux_amd64 ;;67+ Linux\ i*86) download fzf-$version-linux_386 ;;68+ *) binary_available=0 ;;69+esac70+71+cd "$fzf_base"72+if [ -n "$binary_error" ]; then73+ if [ $binary_available -eq 0 ]; then74+ echo "No prebuilt binary for $archi ... "75+ else76+ echo " - $binary_error !!!"77+ fi78+ echo "Installing legacy Ruby version ..."79+80+ # ruby executable81+ echo -n "Checking Ruby executable ... "82+ ruby=`which ruby`83 if [ $? -ne 0 ]; then37- echo38- echo "Failed to install 'curses' gem."39- if [[ $(uname -r) =~ 'ARCH' ]]; then40- echo "Make sure that base-devel package group is installed."41- fi84+ echo "ruby executable not found !!!"85 exit 186 fi44-fi87 46-# Ruby version47-echo -n "Checking Ruby version ... "48-"$ruby" -e 'exit RUBY_VERSION >= "1.9"'49-if [ $? -eq 0 ]; then50- echo ">= 1.9"51- "$ruby" --disable-gems -rcurses -e0 2> /dev/null88+ # System ruby is preferred89+ system_ruby=/usr/bin/ruby90+ if [ -x $system_ruby -a $system_ruby != "$ruby" ]; then91+ $system_ruby --disable-gems -rcurses -e0 2> /dev/null92+ [ $? -eq 0 ] && ruby=$system_ruby93+ fi94+95+ echo "OK ($ruby)"96+97+ # Curses-support98+ echo -n "Checking Curses support ... "99+ "$ruby" -rcurses -e0 2> /dev/null100 if [ $? -eq 0 ]; then53- fzf_cmd="$ruby --disable-gems $fzf_base/fzf"101+ echo "OK"102 else103+ echo "Not found"104+ echo "Installing 'curses' gem ... "105+ if (( EUID )); then106+ /usr/bin/env gem install curses --user-install107+ else108+ /usr/bin/env gem install curses109+ fi110+ if [ $? -ne 0 ]; then111+ echo112+ echo "Failed to install 'curses' gem."113+ if [[ $(uname -r) =~ 'ARCH' ]]; then114+ echo "Make sure that base-devel package group is installed."115+ fi116+ exit 1117+ fi118+ fi119+120+ # Ruby version121+ echo -n "Checking Ruby version ... "122+ "$ruby" -e 'exit RUBY_VERSION >= "1.9"'123+ if [ $? -eq 0 ]; then124+ echo ">= 1.9"125+ "$ruby" --disable-gems -rcurses -e0 2> /dev/null126+ if [ $? -eq 0 ]; then127+ fzf_cmd="$ruby --disable-gems $fzf_base/fzf"128+ else129+ fzf_cmd="$ruby $fzf_base/fzf"130+ fi131+ else132+ echo "< 1.9"133 fzf_cmd="$ruby $fzf_base/fzf"134 fi57-else58- echo "< 1.9"59- fzf_cmd="$ruby $fzf_base/fzf"135 fi136 137 # Auto-completion63-read -p "Do you want to add auto-completion support? ([y]/n) " -n 1 -r64-echo65-[[ ! $REPLY =~ ^[Nn]$ ]]138+ask "Do you want to add auto-completion support?"139 auto_completion=$?140 141 # Key-bindings69-read -p "Do you want to add key bindings? ([y]/n) " -n 1 -r70-echo71-[[ ! $REPLY =~ ^[Nn]$ ]]142+ask "Do you want to add key bindings?"143 key_bindings=$?144 145 echo146 for shell in bash zsh; do4 unmodified lines151 if [ $auto_completion -ne 0 ]; then152 fzf_completion="# $fzf_completion"153 fi154 155+ if [ -n "$binary_error" ]; then84- cat > $src << EOF156+ cat > $src << EOF157 # Setup fzf function158 # ------------------159 unalias fzf 2> /dev/null160 fzf() {5 unmodified lines166 # ---------------167 $fzf_completion168 169 EOF170+ else171+ cat > $src << EOF172+# Setup fzf173+# ---------174+unalias fzf 2> /dev/null175+unset fzf 2> /dev/null176+if [[ ! "\$PATH" =~ "$fzf_base/bin" ]]; then177+ export PATH="$fzf_base/bin:\$PATH"178+fi179 180+# Auto-completion181+# ---------------182+$fzf_completion183+184+EOF185+ fi186+187 if [ $key_bindings -eq 0 ]; then188 if [ $shell = bash ]; then189 cat >> $src << "EOFZF"190 # Key bindings139 unmodified lines330 if [ -n "$(which fish)" ]; then331 has_fish=1332 echo -n "Generate ~/.config/fish/functions/fzf.fish ... "333 mkdir -p ~/.config/fish/functions334+ if [ -n "$binary_error" ]; then246- cat > ~/.config/fish/functions/fzf.fish << EOFZF335+ cat > ~/.config/fish/functions/fzf.fish << EOFZF336 function fzf337 $fzf_cmd \$argv338 end339 EOFZF340+ else341+ cat > ~/.config/fish/functions/fzf.fish << EOFZF342+function fzf343+ $fzf_base/bin/fzf \$argv344+end345+EOFZF346+ fi347 echo "OK"348 349 if [ $key_bindings -eq 0 ]; then350 echo -n "Generate ~/.config/fish/functions/fzf_key_bindings.fish ... "135 unmodified linesmodified:README.md-26 removed
6 unmodified lines7 8 It was heavily inspired by [ctrlp.vim](https://github.com/kien/ctrlp.vim) and9 the likes.10 11-Requirements12-------------13-14-fzf requires Ruby (>= 1.8.5).15-11 Installation12 ------------13 14 Clone this repository and run415 unmodified lines430 background color and make some text unable to read. In that case, try `--black`431 option. And if it solves your problem, I recommend including it in432 `FZF_DEFAULT_OPTS` for further convenience.433 4. If you still have problem, try `--no-256` option or even `--no-color`.439-5. Ruby 1.9 or above is required for correctly displaying unicode characters.434 441-### Ranking algorithm442-443-fzf sorts the result first by the length of the matched substring, then by the444-length of the whole string. However it only does so when the number of matches445-is less than the limit which is by default 1000, in order to avoid the cost of446-sorting a large list and limit the response time of the query.447-448-This limit can be adjusted with `-s` option, or with the environment variable449-`FZF_DEFAULT_OPTS`.450-451-```sh452-export FZF_DEFAULT_OPTS="--sort 20000"453-```454-435 ### Respecting `.gitignore`, `.hgignore`, and `svn:ignore`436 437 [ag](https://github.com/ggreer/the_silver_searcher) or438 [pt](https://github.com/monochromegane/the_platinum_searcher) will do the85 unmodified lines524 end525 end526 ```527 548-### Windows549-550-fzf works on [Cygwin](http://www.cygwin.com/) and551-[MSYS2](http://sourceforge.net/projects/msys2/). You may need to use `--black`552-option on MSYS2 to avoid rendering issues.553-528 ### Handling UTF-8 NFD paths on OSX529 530 Use iconv to convert NFD paths to NFC:531 14 unmodified lines