Skip to content
Myr

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

40 files+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 obtaining
18 unmodified lines
24let s:min_tmux_width = 1025let s:min_tmux_height = 326let s:default_tmux_height = '40%'27let s:launcher = 'xterm -e bash -ic %s'28let s:fzf_go = expand('<sfile>:h:h').'/bin/fzf'29let s:fzf_rb = expand('<sfile>:h:h').'/fzf'3031let s:cpo_save = &cpo32set cpo&vim
1 unmodified line
34function! 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 lines
added:src/algo/algo_test.go+44 added
1package algo23import (4 "strings"5 "testing"6)78func 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}2021func 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}2728func 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}3334func 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}3940func 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
1package algo23import "strings"45/*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 */1213// FuzzyMatch performs fuzzy-match14func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {15 runes := []rune(*input)1617 // 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 := -12930 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 }4647 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}6566// ExactMatchStrings performs exact-match using strings package.67// Currently not used.68func 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 }7576 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}8283// 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_algorithm90func 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 }9798 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}116117// PrefixMatch performs prefix-match118func PrefixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {119 runes := []rune(*input)120 if len(runes) < len(pattern) {121 return -1, -1122 }123124 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}135136// SuffixMatch performs suffix-match137func 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 }144145 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
1package curses23/*4#include <ncurses.h>5#include <locale.h>6#cgo LDFLAGS: -lncurses7void swapOutput() {8 FILE* temp = stdout;9 stdout = stderr;10 stderr = temp;11}12*/13import "C"1415import (16 "os"17 "os/signal"18 "syscall"19 "time"20 "unicode/utf8"21)2223// Types of user action24const (25 Rune = iota2627 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 ESC5455 Invalid56 Mouse5758 BTab5960 Del61 PgUp62 PgDn6364 AltB65 AltF66 AltD67 AltBS68)6970// Pallete71const (72 ColNormal = iota73 ColPrompt74 ColMatch75 ColCurrent76 ColCurrentMatch77 ColSpinner78 ColInfo79 ColCursor80 ColSelected81)8283const (84 doubleClickDuration = 500 * time.Millisecond85)8687type Event struct {88 Type int89 Char rune90 MouseEvent *MouseEvent91}9293type MouseEvent struct {94 Y int95 X int96 S int97 Down bool98 Double bool99 Mod bool100}101102var (103 _buf []byte104 _in *os.File105 _color func(int, bool) C.int106 _prevDownTime time.Time107 _prevDownY int108 _clickY []int109)110111func init() {112 _prevDownTime = time.Unix(0, 0)113 _clickY = []int{}114}115116func 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}126127func 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}144145func MaxX() int {146 return int(C.COLS)147}148149func MaxY() int {150 return int(C.LINES)151}152153func 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}162163func 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 }173174 C.swapOutput()175176 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 undef184185 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 }()192193 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}226227func Close() {228 C.endwin()229 C.swapOutput()230}231232func GetBytes() []byte {233 c := getch(false)234 _buf = append(_buf, byte(c))235236 for {237 c = getch(true)238 if c == -1 {239 break240 }241 _buf = append(_buf, byte(c))242 }243244 return _buf245}246247// 27 (91 79) 77 type x y248func 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}284285func 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}368369func GetChar() Event {370 if len(_buf) == 0 {371 _buf = GetBytes()372 }373 if len(_buf) == 0 {374 panic("Empty _buffer")375 }376377 sz := 1378 defer func() {379 _buf = _buf[sz:]380 }()381382 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 }390391 // 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}399400func Move(y int, x int) {401 C.move(C.int(y), C.int(x))402}403404func MoveAndClear(y int, x int) {405 Move(y, x)406 C.clrtoeol()407}408409func Print(text string) {410 C.addstr(C.CString(text))411}412413func CPrint(pair int, bold bool, text string) {414 attr := _color(pair, bold)415 C.attron(attr)416 Print(text)417 C.attroff(attr)418}419420func Clear() {421 C.clear()422}423424func Refresh() {425 C.refresh()426}
added:src/fzf/main.go+7 added
1package main23import "github.com/junegunn/fzf/src"45func main() {6 fzf.Run(fzf.ParseOptions())7}
added:src/util/atomicbool_test.go+17 added
1package util23import "testing"45func TestAtomicBool(t *testing.T) {6 if !NewAtomicBool(true).Get() || NewAtomicBool(false).Get() {7 t.Error("Invalid initial value")8 }910 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
1package util23import "sync"45// AtomicBool is a boxed-class that provides synchronized access to the6// underlying boolean value7type AtomicBool struct {8 mutex sync.Mutex9 state bool10}1112// NewAtomicBool returns a new AtomicBool13func NewAtomicBool(initialState bool) *AtomicBool {14 return &AtomicBool{15 mutex: sync.Mutex{},16 state: initialState}17}1819// Get returns the current boolean value synchronously20func (a *AtomicBool) Get() bool {21 a.mutex.Lock()22 defer a.mutex.Unlock()23 return a.state24}2526// Set updates the boolean value synchronously27func (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
1package util23import "testing"45// fzf events6const (7 EvtReadNew EventType = iota8 EvtReadFin9 EvtSearchNew10 EvtSearchProgress11 EvtSearchFin12 EvtClose13)1415func TestEventBox(t *testing.T) {16 eb := NewEventBox()1718 // Wait should return immediately19 ch := make(chan bool)2021 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 }()3536 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 }5455 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
1package util23import "sync"45// EventType is the type for fzf events6type EventType int78// Events is a type that associates EventType to any data9type Events map[EventType]interface{}1011// EventBox is used for coordinating events12type EventBox struct {13 events Events14 cond *sync.Cond15 ignore map[EventType]bool16}1718// NewEventBox returns a new EventBox19func NewEventBox() *EventBox {20 return &EventBox{21 events: make(Events),22 cond: sync.NewCond(&sync.Mutex{}),23 ignore: make(map[EventType]bool)}24}2526// Wait blocks the goroutine until signaled27func (b *EventBox) Wait(callback func(*Events)) {28 b.cond.L.Lock()29 defer b.cond.L.Unlock()3031 if len(b.events) == 0 {32 b.cond.Wait()33 }3435 callback(&b.events)36}3738// Set turns on the event type on the box39func (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}4748// Clear clears the events49// Unsynchronized; should be called within Wait routine50func (events *Events) Clear() {51 for event := range *events {52 delete(*events, event)53 }54}5556// Peak peaks at the event box if the given event is set57func (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}6364// Watch deletes the events from the ignore list65func (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}7273// Unwatch adds the events to the ignore list74func (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
1package util23import "testing"45func TestMax(t *testing.T) {6 if Max(-2, 5, 1, 4, 3) != 5 {7 t.Error("Invalid result")8 }9}1011func 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 }1819 if Constrain(5, -1, 3) != 3 {20 t.Error("Expected", 3)21 }22}
added:src/util/util.go+56 added
1package util23// #include <unistd.h>4import "C"56import (7 "os"8 "time"9)1011// Max returns the largest integer12func Max(first int, items ...int) int {13 max := first14 for _, item := range items {15 if item > max {16 max = item17 }18 }19 return max20}2122// Max32 returns the largest 32-bit integer23func Max32(first int32, second int32) int32 {24 if first > second {25 return first26 }27 return second28}2930// Constrain limits the given integer with the upper and lower bounds31func 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}4041// DurWithin limits the given time.Duration with the upper and lower bounds42func 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}5253// IsTty returns true is stdin is a terminal54func IsTty() bool {55 return int(C.isatty(C.int(os.Stdin.Fd()))) != 056}
added:src/cache_test.go+40 added
1package fzf23import "testing"45func 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)1516 { // 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
1package fzf23import "sync"45// QueryCache associates strings to lists of items6type QueryCache map[string][]*Item78// ChunkCache associates Chunk and query string to lists of items9type ChunkCache struct {10 mutex sync.Mutex11 cache map[*Chunk]*QueryCache12}1314// NewChunkCache returns a new ChunkCache15func NewChunkCache() ChunkCache {16 return ChunkCache{sync.Mutex{}, make(map[*Chunk]*QueryCache)}17}1819// Add adds the list to the cache20func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {21 if len(key) == 0 || !chunk.IsFull() {22 return23 }2425 cc.mutex.Lock()26 defer cc.mutex.Unlock()2728 qc, ok := cc.cache[chunk]29 if !ok {30 cc.cache[chunk] = &QueryCache{}31 qc = cc.cache[chunk]32 }33 (*qc)[key] = list34}3536// Find is called to lookup ChunkCache37func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Item, bool) {38 if len(key) == 0 || !chunk.IsFull() {39 return nil, false40 }4142 cc.mutex.Lock()43 defer cc.mutex.Unlock()4445 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
1package fzf23import (4 "fmt"5 "testing"6)78func 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 })1213 // Snapshot14 snapshot, count := cl.Snapshot()15 if len(snapshot) > 0 || count > 0 {16 t.Error("Snapshot should be empty now")17 }1819 // Add some data20 cl.Push("hello")21 cl.Push("world")2223 // Previously created snapshot should remain the same24 if len(snapshot) > 0 {25 t.Error("Snapshot should not have changed")26 }2728 // 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 }3334 // 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 }4647 // Add more data48 for i := 0; i < ChunkSize*2; i++ {49 cl.Push(fmt.Sprintf("item %d", i))50 }5152 // Previous snapshot should remain the same53 if len(snapshot) != 1 {54 t.Error("Snapshot should stay the same")55 }5657 // 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 }6667 cl.Push("hello")68 cl.Push("world")6970 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
1package fzf23import "sync"45// Capacity of each chunk6const ChunkSize int = 10078// Chunk is a list of Item pointers whose size has the upper limit of ChunkSize9type Chunk []*Item // >>> []Item1011// ItemBuilder is a closure type that builds Item object from a pointer to a12// string and an integer13type ItemBuilder func(*string, int) *Item1415// ChunkList is a list of Chunks16type ChunkList struct {17 chunks []*Chunk18 count int19 mutex sync.Mutex20 trans ItemBuilder21}2223// NewChunkList returns a new ChunkList24func NewChunkList(trans ItemBuilder) *ChunkList {25 return &ChunkList{26 chunks: []*Chunk{},27 count: 0,28 mutex: sync.Mutex{},29 trans: trans}30}3132func (c *Chunk) push(trans ItemBuilder, data *string, index int) {33 *c = append(*c, trans(data, index))34}3536// IsFull returns true if the Chunk is full37func (c *Chunk) IsFull() bool {38 return len(*c) == ChunkSize39}4041func (cl *ChunkList) lastChunk() *Chunk {42 return cl.chunks[len(cl.chunks)-1]43}4445// CountItems returns the total number of Items46func CountItems(cs []*Chunk) int {47 if len(cs) == 0 {48 return 049 }50 return ChunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))51}5253// Push adds the item to the list54func (cl *ChunkList) Push(data string) {55 cl.mutex.Lock()56 defer cl.mutex.Unlock()5758 if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {59 newChunk := Chunk(make([]*Item, 0, ChunkSize))60 cl.chunks = append(cl.chunks, &newChunk)61 }6263 cl.lastChunk().push(cl.trans, &data, cl.count)64 cl.count++65}6667// Snapshot returns immutable snapshot of the ChunkList68func (cl *ChunkList) Snapshot() ([]*Chunk, int) {69 cl.mutex.Lock()70 defer cl.mutex.Unlock()7172 ret := make([]*Chunk, len(cl.chunks))73 copy(ret, cl.chunks)7475 // Duplicate the last chunk76 if cnt := len(ret); cnt > 0 {77 ret[cnt-1] = ret[cnt-1].dupe()78 }79 return ret, cl.count80}8182func (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
1package fzf23import (4 "github.com/junegunn/fzf/src/util"5)67// Current version8const Version = "0.9.0"910// fzf events11const (12 EvtReadNew util.EventType = iota13 EvtReadFin14 EvtSearchNew15 EvtSearchProgress16 EvtSearchFin17 EvtClose18)
added:src/core.go+196 added
1/*2Package fzf implements fzf, a command-line fuzzy finder.34The MIT License (MIT)56Copyright (c) 2015 Junegunn Choi78Permission is hereby granted, free of charge, to any person obtaining a copy9of this software and associated documentation files (the "Software"), to deal10in the Software without restriction, including without limitation the rights11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell12copies of the Software, and to permit persons to whom the Software is13furnished to do so, subject to the following conditions:1415The above copyright notice and this permission notice shall be included in16all copies or substantial portions of the Software.1718THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN24THE SOFTWARE.25*/26package fzf2728import (29 "fmt"30 "os"31 "runtime"32 "time"3334 "github.com/junegunn/fzf/src/util"35)3637const coordinatorDelayMax time.Duration = 100 * time.Millisecond38const coordinatorDelayStep time.Duration = 10 * time.Millisecond3940func initProcs() {41 runtime.GOMAXPROCS(runtime.NumCPU())42}4344/*45Reader -> EvtReadFin46Reader -> EvtReadNew -> Matcher (restart)47Terminal -> EvtSearchNew -> Matcher (restart)48Matcher -> EvtSearchProgress -> Terminal (update info)49Matcher -> EvtSearchFin -> Terminal (update list)50*/5152// Run starts fzf53func Run(options *Options) {54 initProcs()5556 opts := ParseOptions()5758 if opts.Version {59 fmt.Println(Version)60 os.Exit(0)61 }6263 // Event channel64 eventBox := util.NewEventBox()6566 // 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 }8687 // Reader88 reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}89 go reader.ReadSource()9091 // 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)9798 // 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))112113 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 }126127 snapshot, _ := chunkList.Snapshot()128 merger, cancelled := matcher.scan(MatchRequest{129 chunks: snapshot,130 pattern: pattern}, limit)131132 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 }144145 // Go interactive146 go matcher.Loop()147148 // Terminal I/O149 terminal := NewTerminal(opts, eventBox)150 go terminal.Loop()151152 // 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 {163164 case EvtReadNew, EvtReadFin:165 reading = reading && evt == EvtReadNew166 snapshot, count := chunkList.Snapshot()167 terminal.UpdateCount(count, !reading)168 matcher.Reset(snapshot, terminal.Input(), false)169170 case EvtSearchNew:171 snapshot, _ := chunkList.Snapshot()172 matcher.Reset(snapshot, terminal.Input(), true)173 delay = false174175 case EvtSearchProgress:176 switch val := value.(type) {177 case float32:178 terminal.UpdateProgress(val)179 }180181 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
1FROM base/archlinux:2014.07.032MAINTAINER Junegunn Choi <junegunn.c@gmail.com>34# apt-get5RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git67# Install Go 1.48RUN cd / && curl \9 https://storage.googleapis.com/golang/go1.4.linux-amd64.tar.gz | \10 tar -xz && mv go go1.41112ENV GOPATH /go13ENV GOROOT /go1.414ENV PATH /go1.4/bin:$PATH1516# For i386 build17RUN 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.bash2122# Volume23VOLUME /go2425# Default CMD26CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash27
added:src/Dockerfile.centos+21 added
1FROM centos:centos72MAINTAINER Junegunn Choi <junegunn.c@gmail.com>34# yum5RUN yum install -y git gcc make tar ncurses-devel67# Install Go 1.48RUN cd / && curl \9 https://storage.googleapis.com/golang/go1.4.linux-amd64.tar.gz | \10 tar -xz && mv go go1.41112ENV GOPATH /go13ENV GOROOT /go1.414ENV PATH /go1.4/bin:$PATH1516# Volume17VOLUME /go1819# Default CMD20CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash21
added:src/Dockerfile.ubuntu+26 added
1FROM ubuntu:14.042MAINTAINER Junegunn Choi <junegunn.c@gmail.com>34# apt-get5RUN apt-get update && apt-get -y upgrade && \6 apt-get install -y --force-yes git curl build-essential libncurses-dev78# Install Go 1.49RUN cd / && curl \10 https://storage.googleapis.com/golang/go1.4.linux-amd64.tar.gz | \11 tar -xz && mv go go1.41213ENV GOPATH /go14ENV GOROOT /go1.415ENV PATH /go1.4/bin:$PATH1617# For i386 build18RUN apt-get install -y lib32ncurses5-dev && \19 cd $GOROOT/src && GOARCH=386 ./make.bash2021# Volume22VOLUME /go2324# Default CMD25CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash26
added:src/item_test.go+67 added
1package fzf23import (4 "sort"5 "testing"6)78func 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))1314 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}2122func TestRankComparison(t *testing.T) {23 if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}) ||24 !compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}) ||25 !compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}) ||26 !compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}) {27 t.Error("Invalid order")28 }29}3031// Match length, string length, index32func 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{}}4142 items := []*Item{&item1, &item2}43 sort.Sort(ByRelevance(items))44 if items[0] != &item2 || items[1] != &item1 {45 t.Error(items)46 }4748 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 }5455 // 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
1package fzf23// Offset holds two 32-bit integers denoting the offsets of a matched substring4type Offset [2]int3256// Item represents each input line7type Item struct {8 text *string9 origText *string10 transformed *Transformed11 index uint3212 offsets []Offset13 rank Rank14}1516// Rank is used to sort the search result17type Rank struct {18 matchlen uint1619 strlen uint1620 index uint3221}2223// Rank calculates rank of the Item24func (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}4950// AsString returns the original string51func (i *Item) AsString() string {52 if i.origText != nil {53 return *i.origText54 }55 return *i.text56}5758// ByOrder is for sorting substring offsets59type ByOrder []Offset6061func (a ByOrder) Len() int {62 return len(a)63}6465func (a ByOrder) Swap(i, j int) {66 a[i], a[j] = a[j], a[i]67}6869func (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}7475// ByRelevance is for sorting Items76type ByRelevance []*Item7778func (a ByRelevance) Len() int {79 return len(a)80}8182func (a ByRelevance) Swap(i, j int) {83 a[i], a[j] = a[j], a[i]84}8586func (a ByRelevance) Less(i, j int) bool {87 irank := a[i].Rank(true)88 jrank := a[j].Rank(true)8990 return compareRanks(irank, jrank)91}9293func compareRanks(irank Rank, jrank Rank) bool {94 if irank.matchlen < jrank.matchlen {95 return true96 } else if irank.matchlen > jrank.matchlen {97 return false98 }99100 if irank.strlen < jrank.strlen {101 return true102 } else if irank.strlen > jrank.strlen {103 return false104 }105106 if irank.index <= jrank.index {107 return true108 }109 return false110}
added:src/LICENSE+21 added
1The MIT License (MIT)23Copyright (c) 2015 Junegunn Choi45Permission is hereby granted, free of charge, to any person obtaining a copy6of this software and associated documentation files (the "Software"), to deal7in the Software without restriction, including without limitation the rights8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9copies of the Software, and to permit persons to whom the Software is10furnished to do so, subject to the following conditions:1112The above copyright notice and this permission notice shall be included in13all copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN21THE SOFTWARE.
added:src/Makefile+73 added
1ifndef GOPATH2$(error GOPATH is undefined)3endif45UNAME_S := $(shell uname -s)6ifeq ($(UNAME_S),Darwin)7 GOOS := darwin8else ifeq ($(UNAME_S),Linux)9 GOOS := linux10endif1112ifneq ($(shell uname -m),x86_64)13$(error "Build on $(UNAME_M) is not supported, yet.")14endif1516SOURCES := $(wildcard *.go */*.go)17BINDIR := ../bin1819BINARY32 := fzf-$(GOOS)_38620BINARY64 := fzf-$(GOOS)_amd6421RELEASE32 = fzf-$(shell fzf/$(BINARY64) --version)-$(GOOS)_38622RELEASE64 = fzf-$(shell fzf/$(BINARY64) --version)-$(GOOS)_amd642324all: test release2526release: 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)3132build: fzf/$(BINARY32) fzf/$(BINARY64)3334test:35 go get36 go test -v ./...3738install: $(BINDIR)/fzf3940uninstall:41 rm -f $(BINDIR)/fzf $(BINDIR)/$(BINARY64)4243clean:44 cd fzf && rm -f $(BINARY32) $(BINARY64) $(RELEASE32).tgz $(RELEASE64).tgz4546fzf/$(BINARY32): $(SOURCES)47 cd fzf && GOARCH=386 CGO_ENABLED=1 go build -o $(BINARY32)4849fzf/$(BINARY64): $(SOURCES)50 cd fzf && go build -o $(BINARY64)5152$(BINDIR)/fzf: fzf/$(BINARY64) | $(BINDIR)53 cp -f fzf/$(BINARY64) $(BINDIR)54 cd $(BINDIR) && ln -sf $(BINARY64) fzf5556$(BINDIR):57 mkdir -p $@5859# Linux distribution to build fzf on60DISTRO := arch6162docker:63 docker build -t junegunn/$(DISTRO)-sandbox - < Dockerfile.$(DISTRO)6465linux: docker66 docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \67 /bin/bash -ci 'cd /go/src/github.com/junegunn/fzf/src; make'6869$(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'7273.PHONY: all build release test install uninstall clean docker linux $(DISTRO)
added:src/matcher.go+214 added
1package fzf23import (4 "fmt"5 "runtime"6 "sort"7 "sync"8 "time"910 "github.com/junegunn/fzf/src/util"11)1213// MatchRequest represents a search request14type MatchRequest struct {15 chunks []*Chunk16 pattern *Pattern17}1819// Matcher is responsible for performing search20type Matcher struct {21 patternBuilder func([]rune) *Pattern22 sort bool23 eventBox *util.EventBox24 reqBox *util.EventBox25 partitions int26 mergerCache map[string]*Merger27}2829const (30 reqRetry util.EventType = iota31 reqReset32)3334const (35 progressMinDuration = 200 * time.Millisecond36)3738// NewMatcher returns a new Matcher39func 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}4950// Loop puts Matcher in action51func (m *Matcher) Loop() {52 prevCount := 05354 for {55 var request MatchRequest5657 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 })6869 // Restart search70 patternString := request.pattern.AsString()71 var merger *Merger72 cancelled := false73 count := CountItems(request.chunks)7475 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 }8788 if !foundCache {89 merger, cancelled = m.scan(request, 0)90 }9192 if !cancelled {93 m.mergerCache[patternString] = merger94 m.eventBox.Set(EvtSearchFin, merger)95 }96 }97}9899func (m *Matcher) sliceChunks(chunks []*Chunk) [][]*Chunk {100 perSlice := len(chunks) / m.partitions101102 // No need to parallelize103 if perSlice == 0 {104 return [][]*Chunk{chunks}105 }106107 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}118119type partialResult struct {120 index int121 matches []*Item122}123124func (m *Matcher) scan(request MatchRequest, limit int) (*Merger, bool) {125 startedAt := time.Now()126127 numChunks := len(request.chunks)128 if numChunks == 0 {129 return EmptyMerger, false130 }131 pattern := request.pattern132 empty := pattern.IsEmpty()133 cancelled := util.NewAtomicBool(false)134135 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{}140141 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 }165166 wait := func() bool {167 cancelled.Set(true)168 waitGroup.Wait()169 return true170 }171172 count := 0173 matchCount := 0174 for matchesInChunk := range countChan {175 count++176 matchCount += matchesInChunk177178 if limit > 0 && matchCount > limit {179 return nil, wait() // For --select-1 and --exit-0180 }181182 if count == numChunks {183 break184 }185186 if !empty && m.reqBox.Peak(reqReset) {187 return nil, wait()188 }189190 if time.Now().Sub(startedAt) > progressMinDuration {191 m.eventBox.Set(EvtSearchProgress, float32(count)/float32(numChunks))192 }193 }194195 partialResults := make([][]*Item, numSlices)196 for range slices {197 partialResult := <-resultChan198 partialResults[partialResult.index] = partialResult.matches199 }200 return NewMerger(partialResults, !empty && m.sort), false201}202203// Reset is called to interrupt/signal the ongoing search204func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool) {205 pattern := m.patternBuilder(patternRunes)206207 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
1package fzf23import (4 "fmt"5 "math/rand"6 "sort"7 "testing"8)910func assert(t *testing.T, cond bool, msg ...string) {11 if !cond {12 t.Error(msg)13 }14}1516func 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}2930func 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}3637func 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}5960func TestMergerUnsorted(t *testing.T) {61 lists, items := buildLists(false)62 cnt := len(items)6364 // 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}7172func TestMergerSorted(t *testing.T) {73 lists, items := buildLists(true)74 cnt := len(items)7576 // 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 }8586 // 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
1package fzf23import "fmt"45// Merger with no data6var EmptyMerger = NewMerger([][]*Item{}, false)78// Merger holds a set of locally sorted lists of items and provides the view of9// a single, globally-sorted list10type Merger struct {11 lists [][]*Item12 merged []*Item13 cursors []int14 sorted bool15 count int16}1718// NewMerger returns a new Merger19func 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}2627 for _, list := range mg.lists {28 mg.count += len(list)29 }30 return &mg31}3233// Length returns the number of items34func (mg *Merger) Length() int {35 return mg.count36}3738// Get returns the pointer to the Item object indexed by the given integer39func (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}5455func (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 }7475 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
1package fzf23import "testing"45func 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}1314func 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
1package fzf23import (4 "fmt"5 "os"6 "regexp"7 "strings"89 "github.com/junegunn/go-shellwords"10)1112const usage = `usage: fzf [options]1314 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)2425 Search result26 -s, --sort Sort the result27 +s, --no-sort Do not sort the result. Keep the sequence unchanged.2829 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: '> ')3738 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 line4445 Environment variables46 FZF_DEFAULT_COMMAND Default command to use when input is tty47 FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m")4849`5051// Mode denotes the current search mode52type Mode int5354// Search modes55const (56 ModeFuzzy Mode = iota57 ModeExtended58 ModeExtendedExact59)6061// Case denotes case-sensitivity of search62type Case int6364// Case-sensitivities65const (66 CaseSmart Case = iota67 CaseIgnore68 CaseRespect69)7071// Options stores the values of command-line options72type 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}9394func 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}116117func help(ok int) {118 os.Stderr.WriteString(usage)119 os.Exit(ok)120}121122func errorExit(msg string) {123 os.Stderr.WriteString(msg + "\n")124 help(1)125}126127func 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}135136func 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}144145func 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}153154func splitNth(str string) []Range {155 if match, _ := regexp.MatchString("^[0-9,-.]+$", str); !match {156 errorExit("invalid format: " + str)157 }158159 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}170171func delimiterRegexp(str string) *regexp.Regexp {172 rx, e := regexp.Compile(str)173 if e != nil {174 str = regexp.QuoteMeta(str)175 }176177 rx, e = regexp.Compile(fmt.Sprintf("(?:.*?%s)|(?:.+?$)", str))178 if e != nil {179 errorExit("invalid regular expression: " + e.Error())180 }181 return rx182}183184func 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}270271// ParseOptions parses command-line options272func ParseOptions() *Options {273 opts := defaultOptions()274275 // Options from Env var276 words, _ := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))277 parseOptions(opts, words)278279 // Options from command-line arguments280 parseOptions(opts, os.Args[1:])281 return opts282}
added:src/pattern_test.go+115 added
1package fzf23import (4 "testing"56 "github.com/junegunn/fzf/src/algo"7)89func 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}3233func 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}4849func TestParseTermsEmpty(t *testing.T) {50 terms := parseTerms(ModeExtended, "' $ ^ !' !^ !$")51 if len(terms) != 0 {52 t.Errorf("%s", terms)53 }54}5556func 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}6768func 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"))8283 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}9293func 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}})100101 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
1package fzf23import (4 "regexp"5 "sort"6 "strings"78 "github.com/junegunn/fzf/src/algo"9)1011const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"1213// fuzzy14// 'exact15// ^exact-prefix16// exact-suffix$17// !not-fuzzy18// !'not-exact19// !^not-exact-prefix20// !not-exact-suffix$2122type termType int2324const (25 termFuzzy termType = iota26 termExact27 termPrefix28 termSuffix29)3031type term struct {32 typ termType33 inv bool34 text []rune35 origText []rune36}3738// Pattern represents search pattern39type 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}4950var (51 _patternCache map[string]*Pattern52 _splitRegex *regexp.Regexp53 _cache ChunkCache54)5556func 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}6364func clearPatternCache() {65 _patternCache = make(map[string]*Pattern)66}6768// BuildPattern builds Pattern object from the given arguments69func BuildPattern(mode Mode, caseMode Case,70 nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {7172 var asString string73 switch mode {74 case ModeExtended, ModeExtendedExact:75 asString = strings.Trim(string(runes), " ")76 default:77 asString = string(runes)78 }7980 cached, found := _patternCache[asString]81 if found {82 return cached83 }8485 caseSensitive, hasInvTerm := true, false86 terms := []term{}8788 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 }9697 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 }106107 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))}116117 ptr.procFun[termFuzzy] = algo.FuzzyMatch118 ptr.procFun[termExact] = algo.ExactMatchNaive119 ptr.procFun[termPrefix] = algo.PrefixMatch120 ptr.procFun[termSuffix] = algo.SuffixMatch121122 _patternCache[asString] = ptr123 return ptr124}125126func 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 }135136 if strings.HasPrefix(text, "!") {137 inv = true138 text = text[1:]139 }140141 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 }153154 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}164165// IsEmpty returns true if the pattern is effectively empty166func (p *Pattern) IsEmpty() bool {167 if p.mode == ModeFuzzy {168 return len(p.text) == 0169 }170 return len(p.terms) == 0171}172173// AsString returns the search query in string type174func (p *Pattern) AsString() string {175 return string(p.text)176}177178// CacheKey is used to build string to be used as the key of result cache179func (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}192193// Match returns the list of matches Items in the given Chunk194func (p *Pattern) Match(chunk *Chunk) []*Item {195 space := chunk196197 // 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 }204205 // ChunkCache: Prefix/suffix match206Loop: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 }221222 var matches []*Item223 if p.mode == ModeFuzzy {224 matches = p.fuzzyMatch(space)225 } else {226 matches = p.extendedMatch(space)227 }228229 if !p.hasInvTerm {230 _cache.Add(chunk, cacheKey, matches)231 }232 return matches233}234235func 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}245246func (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}257258func (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}280281func (p *Pattern) prepareInput(item *Item) *Transformed {282 if item.transformed != nil {283 return item.transformed284 }285286 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}299300func (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
1package fzf23import (4 "testing"56 "github.com/junegunn/fzf/src/util"7)89func 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}1516 // Check EventBox17 if eb.Peak(EvtReadNew) {18 t.Error("EvtReadNew should not be set yet")19 }2021 // 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 }2627 // Check EventBox again28 if !eb.Peak(EvtReadNew) {29 t.Error("EvtReadNew should be set yet")30 }3132 // 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 })3940 // EventBox is cleared41 if eb.Peak(EvtReadNew) {42 t.Error("EvtReadNew should not be set yet")43 }4445 // Failing command46 reader.readFromCommand(`no-such-command`)47 strs = []string{}48 if len(strs) > 0 {49 t.Errorf("%s", strs)50 }5152 // Check EventBox again53 if eb.Peak(EvtReadNew) {54 t.Error("Command failed. EvtReadNew should be set")55 }56}
added:src/reader.go+59 added
1package fzf23import (4 "bufio"5 "io"6 "os"7 "os/exec"89 "github.com/junegunn/fzf/src/util"10)1112const defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`1314// Reader reads from command or standard input15type Reader struct {16 pusher func(string)17 eventBox *util.EventBox18}1920// ReadSource reads data from the default command or from standard input21func (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}3334func (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}4243func (r *Reader) readFromStdin() {44 r.feed(os.Stdin)45}4647func (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
1fzf in Go2=========34This directory contains the source code for the new fzf implementation in5[Go][go].67Upgrade from Ruby version8-------------------------910The install script has been updated to download the right binary for your11system. If you already have installed fzf, simply git-pull the repository and12rerun the install script.1314```sh15cd ~/.fzf16git pull17./install18```1920Motivations21-----------2223### No Ruby dependency2425There have always been complaints about fzf being a Ruby script. To make26matters worse, Ruby 2.1 removed ncurses binding from its standard libary.27Because of the change, users running Ruby 2.1 or above are forced to build C28extensions of curses gem to meet the requirement of fzf. The new Go version29will be distributed as an executable binary so it will be much more accessible30and should be easier to setup.3132### Performance3334Many people have been surprised to see how fast fzf is even when it was35written in Ruby. It stays quite responsive even for 100k+ lines, which is36well above the size of the usual input.3738The new Go version, of course, is significantly faster than that. It has all39the performance optimization techniques used in Ruby implementation and more.40It also doesn't suffer from [GIL][gil], so the search performance scales41proportional to the number of CPU cores. On my MacBook Pro (Mid 2012), the new42version was shown to be an order of magnitude faster on certain cases. It also43starts much faster though the difference may not be noticeable.4445Differences with Ruby version46-----------------------------4748The Go version is designed to be perfectly compatible with the previous Ruby49version. The only behavioral difference is that the new version ignores the50numeric argument to `--sort=N` option and always sorts the result regardless51of the number of matches. The value was introduced to limit the response time52of the query, but the Go version is blazingly fast (almost instant response53even for 1M+ items) so I decided that it's no longer required.5455System requirements56-------------------5758Currently, prebuilt binaries are provided only for OS X and Linux. The install59script will fall back to the legacy Ruby version on the other systems, but if60you have Go 1.4 installed, you can try building it yourself.6162However, as pointed out in [golang.org/doc/install][req], the Go version may63not run on CentOS/RHEL 5.x, and if that's the case, the install script will64choose the Ruby version instead.6566The Go version depends on [ncurses][ncurses] and some Unix system calls, so it67shouldn't run natively on Windows at the moment. But it won't be impossible to68support Windows by falling back to a cross-platform alternative such as69[termbox][termbox] only on Windows. If you're interested in making fzf work on70Windows, please let me know.7172Build73-----7475```sh76# Build fzf executables and tarballs77make7879# Install the executable to ../bin directory80make install8182# Build executables and tarballs for Linux using Docker83make linux84```8586Contribution87------------8889For the time being, I will not add or accept any new features until we can be90sure that the implementation is stable and we have a sufficient number of test91cases. However, fixes for obvious bugs and new test cases are welcome.9293I also care much about the performance of the implementation, so please make94sure that your change does not result in performance regression. And please be95noted that we don't have a quantitative measure of the performance yet.9697Third-party libraries used98--------------------------99100- [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)105106License107-------108109[MIT](LICENSE)110111[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-go
added:src/terminal.go+626 added
1package fzf23import (4 "fmt"5 "os"6 "regexp"7 "sort"8 "sync"9 "time"1011 C "github.com/junegunn/fzf/src/curses"12 "github.com/junegunn/fzf/src/util"1314 "github.com/junegunn/go-runewidth"15)1617// Terminal represents terminal input/output18type 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}4041var _spinner = []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`}4243const (44 reqPrompt util.EventType = iota45 reqInfo46 reqList47 reqRefresh48 reqRedraw49 reqClose50 reqQuit51)5253const (54 initialDelay = 100 * time.Millisecond55 spinnerDuration = 200 * time.Millisecond56)5758// NewTerminal returns new Terminal object59func 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}8283// Input returns current query string84func (t *Terminal) Input() []rune {85 t.mutex.Lock()86 defer t.mutex.Unlock()87 return copySlice(t.input)88}8990// UpdateCount updates the count information91func (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}101102// UpdateProgress updates the search progress103func (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()109110 if changed {111 t.reqBox.Set(reqInfo, nil)112 }113}114115// UpdateList updates Merger to display the list116func (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}124125func (t *Terminal) listIndex(y int) int {126 if t.tac {127 return t.merger.Length() - y - 1128 }129 return y130}131132func (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}150151func displayWidth(runes []rune) int {152 l := 0153 for _, r := range runes {154 l += runewidth.RuneWidth(r)155 }156 return l157}158159func (t *Terminal) move(y int, x int, clear bool) {160 maxy := C.MaxY()161 if !t.reverse {162 y = maxy - y - 1163 }164165 if clear {166 C.MoveAndClear(y, x)167 } else {168 C.Move(y, x)169 }170}171172func (t *Terminal) placeCursor() {173 t.move(0, len(t.prompt)+displayWidth(t.input[:t.cx]), false)174}175176func (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}181182func (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 }189190 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}200201func (t *Terminal) printList() {202 t.constrain()203204 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}213214func (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}234235func trimRight(runes []rune, width int) ([]rune, int) {236 currentWidth := displayWidth(runes)237 trimmed := 0238239 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}247248func trimLeft(runes []rune, width int) ([]rune, int32) {249 currentWidth := displayWidth(runes)250 var trimmed int32251252 for currentWidth > width && len(runes) > 0 {253 currentWidth -= runewidth.RuneWidth(runes[0])254 runes = runes[1:]255 trimmed++256 }257 return runes, trimmed258}259260func (*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 }267268 // 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)287288 // 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 }302303 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}316317func (t *Terminal) printAll() {318 t.printList()319 t.printInfo()320 t.printPrompt()321}322323func (t *Terminal) refresh() {324 if !t.suppress {325 C.Refresh()326 }327}328329func (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}336337func 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}348349func 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}360361func copySlice(slice []rune) []rune {362 ret := make([]rune, len(slice))363 copy(ret, slice)364 return ret365}366367func (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}374375// Loop is called to start Terminal I/O376func (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 }391392 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 }()425426 looping := true427 for looping {428 event := C.GetChar()429430 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 reqBox579580 if changed {581 t.eventBox.Set(EvtSearchNew, nil)582 }583 for _, event := range events {584 t.reqBox.Set(event, nil)585 }586 }587}588589func (t *Terminal) constrain() {590 count := t.merger.Length()591 height := C.MaxY() - 2592 diffpos := t.cy - t.offset593594 t.cy = util.Constrain(t.cy, 0, count-1)595596 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 }603604 // 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}610611func (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}618619func (t *Terminal) vset(o int) bool {620 t.cy = util.Constrain(o, 0, t.merger.Length()-1)621 return t.cy == o622}623624func maxItems() int {625 return C.MaxY() - 2626}
added:src/tokenizer_test.go+101 added
1package fzf23import "testing"45func 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}4243func 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 }5051 // With delimiter52 tokens = Tokenize(&input, delimiterRegexp(":"))53 if *tokens[0].text != " abc:" || tokens[0].prefixLength != 0 {54 t.Errorf("%s", tokens)55 }56}5758func 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}9899func TestTransformIndexOutOfBounds(t *testing.T) {100 Transform([]Token{}, splitNth("1"))101}
added:src/tokenizer.go+204 added
1package fzf23import (4 "regexp"5 "strconv"6 "strings"78 "github.com/junegunn/fzf/src/util"9)1011const rangeEllipsis = 01213// Range represents nth-expression14type Range struct {15 begin int16 end int17}1819// Transformed holds the result of tokenization and transformation20type Transformed struct {21 whole *string22 parts []Token23}2425// Token contains the tokenized part of the strings and its prefix length26type Token struct {27 text *string28 prefixLength int29}3031// ParseRange parses nth-expression and returns the corresponding Range object32func 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 }5960 n, err := strconv.Atoi(*str)61 if err != nil || n == 0 {62 return Range{}, false63 }64 return Range{n, n}, true65}6667func withPrefixLengths(tokens []string, begin int) []Token {68 ret := make([]Token, len(tokens))6970 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}8081const (82 awkNil = iota83 awkBlack84 awkWhite85)8687func 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}123124// Tokenize tokenizes the given string with the delimiter125func 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}134135func joinTokens(tokens []Token) string {136 ret := ""137 for _, token := range tokens {138 ret += *token.text139 }140 return ret141}142143// Transform is used to transform the input when --with-nth option is given144func 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
1bin2src/fzf/fzf_*3pkg4Gemfile.lock5.DS_Store
modified:install+147 added-51 removed
1#!/usr/bin/env bash23cd `dirname $BASH_SOURCE`4fzf_base=`pwd`3version=0.9.046# ruby executable7echo -n "Checking Ruby executable ... "8ruby=`which ruby`9if [ $? -ne 0 ]; then10 echo "ruby executable not found!"11 exit 112fi5cd $(dirname $BASH_SOURCE)6fzf_base=$(pwd)714# System ruby is preferred15system_ruby=/usr/bin/ruby16if [ -x $system_ruby -a $system_ruby != "$ruby" ]; then17 $system_ruby --disable-gems -rcurses -e0 2> /dev/null18 [ $? -eq 0 ] && ruby=$system_ruby19fi8ask() {9 read -p "$1 ([y]/n) " -n 1 -r10 echo11 [[ ! $REPLY =~ ^[Nn]$ ]]12}1321echo "OK ($ruby)"14check_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}2123# Curses-support24echo -n "Checking Curses support ... "25"$ruby" -rcurses -e0 2> /dev/null26if [ $? -eq 0 ]; then27 echo "OK"28else29 echo "Not found"30 echo "Installing 'curses' gem ... "31 if (( EUID )); then32 /usr/bin/env gem install curses --user-install22symlink() {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}2728download() {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 fi4041 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 fi5051 if [ ! -f $1 ]; then52 binary_error="Failed to download ${1}"53 return54 fi5556 chmod +x $1 && symlink $1 && check_binary57}5859# Try to download binary executable60archi=$(uname -sm)61binary_available=162binary_error=""63case "$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 ;;69esac7071cd "$fzf_base"72if [ -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 ..."7980 # 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 fi44fi8746# Ruby version47echo -n "Checking Ruby version ... "48"$ruby" -e 'exit RUBY_VERSION >= "1.9"'49if [ $? -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 fi9495 echo "OK ($ruby)"9697 # 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 fi119120 # 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 fi57else58 echo "< 1.9"59 fzf_cmd="$ruby $fzf_base/fzf"135fi136137# Auto-completion63read -p "Do you want to add auto-completion support? ([y]/n) " -n 1 -r64echo65[[ ! $REPLY =~ ^[Nn]$ ]]138ask "Do you want to add auto-completion support?"139auto_completion=$?140141# Key-bindings69read -p "Do you want to add key bindings? ([y]/n) " -n 1 -r70echo71[[ ! $REPLY =~ ^[Nn]$ ]]142ask "Do you want to add key bindings?"143key_bindings=$?144145echo146for shell in bash zsh; do
4 unmodified lines
151 if [ $auto_completion -ne 0 ]; then152 fzf_completion="# $fzf_completion"153 fi154155 if [ -n "$binary_error" ]; then84 cat > $src << EOF156 cat > $src << EOF157# Setup fzf function158# ------------------159unalias fzf 2> /dev/null160fzf() {
5 unmodified lines
166# ---------------167$fzf_completion168169EOF170 else171 cat > $src << EOF172# Setup fzf173# ---------174unalias fzf 2> /dev/null175unset fzf 2> /dev/null176if [[ ! "\$PATH" =~ "$fzf_base/bin" ]]; then177 export PATH="$fzf_base/bin:\$PATH"178fi179180# Auto-completion181# ---------------182$fzf_completion183184EOF185 fi186187 if [ $key_bindings -eq 0 ]; then188 if [ $shell = bash ]; then189 cat >> $src << "EOFZF"190# Key bindings
139 unmodified lines
330if [ -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 << EOFZF336function fzf337 $fzf_cmd \$argv338end339EOFZF340 else341 cat > ~/.config/fish/functions/fzf.fish << EOFZF342function fzf343 $fzf_base/bin/fzf \$argv344end345EOFZF346 fi347 echo "OK"348349 if [ $key_bindings -eq 0 ]; then350 echo -n "Generate ~/.config/fish/functions/fzf_key_bindings.fish ... "
135 unmodified lines
modified:README.md-26 removed
6 unmodified lines
78It was heavily inspired by [ctrlp.vim](https://github.com/kien/ctrlp.vim) and9the likes.1011Requirements12------------1314fzf requires Ruby (>= 1.8.5).1511Installation12------------1314Clone this repository and run
415 unmodified lines
430 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.4334. If you still have problem, try `--no-256` option or even `--no-color`.4395. Ruby 1.9 or above is required for correctly displaying unicode characters.434441### Ranking algorithm442443fzf sorts the result first by the length of the matched substring, then by the444length of the whole string. However it only does so when the number of matches445is less than the limit which is by default 1000, in order to avoid the cost of446sorting a large list and limit the response time of the query.447448This limit can be adjusted with `-s` option, or with the environment variable449`FZF_DEFAULT_OPTS`.450451```sh452export FZF_DEFAULT_OPTS="--sort 20000"453```454435### Respecting `.gitignore`, `.hgignore`, and `svn:ignore`436437[ag](https://github.com/ggreer/the_silver_searcher) or438[pt](https://github.com/monochromegane/the_platinum_searcher) will do the
85 unmodified lines
524 end525end526```527548### Windows549550fzf works on [Cygwin](http://www.cygwin.com/) and551[MSYS2](http://sourceforge.net/projects/msys2/). You may need to use `--black`552option on MSYS2 to avoid rendering issues.553528### Handling UTF-8 NFD paths on OSX529530Use iconv to convert NFD paths to NFC:531
14 unmodified lines