Micro-optimizations
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Make structs smaller - Introduce Result struct and use it to represent matched items instead of reusing Item struct for that purpose - Avoid unnecessary memory allocation - Avoid growing slice from the initial capacity - Code cleanup
authored by Junegunn Choi · committed by Junegunn Choi · parent f7f01d1 · Browse files · 19 files·+234 added−568 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+234 added−568 removed
- other:+234 added−568 removed
Provenance
- Commit
37dc273- Tree
d90f5e9- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
f7f01d1
19 files changed+234 added−568 removed
modified:src/algo/algo_test.go+1 added-1 removed
5 unmodified lines6 7 "github.com/junegunn/fzf/src/util"8 )9 10-func assertMatch(t *testing.T, fun func(bool, bool, util.Chars, []rune) Result, caseSensitive, forward bool, input, pattern string, sidx int32, eidx int32, bonus int32) {10+func assertMatch(t *testing.T, fun func(bool, bool, util.Chars, []rune) Result, caseSensitive, forward bool, input, pattern string, sidx int, eidx int, bonus int) {11 if !caseSensitive {12 pattern = strings.ToLower(pattern)13 }14 res := fun(caseSensitive, forward, util.RunesToChars([]rune(input)), []rune(pattern))83 unmodified linesmodified:src/algo/algo.go+11 added-11 removed
22 unmodified lines23 }24 25 // Result conatins the results of running a match function.26 type Result struct {27- Start int3228- End int3227+ Start int28+ End int29 30 // Items are basically sorted by the lengths of matched substrings.31 // But we slightly adjust the score with bonus for better results.32- Bonus int3232+ Bonus int33 }34 35 type charClass int36 4 unmodified lines41 charLetter42 charNumber43 )44 45-func evaluateBonus(caseSensitive bool, text util.Chars, pattern []rune, sidx int, eidx int) int32 {46- var bonus int3245+func evaluateBonus(caseSensitive bool, text util.Chars, pattern []rune, sidx int, eidx int) int {46+ var bonus int47 pidx := 048 lenPattern := len(pattern)49 consecutive := false50 prevClass := charNonWord11 unmodified lines62 } else {63 class = charNonWord64 }65 66- var point int3266+ var point int67 if prevClass == charNonWord && class != charNonWord {68 // Word boundary69 point = 270 } else if prevClass == charLower && class == charUpper ||109 unmodified lines180 if !forward {181 sidx, eidx = lenRunes-eidx, lenRunes-sidx182 }183 184- return Result{int32(sidx), int32(eidx),184+ return Result{sidx, eidx,185 evaluateBonus(caseSensitive, text, pattern, sidx, eidx)}186 }187 return Result{-1, -1, 0}188 }38 unmodified lines227 } else {228 sidx = lenRunes - (index + 1)229 eidx = lenRunes - (index - lenPattern + 1)230 }231- return Result{int32(sidx), int32(eidx),231+ return Result{sidx, eidx,232 evaluateBonus(caseSensitive, text, pattern, sidx, eidx)}233 }234 } else {235 index -= pidx18 unmodified lines254 return Result{-1, -1, 0}255 }256 }257 lenPattern := len(pattern)258- return Result{0, int32(lenPattern),258+ return Result{0, lenPattern,259 evaluateBonus(caseSensitive, text, pattern, 0, lenPattern)}260 }261 262 // SuffixMatch performs suffix-match15 unmodified lines278 }279 lenPattern := len(pattern)280 sidx := trimmedLen - lenPattern281 eidx := trimmedLen282- return Result{int32(sidx), int32(eidx),282+ return Result{sidx, eidx,283 evaluateBonus(caseSensitive, text, pattern, sidx, eidx)}284 }285 286 // EqualMatch performs equal-match6 unmodified lines293 if !caseSensitive {294 runesStr = strings.ToLower(runesStr)295 }296 if runesStr == string(pattern) {297- return Result{0, int32(len(pattern)), 0}297+ return Result{0, len(pattern), 0}298 }299 return Result{-1, -1, 0}300 }modified:src/util/util.go+10 added
2 unmodified lines3 // #include <unistd.h>4 import "C"5 6 import (7+ "math"8 "os"9 "os/exec"10 "time"11 )51 unmodified lines63 }64 return val65 }66 67+func AsUint16(val int) uint16 {68+ if val > math.MaxUint16 {69+ return math.MaxUint1670+ } else if val < 0 {71+ return 072+ }73+ return uint16(val)74+}75+76 // DurWithin limits the given time.Duration with the upper and lower bounds77 func DurWithin(78 val time.Duration, min time.Duration, max time.Duration) time.Duration {79 if val < min {21 unmodified linesmodified:src/ansi_test.go+42 added-42 removed
14 unmodified lines15 16 src := "hello world"17 var state *ansiState18 clean := "\x1b[0m"19- check := func(assertion func(ansiOffsets []ansiOffset, state *ansiState)) {19+ check := func(assertion func(ansiOffsets *[]ansiOffset, state *ansiState)) {20 output, ansiOffsets, newState := extractColor(src, state, nil)21 state = newState22 if output != "hello world" {23 t.Errorf("Invalid output: {}", output)1 unmodified line25 fmt.Println(src, ansiOffsets, clean)26 assertion(ansiOffsets, state)27 }28 29- check(func(offsets []ansiOffset, state *ansiState) {30- if len(offsets) > 0 {29+ check(func(offsets *[]ansiOffset, state *ansiState) {30+ if offsets != nil {31 t.Fail()32 }33 })34 35 state = nil36 src = "\x1b[0mhello world"37- check(func(offsets []ansiOffset, state *ansiState) {38- if len(offsets) > 0 {37+ check(func(offsets *[]ansiOffset, state *ansiState) {38+ if offsets != nil {39 t.Fail()40 }41 })42 43 state = nil44 src = "\x1b[1mhello world"45- check(func(offsets []ansiOffset, state *ansiState) {46- if len(offsets) != 1 {45+ check(func(offsets *[]ansiOffset, state *ansiState) {46+ if len(*offsets) != 1 {47 t.Fail()48 }49- assert(offsets[0], 0, 11, -1, -1, true)49+ assert((*offsets)[0], 0, 11, -1, -1, true)50 })51 52 state = nil53 src = "\x1b[1mhello \x1b[mworld"54- check(func(offsets []ansiOffset, state *ansiState) {55- if len(offsets) != 1 {54+ check(func(offsets *[]ansiOffset, state *ansiState) {55+ if len(*offsets) != 1 {56 t.Fail()57 }58- assert(offsets[0], 0, 6, -1, -1, true)58+ assert((*offsets)[0], 0, 6, -1, -1, true)59 })60 61 state = nil62 src = "\x1b[1mhello \x1b[Kworld"63- check(func(offsets []ansiOffset, state *ansiState) {64- if len(offsets) != 1 {63+ check(func(offsets *[]ansiOffset, state *ansiState) {64+ if len(*offsets) != 1 {65 t.Fail()66 }67- assert(offsets[0], 0, 11, -1, -1, true)67+ assert((*offsets)[0], 0, 11, -1, -1, true)68 })69 70 state = nil71 src = "hello \x1b[34;45;1mworld"72- check(func(offsets []ansiOffset, state *ansiState) {73- if len(offsets) != 1 {72+ check(func(offsets *[]ansiOffset, state *ansiState) {73+ if len(*offsets) != 1 {74 t.Fail()75 }76- assert(offsets[0], 6, 11, 4, 5, true)76+ assert((*offsets)[0], 6, 11, 4, 5, true)77 })78 79 state = nil80 src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"81- check(func(offsets []ansiOffset, state *ansiState) {82- if len(offsets) != 1 {81+ check(func(offsets *[]ansiOffset, state *ansiState) {82+ if len(*offsets) != 1 {83 t.Fail()84 }85- assert(offsets[0], 6, 11, 4, 5, true)85+ assert((*offsets)[0], 6, 11, 4, 5, true)86 })87 88 state = nil89 src = "hello \x1b[34;45;1mwor\x1b[0mld"90- check(func(offsets []ansiOffset, state *ansiState) {91- if len(offsets) != 1 {90+ check(func(offsets *[]ansiOffset, state *ansiState) {91+ if len(*offsets) != 1 {92 t.Fail()93 }94- assert(offsets[0], 6, 9, 4, 5, true)94+ assert((*offsets)[0], 6, 9, 4, 5, true)95 })96 97 state = nil98 src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"99- check(func(offsets []ansiOffset, state *ansiState) {100- if len(offsets) != 3 {99+ check(func(offsets *[]ansiOffset, state *ansiState) {100+ if len(*offsets) != 3 {101 t.Fail()102 }103- assert(offsets[0], 6, 8, 4, 233, true)104- assert(offsets[1], 8, 9, 161, 233, true)105- assert(offsets[2], 10, 11, 161, -1, false)103+ assert((*offsets)[0], 6, 8, 4, 233, true)104+ assert((*offsets)[1], 8, 9, 161, 233, true)105+ assert((*offsets)[2], 10, 11, 161, -1, false)106 })107 108 // {38,48};5;{38,48}109 state = nil110 src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"111- check(func(offsets []ansiOffset, state *ansiState) {112- if len(offsets) != 2 {111+ check(func(offsets *[]ansiOffset, state *ansiState) {112+ if len(*offsets) != 2 {113 t.Fail()114 }115- assert(offsets[0], 6, 9, 38, 48, true)116- assert(offsets[1], 9, 10, 48, 38, true)115+ assert((*offsets)[0], 6, 9, 38, 48, true)116+ assert((*offsets)[1], 9, 10, 48, 38, true)117 })118 119 src = "hello \x1b[32;1mworld"120- check(func(offsets []ansiOffset, state *ansiState) {121- if len(offsets) != 1 {120+ check(func(offsets *[]ansiOffset, state *ansiState) {121+ if len(*offsets) != 1 {122 t.Fail()123 }124 if state.fg != 2 || state.bg != -1 || !state.bold {125 t.Fail()126 }127- assert(offsets[0], 6, 11, 2, -1, true)127+ assert((*offsets)[0], 6, 11, 2, -1, true)128 })129 130 src = "hello world"131- check(func(offsets []ansiOffset, state *ansiState) {132- if len(offsets) != 1 {131+ check(func(offsets *[]ansiOffset, state *ansiState) {132+ if len(*offsets) != 1 {133 t.Fail()134 }135 if state.fg != 2 || state.bg != -1 || !state.bold {136 t.Fail()137 }138- assert(offsets[0], 0, 11, 2, -1, true)138+ assert((*offsets)[0], 0, 11, 2, -1, true)139 })140 141 src = "hello \x1b[0;38;5;200;48;5;100mworld"142- check(func(offsets []ansiOffset, state *ansiState) {143- if len(offsets) != 2 {142+ check(func(offsets *[]ansiOffset, state *ansiState) {143+ if len(*offsets) != 2 {144 t.Fail()145 }146 if state.fg != 200 || state.bg != 100 || state.bold {147 t.Fail()148 }149- assert(offsets[0], 0, 6, 2, -1, true)150- assert(offsets[1], 6, 11, 200, 100, false)149+ assert((*offsets)[0], 0, 6, 2, -1, true)150+ assert((*offsets)[1], 6, 11, 200, 100, false)151 })152 }modified:src/ansi.go+5 added-2 removed
34 unmodified lines35 func init() {36 ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[mK]")37 }38 39-func extractColor(str string, state *ansiState, proc func(string, *ansiState) bool) (string, []ansiOffset, *ansiState) {39+func extractColor(str string, state *ansiState, proc func(string, *ansiState) bool) (string, *[]ansiOffset, *ansiState) {40 var offsets []ansiOffset41 var output bytes.Buffer42 43 if state != nil {39 unmodified lines83 }84 if proc != nil {85 proc(rest, state)86 }87+ if len(offsets) == 0 {88+ return output.String(), nil, state89+ }87- return output.String(), offsets, state90+ return output.String(), &offsets, state91 }92 93 func interpretCode(ansiCode string, prevState *ansiState) *ansiState {94 // State65 unmodified linesmodified:src/cache_test.go+2 added-2 removed
5 unmodified lines6 cache := NewChunkCache()7 chunk2 := make(Chunk, chunkSize)8 chunk1p := &Chunk{}9 chunk2p := &chunk210- items1 := []*Item{&Item{}}11- items2 := []*Item{&Item{}, &Item{}}10+ items1 := []*Result{&Result{}}11+ items2 := []*Result{&Result{}, &Result{}}12 cache.Add(chunk1p, "foo", items1)13 cache.Add(chunk2p, "foo", items1)14 cache.Add(chunk2p, "bar", items2)15 25 unmodified linesmodified:src/cache.go+3 added-3 removed
1 unmodified line2 3 import "sync"4 5 // queryCache associates strings to lists of items6-type queryCache map[string][]*Item6+type queryCache map[string][]*Result7 8 // ChunkCache associates Chunk and query string to lists of items9 type ChunkCache struct {10 mutex sync.Mutex5 unmodified lines16 return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}17 }18 19 // Add adds the list to the cache20-func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {20+func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Result) {21 if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {22 return23 }24 8 unmodified lines33 (*qc)[key] = list34 }35 36 // Find is called to lookup ChunkCache37-func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Item, bool) {37+func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Result, bool) {38 if len(key) == 0 || !chunk.IsFull() {39 return nil, false40 }41 12 unmodified linesmodified:src/chunklist_test.go+3 added-6 removed
10 unmodified lines11 // FIXME global12 sortCriteria = []criterion{byMatchLen, byLength}13 14 cl := NewChunkList(func(s []byte, i int) *Item {15- return &Item{text: util.ToChars(s), rank: buildEmptyRank(int32(i * 2))}15+ return &Item{text: util.ToChars(s), index: int32(i * 2)}16 })17 18 // Snapshot19 snapshot, count := cl.Snapshot()20 unmodified lines40 chunk1 := snapshot[0]41 if len(*chunk1) != 2 {42 t.Error("Snapshot should contain only two items")43 }44- last := func(arr [5]int32) int32 {45- return arr[len(arr)-1]46- }47- if (*chunk1)[0].text.ToString() != "hello" || last((*chunk1)[0].rank) != 0 ||48- (*chunk1)[1].text.ToString() != "world" || last((*chunk1)[1].rank) != 2 {44+ if (*chunk1)[0].text.ToString() != "hello" || (*chunk1)[0].index != 0 ||45+ (*chunk1)[1].text.ToString() != "world" || (*chunk1)[1].index != 2 {46 t.Error("Invalid data")47 }48 if chunk1.IsFull() {49 t.Error("Chunk should not have been marked full yet")30 unmodified linesmodified:src/core.go+13 added-15 removed
54 unmodified lines55 // Event channel56 eventBox := util.NewEventBox()57 58 // ANSI code processor59- ansiProcessor := func(data []byte) (util.Chars, []ansiOffset) {59+ ansiProcessor := func(data []byte) (util.Chars, *[]ansiOffset) {60 return util.ToChars(data), nil61 }62- ansiProcessorRunes := func(data []rune) (util.Chars, []ansiOffset) {62+ ansiProcessorRunes := func(data []rune) (util.Chars, *[]ansiOffset) {63 return util.RunesToChars(data), nil64 }65 if opts.Ansi {66 if opts.Theme != nil {67 var state *ansiState68- ansiProcessor = func(data []byte) (util.Chars, []ansiOffset) {68+ ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {69 trimmed, offsets, newState := extractColor(string(data), state, nil)70 state = newState71 return util.RunesToChars([]rune(trimmed)), offsets72 }73 } else {74 // When color is disabled but ansi option is given,75 // we simply strip out ANSI codes from the input76- ansiProcessor = func(data []byte) (util.Chars, []ansiOffset) {76+ ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {77 trimmed, _, _ := extractColor(string(data), nil, nil)78 return util.RunesToChars([]rune(trimmed)), nil79 }80 }81- ansiProcessorRunes = func(data []rune) (util.Chars, []ansiOffset) {81+ ansiProcessorRunes = func(data []rune) (util.Chars, *[]ansiOffset) {82 return ansiProcessor([]byte(string(data)))83 }84 }85 8 unmodified lines94 return nil95 }96 chars, colors := ansiProcessor(data)97 return &Item{98+ index: int32(index),99 text: chars,99- colors: colors,100- rank: buildEmptyRank(int32(index))}100+ colors: colors}101 })102 } else {103 chunkList = NewChunkList(func(data []byte, index int) *Item {104- chars := util.ToChars(data)105- tokens := Tokenize(chars, opts.Delimiter)104+ tokens := Tokenize(util.ToChars(data), opts.Delimiter)105 trans := Transform(tokens, opts.WithNth)106 if len(header) < opts.HeaderLines {107 header = append(header, string(joinTokens(trans)))108 eventBox.Set(EvtHeader, header)109 return nil110 }111 textRunes := joinTokens(trans)112 item := Item{114- text: util.RunesToChars(textRunes),113+ index: int32(index),114 origText: &data,116- colors: nil,117- rank: buildEmptyRank(int32(index))}115+ colors: nil}116 117 trimmed, colors := ansiProcessorRunes(textRunes)118 item.text = trimmed119 item.colors = colors40 unmodified lines160 if streamingFilter {161 reader := Reader{162 func(runes []byte) bool {163 item := chunkList.trans(runes, 0)166- if item != nil && pattern.MatchItem(item) {164+ if item != nil && pattern.MatchItem(item) != nil {165 fmt.Println(item.text.ToString())166 found = true167 }168 return false7 unmodified lines176 merger, _ := matcher.scan(MatchRequest{177 chunks: snapshot,178 pattern: pattern})179 for i := 0; i < merger.Length(); i++ {182- fmt.Println(merger.Get(i).AsString(opts.Ansi))180+ fmt.Println(merger.Get(i).item.AsString(opts.Ansi))181 found = true182 }183 }184 if found {71 unmodified lines256 if len(opts.Expect) > 0 {257 fmt.Println()258 }259 for i := 0; i < count; i++ {262- fmt.Println(val.Get(i).AsString(opts.Ansi))260+ fmt.Println(val.Get(i).item.AsString(opts.Ansi))261 }262 if count > 0 {263 os.Exit(exitOk)264 }19 unmodified linesmodified:src/item_test.go+11 added-97 removed
1 package fzf2 3 import (4- "math"5- "sort"4 "testing"5 8- "github.com/junegunn/fzf/src/curses"6 "github.com/junegunn/fzf/src/util"7 )8 12-func TestOffsetSort(t *testing.T) {13- offsets := []Offset{14- Offset{3, 5}, Offset{2, 7},15- Offset{1, 3}, Offset{2, 9}}16- sort.Sort(ByOrder(offsets))17-18- if offsets[0][0] != 1 || offsets[0][1] != 3 ||19- offsets[1][0] != 2 || offsets[1][1] != 7 ||20- offsets[2][0] != 2 || offsets[2][1] != 9 ||21- offsets[3][0] != 3 || offsets[3][1] != 5 {22- t.Error("Invalid order:", offsets)9+func TestStringPtr(t *testing.T) {10+ orig := []byte("\x1b[34mfoo")11+ text := []byte("\x1b[34mbar")12+ item := Item{origText: &orig, text: util.ToChars(text)}13+ if item.AsString(true) != "foo" || item.AsString(false) != string(orig) {14+ t.Fail()15 }24-}25-26-func TestRankComparison(t *testing.T) {27- if compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{2, 0, 0, 0, 7}, false) ||28- !compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{3, 0, 0, 0, 6}, false) ||29- !compareRanks([5]int32{1, 2, 0, 0, 3}, [5]int32{1, 3, 0, 0, 2}, false) ||30- !compareRanks([5]int32{0, 0, 0, 0, 0}, [5]int32{0, 0, 0, 0, 0}, false) {31- t.Error("Invalid order")16+ if item.AsString(true) != "foo" {17+ t.Fail()18 }33-34- if compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{2, 0, 0, 0, 7}, true) ||35- !compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{3, 0, 0, 0, 6}, false) ||36- !compareRanks([5]int32{1, 2, 0, 0, 3}, [5]int32{1, 3, 0, 0, 2}, true) ||37- !compareRanks([5]int32{0, 0, 0, 0, 0}, [5]int32{0, 0, 0, 0, 0}, false) {38- t.Error("Invalid order (tac)")19+ item.origText = nil20+ if item.AsString(true) != string(text) || item.AsString(false) != string(text) {21+ t.Fail()22 }23 }41-42-// Match length, string length, index43-func TestItemRank(t *testing.T) {44- // FIXME global45- sortCriteria = []criterion{byMatchLen, byLength}46-47- strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}48- item1 := Item{text: util.RunesToChars(strs[0]), offsets: []Offset{}, rank: [5]int32{0, 0, 0, 0, 1}}49- rank1 := item1.Rank(true)50- if rank1[0] != math.MaxInt32 || rank1[1] != 3 || rank1[4] != 1 {51- t.Error(item1.Rank(true))52- }53- // Only differ in index54- item2 := Item{text: util.RunesToChars(strs[0]), offsets: []Offset{}}55-56- items := []*Item{&item1, &item2}57- sort.Sort(ByRelevance(items))58- if items[0] != &item2 || items[1] != &item1 {59- t.Error(items)60- }61-62- items = []*Item{&item2, &item1, &item1, &item2}63- sort.Sort(ByRelevance(items))64- if items[0] != &item2 || items[1] != &item2 ||65- items[2] != &item1 || items[3] != &item1 {66- t.Error(items)67- }68-69- // Sort by relevance70- item3 := Item{text: util.RunesToChars(strs[1]), rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}71- item4 := Item{text: util.RunesToChars(strs[1]), rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}72- item5 := Item{text: util.RunesToChars(strs[2]), rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}73- item6 := Item{text: util.RunesToChars(strs[2]), rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}74- items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}75- sort.Sort(ByRelevance(items))76- if items[0] != &item6 || items[1] != &item4 ||77- items[2] != &item5 || items[3] != &item3 ||78- items[4] != &item2 || items[5] != &item1 {79- t.Error(items)80- }81-}82-83-func TestColorOffset(t *testing.T) {84- // ------------ 20 ---- -- ----85- // ++++++++ ++++++++++86- // --++++++++-- --++++++++++---87- item := Item{88- offsets: []Offset{Offset{5, 15}, Offset{25, 35}},89- colors: []ansiOffset{90- ansiOffset{[2]int32{0, 20}, ansiState{1, 5, false}},91- ansiOffset{[2]int32{22, 27}, ansiState{2, 6, true}},92- ansiOffset{[2]int32{30, 32}, ansiState{3, 7, false}},93- ansiOffset{[2]int32{33, 40}, ansiState{4, 8, true}}}}94- // [{[0 5] 9 false} {[5 15] 99 false} {[15 20] 9 false} {[22 25] 10 true} {[25 35] 99 false} {[35 40] 11 true}]95-96- offsets := item.colorOffsets(99, false, true)97- assert := func(idx int, b int32, e int32, c int, bold bool) {98- o := offsets[idx]99- if o.offset[0] != b || o.offset[1] != e || o.color != c || o.bold != bold {100- t.Error(o)101- }102- }103- assert(0, 0, 5, curses.ColUser, false)104- assert(1, 5, 15, 99, false)105- assert(2, 15, 20, curses.ColUser, false)106- assert(3, 22, 25, curses.ColUser+1, true)107- assert(4, 25, 35, 99, false)108- assert(5, 35, 40, curses.ColUser+2, true)109-}modified:src/item.go+11 added-267 removed
1 package fzf2 3 import (4- "math"5-6- "github.com/junegunn/fzf/src/curses"4 "github.com/junegunn/fzf/src/util"5 )6 10-// Offset holds three 32-bit integers denoting the offsets of a matched substring11-type Offset [3]int3212-13-type colorOffset struct {14- offset [2]int3215- color int16- bold bool17-}18-7 // Item represents each input line8 type Item struct {9+ index int3210 text util.Chars11 origText *[]byte12+ colors *[]ansiOffset13 transformed []Token24- offsets []Offset25- colors []ansiOffset26- rank [5]int3227- bonus int3214 }15 30-// Sort criteria to use. Never changes once fzf is started.31-var sortCriteria []criterion32-33-func isRankValid(rank [5]int32) bool {34- // Exclude ordinal index35- for _, r := range rank[:4] {36- if r > 0 {37- return true38- }39- }40- return false41-}42-43-func buildEmptyRank(index int32) [5]int32 {44- return [5]int32{0, 0, 0, 0, index}45-}46-16 // Index returns ordinal index of the Item17 func (item *Item) Index() int32 {49- return item.rank[4]18+ return item.index19 }20 52-// Rank calculates rank of the Item53-func (item *Item) Rank(cache bool) [5]int32 {54- if cache && isRankValid(item.rank) {55- return item.rank21+// Colors returns ansiOffsets of the Item22+func (item *Item) Colors() []ansiOffset {23+ if item.colors == nil {24+ return []ansiOffset{}25 }57- matchlen := 058- prevEnd := 059- lenSum := 060- minBegin := math.MaxInt3261- for _, offset := range item.offsets {62- begin := int(offset[0])63- end := int(offset[1])64- trimLen := int(offset[2])65- lenSum += trimLen66- if prevEnd > begin {67- begin = prevEnd68- }69- if end > prevEnd {70- prevEnd = end71- }72- if end > begin {73- if begin < minBegin {74- minBegin = begin75- }76- matchlen += end - begin77- }78- }79- rank := buildEmptyRank(item.Index())80- for idx, criterion := range sortCriteria {81- var val int3282- switch criterion {83- case byMatchLen:84- if matchlen == 0 {85- val = math.MaxInt3286- } else {87- // It is extremely unlikely that bonus exceeds 12888- val = 128*int32(matchlen) - item.bonus89- }90- case byLength:91- // It is guaranteed that .transformed in not null in normal execution92- if item.transformed != nil {93- // If offsets is empty, lenSum will be 0, but we don't care94- val = int32(lenSum)95- } else {96- val = int32(item.text.Length())97- }98- case byBegin:99- // We can't just look at item.offsets[0][0] because it can be an inverse term100- whitePrefixLen := 0101- numChars := item.text.Length()102- for idx := 0; idx < numChars; idx++ {103- r := item.text.Get(idx)104- whitePrefixLen = idx105- if idx == minBegin || r != ' ' && r != '\t' {106- break107- }108- }109- val = int32(minBegin - whitePrefixLen)110- case byEnd:111- if prevEnd > 0 {112- val = int32(1 + item.text.Length() - prevEnd)113- } else {114- // Empty offsets due to inverse terms.115- val = 1116- }117- }118- rank[idx] = val119- }120- if cache {121- item.rank = rank122- }123- return rank26+ return *item.colors27 }28 29 // AsString returns the original string30 func (item *Item) AsString(stripAnsi bool) string {128- return *item.StringPtr(stripAnsi)129-}130-131-// StringPtr returns the pointer to the original string132-func (item *Item) StringPtr(stripAnsi bool) *string {31 if item.origText != nil {32 if stripAnsi {33 trimmed, _, _ := extractColor(string(*item.origText), nil, nil)136- return &trimmed34+ return trimmed35 }138- orig := string(*item.origText)139- return &orig36+ return string(*item.origText)37 }141- str := item.text.ToString()142- return &str38+ return item.text.ToString()39 }144-145-func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {146- if len(item.colors) == 0 {147- var offsets []colorOffset148- for _, off := range item.offsets {149-150- offsets = append(offsets, colorOffset{offset: [2]int32{off[0], off[1]}, color: color, bold: bold})151- }152- return offsets153- }154-155- // Find max column156- var maxCol int32157- for _, off := range item.offsets {158- if off[1] > maxCol {159- maxCol = off[1]160- }161- }162- for _, ansi := range item.colors {163- if ansi.offset[1] > maxCol {164- maxCol = ansi.offset[1]165- }166- }167- cols := make([]int, maxCol)168-169- for colorIndex, ansi := range item.colors {170- for i := ansi.offset[0]; i < ansi.offset[1]; i++ {171- cols[i] = colorIndex + 1 // XXX172- }173- }174-175- for _, off := range item.offsets {176- for i := off[0]; i < off[1]; i++ {177- cols[i] = -1178- }179- }180-181- // sort.Sort(ByOrder(offsets))182-183- // Merge offsets184- // ------------ ---- -- ----185- // ++++++++ ++++++++++186- // --++++++++-- --++++++++++---187- curr := 0188- start := 0189- var offsets []colorOffset190- add := func(idx int) {191- if curr != 0 && idx > start {192- if curr == -1 {193- offsets = append(offsets, colorOffset{194- offset: [2]int32{int32(start), int32(idx)}, color: color, bold: bold})195- } else {196- ansi := item.colors[curr-1]197- fg := ansi.color.fg198- if fg == -1 {199- if current {200- fg = curses.CurrentFG201- } else {202- fg = curses.FG203- }204- }205- bg := ansi.color.bg206- if bg == -1 {207- if current {208- bg = curses.DarkBG209- } else {210- bg = curses.BG211- }212- }213- offsets = append(offsets, colorOffset{214- offset: [2]int32{int32(start), int32(idx)},215- color: curses.PairFor(fg, bg),216- bold: ansi.color.bold || bold})217- }218- }219- }220- for idx, col := range cols {221- if col != curr {222- add(idx)223- start = idx224- curr = col225- }226- }227- add(int(maxCol))228- return offsets229-}230-231-// ByOrder is for sorting substring offsets232-type ByOrder []Offset233-234-func (a ByOrder) Len() int {235- return len(a)236-}237-238-func (a ByOrder) Swap(i, j int) {239- a[i], a[j] = a[j], a[i]240-}241-242-func (a ByOrder) Less(i, j int) bool {243- ioff := a[i]244- joff := a[j]245- return (ioff[0] < joff[0]) || (ioff[0] == joff[0]) && (ioff[1] <= joff[1])246-}247-248-// ByRelevance is for sorting Items249-type ByRelevance []*Item250-251-func (a ByRelevance) Len() int {252- return len(a)253-}254-255-func (a ByRelevance) Swap(i, j int) {256- a[i], a[j] = a[j], a[i]257-}258-259-func (a ByRelevance) Less(i, j int) bool {260- irank := a[i].Rank(true)261- jrank := a[j].Rank(true)262-263- return compareRanks(irank, jrank, false)264-}265-266-// ByRelevanceTac is for sorting Items267-type ByRelevanceTac []*Item268-269-func (a ByRelevanceTac) Len() int {270- return len(a)271-}272-273-func (a ByRelevanceTac) Swap(i, j int) {274- a[i], a[j] = a[j], a[i]275-}276-277-func (a ByRelevanceTac) Less(i, j int) bool {278- irank := a[i].Rank(true)279- jrank := a[j].Rank(true)280-281- return compareRanks(irank, jrank, true)282-}283-284-func compareRanks(irank [5]int32, jrank [5]int32, tac bool) bool {285- for idx := 0; idx < 4; idx++ {286- left := irank[idx]287- right := jrank[idx]288- if left < right {289- return true290- } else if left > right {291- return false292- }293- }294- return (irank[4] <= jrank[4]) != tac295-}modified:src/matcher.go+11 added-5 removed
126 unmodified lines127 }128 129 type partialResult struct {130 index int131- matches []*Item131+ matches []*Result132 }133 134 func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {135 startedAt := time.Now()18 unmodified lines154 for idx, chunks := range slices {155 waitGroup.Add(1)156 go func(idx int, chunks []*Chunk) {157 defer func() { waitGroup.Done() }()158- sliceMatches := []*Item{}159- for _, chunk := range chunks {158+ count := 0159+ allMatches := make([][]*Result, len(chunks))160+ for idx, chunk := range chunks {161 matches := request.pattern.Match(chunk)161- sliceMatches = append(sliceMatches, matches...)162+ allMatches[idx] = matches163+ count += len(matches)164 if cancelled.Get() {165 return166 }167 countChan <- len(matches)168 }169+ sliceMatches := make([]*Result, 0, count)170+ for _, matches := range allMatches {171+ sliceMatches = append(sliceMatches, matches...)172+ }173 if m.sort {174 if m.tac {175 sort.Sort(ByRelevanceTac(sliceMatches))176 } else {28 unmodified lines205 m.eventBox.Set(EvtSearchProgress, float32(count)/float32(numChunks))206 }207 }208 203- partialResults := make([][]*Item, numSlices)209+ partialResults := make([][]*Result, numSlices)210 for _ = range slices {211 partialResult := <-resultChan212 partialResults[partialResult.index] = partialResult.matches213 }15 unmodified linesmodified:src/merger_test.go+13 added-13 removed
13 unmodified lines14 t.Error(msg)15 }16 }17 18-func randItem() *Item {18+func randResult() *Result {19 str := fmt.Sprintf("%d", rand.Uint32())20 offsets := make([]Offset, rand.Int()%3)21 for idx := range offsets {22 sidx := int32(rand.Uint32() % 20)23 eidx := sidx + int32(rand.Uint32()%20)24 offsets[idx] = Offset{sidx, eidx}25 }26- return &Item{27- text: util.RunesToChars([]rune(str)),28- rank: buildEmptyRank(rand.Int31()),29- offsets: offsets}26+ return &Result{27+ item: &Item{text: util.RunesToChars([]rune(str))},28+ offsets: offsets,29+ rank: rank{index: rand.Int31()}}30 }31 32 func TestEmptyMerger(t *testing.T) {33 assert(t, EmptyMerger.Length() == 0, "Not empty")1 unmodified line35 assert(t, len(EmptyMerger.lists) == 0, "Invalid lists")36 assert(t, len(EmptyMerger.merged) == 0, "Invalid merged list")37 }38 39-func buildLists(partiallySorted bool) ([][]*Item, []*Item) {39+func buildLists(partiallySorted bool) ([][]*Result, []*Result) {40 numLists := 441- lists := make([][]*Item, numLists)41+ lists := make([][]*Result, numLists)42 cnt := 043 for i := 0; i < numLists; i++ {44- numItems := rand.Int() % 2045- cnt += numItems46- lists[i] = make([]*Item, numItems)47- for j := 0; j < numItems; j++ {48- item := randItem()44+ numResults := rand.Int() % 2045+ cnt += numResults46+ lists[i] = make([]*Result, numResults)47+ for j := 0; j < numResults; j++ {48+ item := randResult()49 lists[i][j] = item50 }51 if partiallySorted {52 sort.Sort(ByRelevance(lists[i]))53 }54 }55- items := []*Item{}55+ items := []*Result{}56 for _, list := range lists {57 items = append(items, list...)58 }59 return lists, items36 unmodified linesmodified:src/merger.go+11 added-11 removed
1 unmodified line2 3 import "fmt"4 5 // EmptyMerger is a Merger with no data6-var EmptyMerger = NewMerger([][]*Item{}, false, false)6+var EmptyMerger = NewMerger([][]*Result{}, false, false)7 8 // Merger holds a set of locally sorted lists of items and provides the view of9 // a single, globally-sorted list10 type Merger struct {11- lists [][]*Item12- merged []*Item11+ lists [][]*Result12+ merged []*Result13 chunks *[]*Chunk14 cursors []int15 sorted bool16 tac bool15 unmodified lines32 return &mg33 }34 35 // NewMerger returns a new Merger36-func NewMerger(lists [][]*Item, sorted bool, tac bool) *Merger {36+func NewMerger(lists [][]*Result, sorted bool, tac bool) *Merger {37 mg := Merger{38 lists: lists,39- merged: []*Item{},39+ merged: []*Result{},40 chunks: nil,41 cursors: make([]int, len(lists)),42 sorted: sorted,43 tac: tac,10 unmodified lines54 func (mg *Merger) Length() int {55 return mg.count56 }57 58-// Get returns the pointer to the Item object indexed by the given integer59-func (mg *Merger) Get(idx int) *Item {58+// Get returns the pointer to the Result object indexed by the given integer59+func (mg *Merger) Get(idx int) *Result {60 if mg.chunks != nil {61 if mg.tac {62 idx = mg.count - idx - 163 }64 chunk := (*mg.chunks)[idx/chunkSize]65- return (*chunk)[idx%chunkSize]65+ return &Result{item: (*chunk)[idx%chunkSize]}66 }67 68 if mg.sorted {69 return mg.mergedGet(idx)15 unmodified lines85 func (mg *Merger) cacheable() bool {86 return mg.count < mergerCacheMax87 }88 89-func (mg *Merger) mergedGet(idx int) *Item {89+func (mg *Merger) mergedGet(idx int) *Result {90 for i := len(mg.merged); i <= idx; i++ {91- minRank := buildEmptyRank(0)91+ minRank := minRank()92 minIdx := -193 for listIdx, list := range mg.lists {94 cursor := mg.cursors[listIdx]95 if cursor < 0 || cursor == len(list) {96 mg.cursors[listIdx] = -197 continue98 }99 if cursor >= 0 {100- rank := list[cursor].Rank(false)100+ rank := list[cursor].rank101 if minIdx < 0 || compareRanks(rank, minRank, mg.tac) {102 minRank = rank103 minIdx = listIdx104 }14 unmodified linesmodified:src/options.go+3 added-2 removed
93 unmodified lines94 type criterion int95 96 const (97 byMatchLen criterion = iota98+ byBonus99 byLength100 byBegin101 byEnd102 )75 unmodified lines178 WithNth: make([]Range, 0),179 Delimiter: Delimiter{},180 Sort: 1000,181 Tac: false,181- Criteria: []criterion{byMatchLen, byLength},182+ Criteria: []criterion{byMatchLen, byBonus, byLength},183 Multi: false,184 Ansi: false,185 Mouse: true,186 Theme: curses.EmptyTheme(),219 unmodified lines406 return chords407 }408 409 func parseTiebreak(str string) []criterion {409- criteria := []criterion{byMatchLen}410+ criteria := []criterion{byMatchLen, byBonus}411 hasIndex := false412 hasLength := false413 hasBegin := false414 hasEnd := false674 unmodified linesmodified:src/pattern_test.go+4 added-4 removed
81 unmodified lines82 defer clearPatternCache()83 clearPatternCache()84 pattern := BuildPattern(true, true, CaseSmart, true, []Range{}, Delimiter{}, []rune("^AbC$"))85 86- match := func(str string, sidxExpected int32, eidxExpected int32) {86+ match := func(str string, sidxExpected int, eidxExpected int) {87 res := algo.EqualMatch(88 pattern.caseSensitive, pattern.forward, util.RunesToChars([]rune(str)), pattern.termSets[0][0].text)89 if res.Start != sidxExpected || res.End != eidxExpected {90 t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)41 unmodified lines132 origText: &origBytes,133 transformed: trans},134 }135 pattern.extended = extended136- matches := pattern.matchChunk(&chunk)137- if matches[0].text.ToString() != "junegunn" || string(*matches[0].origText) != "junegunn.choi" ||136+ matches := pattern.matchChunk(&chunk, nil) // No cache137+ if matches[0].item.text.ToString() != "junegunn" || string(*matches[0].item.origText) != "junegunn.choi" ||138 matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||139- !reflect.DeepEqual(matches[0].transformed, trans) {139+ !reflect.DeepEqual(matches[0].item.transformed, trans) {140 t.Error("Invalid match result", matches)141 }142 }143 }22 unmodified linesmodified:src/pattern.go+51 added-59 removed
1 package fzf2 3 import (4 "regexp"5- "sort"5 "strings"6 7 "github.com/junegunn/fzf/src/algo"8 "github.com/junegunn/fzf/src/util"224 unmodified lines233 return strings.Join(cacheableTerms, " ")234 }235 236 // Match returns the list of matches Items in the given Chunk238-func (p *Pattern) Match(chunk *Chunk) []*Item {239- space := chunk240-237+func (p *Pattern) Match(chunk *Chunk) []*Result {238 // ChunkCache: Exact match239 cacheKey := p.CacheKey()240 if p.cacheable {241 if cached, found := _cache.Find(chunk, cacheKey); found {242 return cached243 }244 }245 249- // ChunkCache: Prefix/suffix match246+ // Prefix/suffix cache247+ var space []*Result248 Loop:249 for idx := 1; idx < len(cacheKey); idx++ {250 // [---------| ] | [ |---------]251 // [--------| ] | [ |--------]1 unmodified line253 prefix := cacheKey[:len(cacheKey)-idx]254 suffix := cacheKey[idx:]255 for _, substr := range [2]*string{&prefix, &suffix} {256 if cached, found := _cache.Find(chunk, *substr); found {259- cachedChunk := Chunk(cached)260- space = &cachedChunk257+ space = cached258 break Loop259 }260 }261 }262 266- matches := p.matchChunk(space)263+ matches := p.matchChunk(chunk, space)264 265 if p.cacheable {266 _cache.Add(chunk, cacheKey, matches)267 }268 return matches269 }270 274-func (p *Pattern) matchChunk(chunk *Chunk) []*Item {275- matches := []*Item{}276- if !p.extended {271+func (p *Pattern) matchChunk(chunk *Chunk, space []*Result) []*Result {272+ matches := []*Result{}273+274+ if space == nil {275 for _, item := range *chunk {278- offset, bonus := p.basicMatch(item)279- if sidx := offset[0]; sidx >= 0 {280- matches = append(matches,281- dupItem(item, []Offset{offset}, bonus))276+ if match := p.MatchItem(item); match != nil {277+ matches = append(matches, match)278 }279 }280 } else {285- for _, item := range *chunk {286- if offsets, bonus := p.extendedMatch(item); len(offsets) == len(p.termSets) {287- matches = append(matches, dupItem(item, offsets, bonus))281+ for _, result := range space {282+ if match := p.MatchItem(result.item); match != nil {283+ matches = append(matches, match)284 }285 }286 }287 return matches288 }289 290 // MatchItem returns true if the Item is a match295-func (p *Pattern) MatchItem(item *Item) bool {296- if !p.extended {297- offset, _ := p.basicMatch(item)298- sidx := offset[0]299- return sidx >= 0291+func (p *Pattern) MatchItem(item *Item) *Result {292+ if p.extended {293+ if offsets, bonus, trimLen := p.extendedMatch(item); len(offsets) == len(p.termSets) {294+ return buildResult(item, offsets, bonus, trimLen)295+ }296+ return nil297 }301- offsets, _ := p.extendedMatch(item)302- return len(offsets) == len(p.termSets)298+ offset, bonus, trimLen := p.basicMatch(item)299+ if sidx := offset[0]; sidx >= 0 {300+ return buildResult(item, []Offset{offset}, bonus, trimLen)301+ }302+ return nil303 }304 305-func dupItem(item *Item, offsets []Offset, bonus int32) *Item {306- sort.Sort(ByOrder(offsets))307- return &Item{308- text: item.text,309- origText: item.origText,310- transformed: item.transformed,311- offsets: offsets,312- bonus: bonus,313- colors: item.colors,314- rank: buildEmptyRank(item.Index())}315-}316-317-func (p *Pattern) basicMatch(item *Item) (Offset, int32) {305+func (p *Pattern) basicMatch(item *Item) (Offset, int, int) {306 input := p.prepareInput(item)307 if p.fuzzy {308 return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)309 }310 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)311 }312 325-func (p *Pattern) extendedMatch(item *Item) ([]Offset, int32) {313+func (p *Pattern) extendedMatch(item *Item) ([]Offset, int, int) {314 input := p.prepareInput(item)315 offsets := []Offset{}328- var totalBonus int32316+ var totalBonus int317+ var totalTrimLen int318 for _, termSet := range p.termSets {330- var offset *Offset331- var bonus int32319+ var offset Offset320+ var bonus int321+ var trimLen int322+ matched := false323 for _, term := range termSet {324 pfun := p.procFun[term.typ]334- off, pen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text)325+ off, pen, tLen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text)326 if sidx := off[0]; sidx >= 0 {327 if term.inv {328 continue329 }339- offset, bonus = &off, pen330+ offset, bonus, trimLen = off, pen, tLen331+ matched = true332 break333 } else if term.inv {342- offset, bonus = &Offset{0, 0, 0}, 0334+ offset, bonus, trimLen = Offset{0, 0}, 0, 0335+ matched = true336 continue337 }338 }346- if offset != nil {347- offsets = append(offsets, *offset)339+ if matched {340+ offsets = append(offsets, offset)341 totalBonus += bonus342+ totalTrimLen += trimLen343 }344 }351- return offsets, totalBonus345+ return offsets, totalBonus, totalTrimLen346 }347 348 func (p *Pattern) prepareInput(item *Item) []Token {349 if item.transformed != nil {350 return item.transformed351 }352 353 var ret []Token360- if len(p.nth) > 0 {354+ if len(p.nth) == 0 {355+ ret = []Token{Token{text: &item.text, prefixLength: 0, trimLength: int32(item.text.TrimLength())}}356+ } else {357 tokens := Tokenize(item.text, p.delimiter)358 ret = Transform(tokens, p.nth)363- } else {364- ret = []Token{Token{text: item.text, prefixLength: 0, trimLength: item.text.TrimLength()}}359 }360 item.transformed = ret361 return ret362 }363 364 func (p *Pattern) iter(pfun func(bool, bool, util.Chars, []rune) algo.Result,371- tokens []Token, caseSensitive bool, forward bool, pattern []rune) (Offset, int32) {365+ tokens []Token, caseSensitive bool, forward bool, pattern []rune) (Offset, int, int) {366 for _, part := range tokens {373- prefixLength := int32(part.prefixLength)374- if res := pfun(caseSensitive, forward, part.text, pattern); res.Start >= 0 {375- sidx := res.Start + prefixLength376- eidx := res.End + prefixLength377- return Offset{sidx, eidx, int32(part.trimLength)}, res.Bonus367+ if res := pfun(caseSensitive, forward, *part.text, pattern); res.Start >= 0 {368+ sidx := int32(res.Start) + part.prefixLength369+ eidx := int32(res.End) + part.prefixLength370+ return Offset{sidx, eidx}, res.Bonus, int(part.trimLength)371 }372 }380- // TODO: math.MaxUint16381- return Offset{-1, -1, -1}, 0.0373+ return Offset{-1, -1}, 0, -1374 }modified:src/terminal.go+18 added-17 removed
75 unmodified lines76 }77 78 type selectedItem struct {79 at time.Time80- text *string80+ text string81 }82 83 type byTimeOrder []selectedItem84 271 unmodified lines356 found = true357 }358 } else {359 for _, sel := range t.sortSelected() {360- fmt.Println(*sel.text)360+ fmt.Println(sel.text)361 }362 }363 return found364 }199 unmodified lines564 trimmed, colors, newState := extractColor(lineStr, state, nil)565 state = newState566 item := &Item{567 text: util.RunesToChars([]rune(trimmed)),568- colors: colors,569- rank: buildEmptyRank(0)}568+ colors: colors}569 570 t.move(line, 2, true)572- t.printHighlighted(item, false, C.ColHeader, 0, false)571+ t.printHighlighted(&Result{item: item}, false, C.ColHeader, 0, false)572 }573 }574 575 func (t *Terminal) printList() {12 unmodified lines588 }589 }590 }591 593-func (t *Terminal) printItem(item *Item, i int, current bool) {592+func (t *Terminal) printItem(result *Result, i int, current bool) {593+ item := result.item594 _, selected := t.selected[item.Index()]595 label := " "596 if t.jumping != jumpDisabled {597 if i < len(t.jumpLabels) {10 unmodified lines608 t.window.CPrint(C.ColSelected, true, ">")609 } else {610 t.window.CPrint(C.ColCurrent, true, " ")611 }612- t.printHighlighted(item, true, C.ColCurrent, C.ColCurrentMatch, true)612+ t.printHighlighted(result, true, C.ColCurrent, C.ColCurrentMatch, true)613 } else {614 if selected {615 t.window.CPrint(C.ColSelected, true, ">")616 } else {617 t.window.Print(" ")618 }619- t.printHighlighted(item, false, 0, C.ColMatch, false)619+ t.printHighlighted(result, false, 0, C.ColMatch, false)620 }621 }622 623 func trimRight(runes []rune, width int) ([]rune, int) {42 unmodified lines666 }667 return false668 }669 670-func (t *Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, current bool) {670+func (t *Terminal) printHighlighted(result *Result, bold bool, col1 int, col2 int, current bool) {671+ item := result.item672 var maxe int672- for _, offset := range item.offsets {673+ for _, offset := range result.offsets {674 maxe = util.Max(maxe, int(offset[1]))675 }676 677 // Overflow678 text := make([]rune, item.text.Length())679 copy(text, item.text.ToRunes())679- offsets := item.colorOffsets(col2, bold, current)680+ offsets := result.colorOffsets(col2, bold, current)681 maxWidth := t.window.Width - 3682 maxe = util.Constrain(maxe+util.Min(maxWidth/2-2, t.hscrollOff), 0, len(text))683 if overflow(text, maxWidth) {684 if t.hscroll {181 unmodified lines866 return t.previewBox != nil && t.previewing867 }868 869 func (t *Terminal) current() string {869- return t.merger.Get(t.cy).AsString(t.ansi)870+ return t.merger.Get(t.cy).item.AsString(t.ansi)871 }872 873 // Loop is called to start Terminal I/O874 func (t *Terminal) Loop() {162 unmodified lines1037 }1038 }1039 selectItem := func(item *Item) bool {1040 if _, found := t.selected[item.Index()]; !found {1040- t.selected[item.Index()] = selectedItem{time.Now(), item.StringPtr(t.ansi)}1041+ t.selected[item.Index()] = selectedItem{time.Now(), item.AsString(t.ansi)}1042 return true1043 }1044 return false1045 }1046 toggleY := func(y int) {1046- item := t.merger.Get(y)1047+ item := t.merger.Get(y).item1048 if !selectItem(item) {1049 delete(t.selected, item.Index())1050 }1051 }16 unmodified lines1068 switch action {1069 case actIgnore:1070 case actExecute:1071 if t.cy >= 0 && t.cy < t.merger.Length() {1071- item := t.merger.Get(t.cy)1072+ item := t.merger.Get(t.cy).item1073 t.executeCommand(t.execmap[mapkey], quoteEntry(item.AsString(t.ansi)))1074 }1075 case actExecuteMulti:1076 if len(t.selected) > 0 {1077 sels := make([]string, len(t.selected))1078 for i, sel := range t.sortSelected() {1078- sels[i] = quoteEntry(*sel.text)1079+ sels[i] = quoteEntry(sel.text)1080 }1081 t.executeCommand(t.execmap[mapkey], strings.Join(sels, " "))1082 } else {1083 return doAction(actExecute, mapkey)53 unmodified lines1137 }1138 case actSelectAll:1139 if t.multi {1140 for i := 0; i < t.merger.Length(); i++ {1140- item := t.merger.Get(i)1141+ item := t.merger.Get(i).item1142 selectItem(item)1143 }1144 req(reqList, reqInfo)1145 }244 unmodified linesmodified:src/tokenizer.go+11 added-11 removed
16 unmodified lines17 }18 19 // Token contains the tokenized part of the strings and its prefix length20 type Token struct {21- text util.Chars22- prefixLength int23- trimLength int21+ text *util.Chars22+ prefixLength int3223+ trimLength int3224 }25 26 // Delimiter for tokenizing the input27 type Delimiter struct {51 unmodified lines79 ret := make([]Token, len(tokens))80 81 prefixLength := begin82 for idx, token := range tokens {83- // Need to define a new local variable instead of the reused token to take84- // the pointer to it85- ret[idx] = Token{token, prefixLength, token.TrimLength()}83+ // NOTE: &tokens[idx] instead of &tokens84+ ret[idx] = Token{&tokens[idx], int32(prefixLength), int32(token.TrimLength())}85 prefixLength += token.Length()86 }87 return ret88 }87 unmodified lines176 func Transform(tokens []Token, withNth []Range) []Token {177 transTokens := make([]Token, len(withNth))178 numTokens := len(tokens)179 for idx, r := range withNth {181- parts := []util.Chars{}180+ parts := []*util.Chars{}181 minIdx := 0182 if r.begin == r.end {183 idx := r.begin184 if idx == rangeEllipsis {186- parts = append(parts, util.RunesToChars(joinTokens(tokens)))185+ chars := util.RunesToChars(joinTokens(tokens))186+ parts = append(parts, &chars)187 } else {188 if idx < 0 {189 idx += numTokens + 1190 }35 unmodified lines226 switch len(parts) {227 case 0:228 merged = util.RunesToChars([]rune{})229 case 1:230- merged = parts[0]230+ merged = *parts[0]231 default:232 runes := []rune{}233 for _, part := range parts {234 runes = append(runes, part.ToRunes()...)235 }236 merged = util.RunesToChars(runes)237 }238 239- var prefixLength int239+ var prefixLength int32240 if minIdx < numTokens {241 prefixLength = tokens[minIdx].prefixLength242 } else {243 prefixLength = 0244 }245- transTokens[idx] = Token{merged, prefixLength, merged.TrimLength()}245+ transTokens[idx] = Token{&merged, prefixLength, int32(merged.TrimLength())}246 }247 return transTokens248 }