Skip to content
Myr

Support field index expressions in preview and execute action

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Also close #679. The placeholder for the current query is {q}.

authored by Junegunn Choi · committed by Junegunn Choi · parent 04492ba · Browse files · 2 files+157 added−25 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+157 added−25 removed

  • other:+157 added−25 removed

2 files+157 added−25 removed

added:src/terminal_test.go+73 added
1package fzf23import (4 "regexp"5 "testing"67 "github.com/junegunn/fzf/src/util"8)910func newItem(str string) *Item {11 bytes := []byte(str)12 trimmed, _, _ := extractColor(str, nil, nil)13 return &Item{origText: &bytes, text: util.RunesToChars([]rune(trimmed))}14}1516func TestReplacePlaceholder(t *testing.T) {17 items1 := []*Item{newItem(" foo'bar \x1b[31mbaz\x1b[m")}18 items2 := []*Item{19 newItem("foo'bar \x1b[31mbaz\x1b[m"),20 newItem("FOO'BAR \x1b[31mBAZ\x1b[m")}2122 var result string23 check := func(expected string) {24 if result != expected {25 t.Errorf("expected: %s, actual: %s", expected, result)26 }27 }2829 // {}, preserve ansi30 result = replacePlaceholder("echo {}", false, Delimiter{}, "query", items1)31 check("echo ' foo'\\''bar \x1b[31mbaz\x1b[m'")3233 // {}, strip ansi34 result = replacePlaceholder("echo {}", true, Delimiter{}, "query", items1)35 check("echo ' foo'\\''bar baz'")3637 // {}, with multiple items38 result = replacePlaceholder("echo {}", true, Delimiter{}, "query", items2)39 check("echo 'foo'\\''bar baz' 'FOO'\\''BAR BAZ'")4041 // {..}, strip leading whitespaces, preserve ansi42 result = replacePlaceholder("echo {..}", false, Delimiter{}, "query", items1)43 check("echo 'foo'\\''bar \x1b[31mbaz\x1b[m'")4445 // {..}, strip leading whitespaces, strip ansi46 result = replacePlaceholder("echo {..}", true, Delimiter{}, "query", items1)47 check("echo 'foo'\\''bar baz'")4849 // {q}50 result = replacePlaceholder("echo {} {q}", true, Delimiter{}, "query", items1)51 check("echo ' foo'\\''bar baz' 'query'")5253 // {q}, multiple items54 result = replacePlaceholder("echo {}{q}{}", true, Delimiter{}, "query 'string'", items2)55 check("echo 'foo'\\''bar baz' 'FOO'\\''BAR BAZ''query '\\''string'\\''''foo'\\''bar baz' 'FOO'\\''BAR BAZ'")5657 result = replacePlaceholder("echo {1}/{2}/{2,1}/{-1}/{-2}/{}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, "query", items1)58 check("echo 'foo'\\''bar'/'baz'/'bazfoo'\\''bar'/'baz'/'foo'\\''bar'/' foo'\\''bar baz'/'foo'\\''bar baz'/{n.t}/{}/{1}/{q}/''")5960 result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, "query", items2)61 check("echo 'foo'\\''bar' 'FOO'\\''BAR'/'baz' 'BAZ'/'baz' 'BAZ'/'foo'\\''bar' 'FOO'\\''BAR'/'foo'\\''bar baz' 'FOO'\\''BAR BAZ'/{n.t}/{}/{1}/{q}/'' ''")6263 // String delimiter64 delim := "'"65 result = replacePlaceholder("echo {}/{1}/{2}", true, Delimiter{str: &delim}, "query", items1)66 check("echo ' foo'\\''bar baz'/'foo'/'bar baz'")6768 // Regex delimiter69 regex := regexp.MustCompile("[oa]+")70 // foo'bar baz71 result = replacePlaceholder("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, "query", items1)72 check("echo ' foo'\\''bar baz'/'f'/'r b'/''\\''bar b'")73}
modified:src/terminal.go+84 added-25 removed
18 unmodified lines
19)2021// import "github.com/pkg/profile"2223var placeholder *regexp.Regexp2425func init() {26 placeholder = regexp.MustCompile("\\\\?(?:{[0-9,-.]*}|{q})")27}2829type jumpMode int3031const (32 jumpDisabled jumpMode = iota
23 unmodified lines
56 input []rune57 multi bool58 sort bool59 toggleSort bool60 delimiter Delimiter61 expect map[int]string62 keymap map[int]actionType63 execmap map[int]string64 pressed string
28 unmodified lines
93}9495type selectedItem struct {96 at time.Time90 text string97 item *Item98}99100type byTimeOrder []selectedItem10195type previewRequest struct {96 ok bool97 str string98}99102func (a byTimeOrder) Len() int {103 return len(a)104}105
162 unmodified lines
268 input: input,269 multi: opts.Multi,270 sort: opts.Sort > 0,271 toggleSort: opts.ToggleSort,272 delimiter: opts.Delimiter,273 expect: opts.Expect,274 keymap: opts.Keymap,275 execmap: opts.Execmap,276 pressed: "",
98 unmodified lines
375 found = true376 }377 } else {378 for _, sel := range t.sortSelected() {376 t.printer(sel.text)379 t.printer(sel.item.AsString(t.ansi))380 }381 }382 return found383}
530 unmodified lines
914func quoteEntry(entry string) string {915 return "'" + strings.Replace(entry, "'", "'\\''", -1) + "'"916}917915func (t *Terminal) executeCommand(template string, replacement string) {916 command := strings.Replace(template, "{}", replacement, -1)918func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, query string, items []*Item) string {919 return placeholder.ReplaceAllStringFunc(template, func(match string) string {920 // Escaped pattern921 if match[0] == '\\' {922 return match[1:]923 }924925 // Current query926 if match == "{q}" {927 return quoteEntry(query)928 }929930 replacements := make([]string, len(items))931932 if match == "{}" {933 for idx, item := range items {934 replacements[idx] = quoteEntry(item.AsString(stripAnsi))935 }936 return strings.Join(replacements, " ")937 }938939 tokens := strings.Split(match[1:len(match)-1], ",")940 ranges := make([]Range, len(tokens))941 for idx, s := range tokens {942 r, ok := ParseRange(&s)943 if !ok {944 // Invalid expression, just return the original string in the template945 return match946 }947 ranges[idx] = r948 }949950 for idx, item := range items {951 chars := util.RunesToChars([]rune(item.AsString(stripAnsi)))952 tokens := Tokenize(chars, delimiter)953 trans := Transform(tokens, ranges)954 str := string(joinTokens(trans))955 if delimiter.str != nil {956 str = strings.TrimSuffix(str, *delimiter.str)957 } else if delimiter.regex != nil {958 delims := delimiter.regex.FindAllStringIndex(str, -1)959 if len(delims) > 0 && delims[len(delims)-1][1] == len(str) {960 str = str[:delims[len(delims)-1][0]]961 }962 }963 str = strings.TrimSpace(str)964 replacements[idx] = quoteEntry(str)965 }966 return strings.Join(replacements, " ")967 })968}969970func (t *Terminal) executeCommand(template string, items []*Item) {971 command := replacePlaceholder(template, t.ansi, t.delimiter, string(t.input), items)972 cmd := util.ExecCommand(command)973 cmd.Stdin = os.Stdin974 cmd.Stdout = os.Stdout975 cmd.Stderr = os.Stderr
9 unmodified lines
985func (t *Terminal) isPreviewEnabled() bool {986 return t.previewBox != nil && t.previewer.enabled987}988989func (t *Terminal) currentItem() *Item {990 return t.merger.Get(t.cy).item991}992993func (t *Terminal) current() string {935 return t.merger.Get(t.cy).item.AsString(t.ansi)994 return t.currentItem().AsString(t.ansi)995}996997// Loop is called to start Terminal I/O998func (t *Terminal) Loop() {
48 unmodified lines
10471048 if t.hasPreviewWindow() {1049 go func() {1050 for {992 request := previewRequest{false, ""}1051 var request *Item1052 t.previewBox.Wait(func(events *util.Events) {1053 for req, value := range *events {1054 switch req {1055 case reqPreviewEnqueue:997 request = value.(previewRequest)1056 request = value.(*Item)1057 }1058 }1059 events.Clear()1060 })1002 if request.ok {1003 command := strings.Replace(t.preview.command, "{}", quoteEntry(request.str), -1)1061 if request != nil {1062 command := replacePlaceholder(t.preview.command,1063 t.ansi, t.delimiter, string(t.input), []*Item{request})1064 cmd := util.ExecCommand(command)1065 out, _ := cmd.CombinedOutput()1066 t.reqBox.Set(reqPreviewDisplay, string(out))1067 } else {
11 unmodified lines
1079 os.Exit(code)1080 }10811082 go func() {1023 focused := previewRequest{false, ""}1083 var focused *Item1084 for {1085 t.reqBox.Wait(func(events *util.Events) {1086 defer events.Clear()1087 t.mutex.Lock()
8 unmodified lines
1096 t.printInfo()1097 case reqList:1098 t.printList()1099 cnt := t.merger.Length()1040 var currentFocus previewRequest1100 var currentFocus *Item1101 if cnt > 0 && cnt > t.cy {1042 currentFocus = previewRequest{true, t.current()}1102 currentFocus = t.currentItem()1103 } else {1044 currentFocus = previewRequest{false, ""}1104 currentFocus = nil1105 }1106 if currentFocus != focused {1107 focused = currentFocus1108 if t.isPreviewEnabled() {
59 unmodified lines
1168 }1169 }1170 selectItem := func(item *Item) bool {1171 if _, found := t.selected[item.Index()]; !found {1112 t.selected[item.Index()] = selectedItem{time.Now(), item.AsString(t.ansi)}1172 t.selected[item.Index()] = selectedItem{time.Now(), item}1173 return true1174 }1175 return false1176 }
28 unmodified lines
1205 switch action {1206 case actIgnore:1207 case actExecute:1208 if t.cy >= 0 && t.cy < t.merger.Length() {1149 item := t.merger.Get(t.cy).item1150 t.executeCommand(t.execmap[mapkey], quoteEntry(item.AsString(t.ansi)))1209 t.executeCommand(t.execmap[mapkey], []*Item{t.currentItem()})1210 }1211 case actExecuteMulti:1212 if len(t.selected) > 0 {1154 sels := make([]string, len(t.selected))1213 sels := make([]*Item, len(t.selected))1214 for i, sel := range t.sortSelected() {1156 sels[i] = quoteEntry(sel.text)1215 sels[i] = sel.item1216 }1158 t.executeCommand(t.execmap[mapkey], strings.Join(sels, " "))1217 t.executeCommand(t.execmap[mapkey], sels)1218 } else {1219 return doAction(actExecute, mapkey)1220 }1221 case actInvalid:
4 unmodified lines
1226 t.previewer.enabled = !t.previewer.enabled1227 t.resizeWindows()1228 cnt := t.merger.Length()1229 if t.previewer.enabled && cnt > 0 && cnt > t.cy {1171 t.previewBox.Set(reqPreviewEnqueue, previewRequest{true, t.current()})1230 t.previewBox.Set(reqPreviewEnqueue, t.currentItem())1231 }1232 req(reqList, reqInfo)1233 }1234 case actToggleSort:
314 unmodified lines