Skip to content
Myr

Add {fzf:prompt} placeholder expression

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

Close #3354

authored by Junegunn Choi · committed by Junegunn Choi · parent f0fbed6 · Browse files · 4 files+100 added−58 removed
This commit

State

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

Diff stats

4 files+100 added−58 removed

  • other:+100 added−58 removed

4 files+100 added−58 removed

modified:man/man1/fzf.1+1 added
591 unmodified lines
592* \fB{n}\fR is replaced to the zero-based ordinal index of the current item.593 Use \fB{+n}\fR if you want all index numbers when multiple lines are selected.594.br595* \fB{fzf:action}\fR is replaced to to the name of the last action performed596* \fB{fzf:prompt}\fR is replaced to to the prompt string597598Note that you can escape a placeholder pattern by prepending a backslash.599600Preview window will be updated even when there is no match for the current
810 unmodified lines
modified:src/terminal_test.go+42 added-29 removed
10 unmodified lines
1112 "github.com/junegunn/fzf/src/util"13)1415func replacePlaceholderTest(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems []*Item) string {16 return replacePlaceholder(replacePlaceholderParams{17 template: template,18 stripAnsi: stripAnsi,19 delimiter: delimiter,20 printsep: printsep,21 forcePlus: forcePlus,22 query: query,23 allItems: allItems,24 lastAction: actBackwardDeleteCharEof,25 prompt: "prompt",26 })27}2829func TestReplacePlaceholder(t *testing.T) {30 item1 := newItem(" foo'bar \x1b[31mbaz\x1b[m")31 items1 := []*Item{item1, item1}32 items2 := []*Item{
32 unmodified lines
65 Test multiple placeholders and the function parameters.66 */6768 // {}, preserve ansi55 result = replacePlaceholder("echo {}", false, Delimiter{}, printsep, false, "query", items1, actIgnore)69 result = replacePlaceholderTest("echo {}", false, Delimiter{}, printsep, false, "query", items1)70 checkFormat("echo {{.O}} foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}")7172 // {}, strip ansi59 result = replacePlaceholder("echo {}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)73 result = replacePlaceholderTest("echo {}", true, Delimiter{}, printsep, false, "query", items1)74 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}")7576 // {}, with multiple items63 result = replacePlaceholder("echo {}", true, Delimiter{}, printsep, false, "query", items2, actIgnore)77 result = replacePlaceholderTest("echo {}", true, Delimiter{}, printsep, false, "query", items2)78 checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}")7980 // {..}, strip leading whitespaces, preserve ansi67 result = replacePlaceholder("echo {..}", false, Delimiter{}, printsep, false, "query", items1, actIgnore)81 result = replacePlaceholderTest("echo {..}", false, Delimiter{}, printsep, false, "query", items1)82 checkFormat("echo {{.O}}foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}")8384 // {..}, strip leading whitespaces, strip ansi71 result = replacePlaceholder("echo {..}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)85 result = replacePlaceholderTest("echo {..}", true, Delimiter{}, printsep, false, "query", items1)86 checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}")8788 // {q}75 result = replacePlaceholder("echo {} {q}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)89 result = replacePlaceholderTest("echo {} {q}", true, Delimiter{}, printsep, false, "query", items1)90 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}} {{.O}}query{{.O}}")9192 // {q}, multiple items79 result = replacePlaceholder("echo {+}{q}{+}", true, Delimiter{}, printsep, false, "query 'string'", items2, actIgnore)93 result = replacePlaceholderTest("echo {+}{q}{+}", true, Delimiter{}, printsep, false, "query 'string'", items2)94 checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}{{.O}}query {{.I}}string{{.I}}{{.O}}{{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}")9582 result = replacePlaceholder("echo {}{q}{}", true, Delimiter{}, printsep, false, "query 'string'", items2, actIgnore)96 result = replacePlaceholderTest("echo {}{q}{}", true, Delimiter{}, printsep, false, "query 'string'", items2)97 checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}{{.O}}query {{.I}}string{{.I}}{{.O}}{{.O}}foo{{.I}}bar baz{{.O}}")9885 result = replacePlaceholder("echo {1}/{2}/{2,1}/{-1}/{-2}/{}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)99 result = replacePlaceholderTest("echo {1}/{2}/{2,1}/{-1}/{-2}/{}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items1)100 checkFormat("echo {{.O}}foo{{.I}}bar{{.O}}/{{.O}}baz{{.O}}/{{.O}}bazfoo{{.I}}bar{{.O}}/{{.O}}baz{{.O}}/{{.O}}foo{{.I}}bar{{.O}}/{{.O}} foo{{.I}}bar baz{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}}")10188 result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items2, actIgnore)102 result = replacePlaceholderTest("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items2)103 checkFormat("echo {{.O}}foo{{.I}}bar{{.O}}/{{.O}}baz{{.O}}/{{.O}}baz{{.O}}/{{.O}}foo{{.I}}bar{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}}")10491 result = replacePlaceholder("echo {+1}/{+2}/{+-1}/{+-2}/{+..}/{n.t}/\\{}/\\{1}/\\{q}/{+3}", true, Delimiter{}, printsep, false, "query", items2, actIgnore)105 result = replacePlaceholderTest("echo {+1}/{+2}/{+-1}/{+-2}/{+..}/{n.t}/\\{}/\\{1}/\\{q}/{+3}", true, Delimiter{}, printsep, false, "query", items2)106 checkFormat("echo {{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}} {{.O}}{{.O}}")107108 // forcePlus95 result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, true, "query", items2, actIgnore)109 result = replacePlaceholderTest("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, true, "query", items2)110 checkFormat("echo {{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}} {{.O}}{{.O}}")111112 // Whitespace preserving flag with "'" delimiter99 result = replacePlaceholder("echo {s1}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)113 result = replacePlaceholderTest("echo {s1}", true, Delimiter{str: &delim}, printsep, false, "query", items1)114 checkFormat("echo {{.O}} foo{{.O}}")115102 result = replacePlaceholder("echo {s2}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)116 result = replacePlaceholderTest("echo {s2}", true, Delimiter{str: &delim}, printsep, false, "query", items1)117 checkFormat("echo {{.O}}bar baz{{.O}}")118105 result = replacePlaceholder("echo {s}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)119 result = replacePlaceholderTest("echo {s}", true, Delimiter{str: &delim}, printsep, false, "query", items1)120 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}")121108 result = replacePlaceholder("echo {s..}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)122 result = replacePlaceholderTest("echo {s..}", true, Delimiter{str: &delim}, printsep, false, "query", items1)123 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}")124125 // Whitespace preserving flag with regex delimiter126 regex = regexp.MustCompile(`\w+`)127114 result = replacePlaceholder("echo {s1}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)128 result = replacePlaceholderTest("echo {s1}", true, Delimiter{regex: regex}, printsep, false, "query", items1)129 checkFormat("echo {{.O}} {{.O}}")130117 result = replacePlaceholder("echo {s2}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)131 result = replacePlaceholderTest("echo {s2}", true, Delimiter{regex: regex}, printsep, false, "query", items1)132 checkFormat("echo {{.O}}{{.I}}{{.O}}")133120 result = replacePlaceholder("echo {s3}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)134 result = replacePlaceholderTest("echo {s3}", true, Delimiter{regex: regex}, printsep, false, "query", items1)135 checkFormat("echo {{.O}} {{.O}}")136137 // No match124 result = replacePlaceholder("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, nil}, actIgnore)138 result = replacePlaceholderTest("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, nil})139 check("echo /")140141 // No match, but with selections128 result = replacePlaceholder("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, item1}, actIgnore)142 result = replacePlaceholderTest("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, item1})143 checkFormat("echo /{{.O}} foo{{.I}}bar baz{{.O}}")144145 // String delimiter132 result = replacePlaceholder("echo {}/{1}/{2}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)146 result = replacePlaceholderTest("echo {}/{1}/{2}", true, Delimiter{str: &delim}, printsep, false, "query", items1)147 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}/{{.O}}foo{{.O}}/{{.O}}bar baz{{.O}}")148149 // Regex delimiter150 regex = regexp.MustCompile("[oa]+")151 // foo'bar baz138 result = replacePlaceholder("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)152 result = replacePlaceholderTest("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, printsep, false, "query", items1)153 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}/{{.O}}f{{.O}}/{{.O}}r b{{.O}}/{{.O}}{{.I}}bar b{{.O}}")154155 /*156 Test single placeholders, but focus on the placeholders' parameters (e.g. flags).
11 unmodified lines
168 newItem("6a 6b 6c 6d 6e 6f"),169 newItem("7a 7b 7c 7d 7e 7f"),170 }171 stripAnsi := false158 printsep = "\n"172 forcePlus := false173 query := "sample query"174175 templateToOutput := make(map[string]string)
35 unmodified lines
211 // query flag is not removed after parsing, so it gets doubled212 // while the double q is invalid, it is useful here for testing purposes213 templateToOutput[`{q}`] = "{{.O}}" + query + "{{.O}}"214 templateToOutput[`{fzf:query}`] = "{{.O}}" + query + "{{.O}}"202 templateToOutput[`{fzf:action}`] = "backward-delete-char-eof"215 templateToOutput[`{fzf:action} {fzf:prompt}`] = "backward-delete-char-eof 'prompt'"216217 // IV. escaping placeholder218 templateToOutput[`\{}`] = `{}`219 templateToOutput[`\{q}`] = `{q}`
2 unmodified lines
222 templateToOutput[`\{++}`] = `{++}`223 templateToOutput[`{++}`] = templateToOutput[`{+}`]224225 for giveTemplate, wantOutput := range templateToOutput {213 result = replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3, actBackwardDeleteCharEof)226 result = replacePlaceholderTest(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)227 checkFormat(wantOutput)228 }229 for giveTemplate, wantOutput := range templateToFile {217 path := replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3, actIgnore)230 path := replacePlaceholderTest(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)231232 data, err := readFile(path)233 if err != nil {234 t.Errorf("Cannot read the content of the temp file %s.", path)
345 unmodified lines
580 forcePlus := false581582 // evaluate the test cases583 for idx, test := range tests {571 gotOutput := replacePlaceholder(584 gotOutput := replacePlaceholderTest(585 test.give.template, stripAnsi, delimiter, printsep, forcePlus,586 test.give.query,574 test.give.allItems, actIgnore)587 test.give.allItems)588 switch {589 case test.want.output != "":590 if gotOutput != test.want.output {591 t.Errorf("tests[%v]:\ngave{\n\ttemplate: '%s',\n\tquery: '%s',\n\tallItems: %s}\nand got '%s',\nbut want '%s'",
65 unmodified lines
modified:src/terminal.go+54 added-27 removed
55 unmodified lines
5657const clearCode string = "\x1b[2J"5859func init() {60 placeholder = regexp.MustCompile(`\\?(?:{[+sf]*[0-9,-.]*}|{q}|{fzf:(?:query|action)}|{\+?f?nf?})`)60 placeholder = regexp.MustCompile(`\\?(?:{[+sf]*[0-9,-.]*}|{q}|{fzf:(?:query|action|prompt)}|{\+?f?nf?})`)61 whiteSuffix = regexp.MustCompile(`\s*$`)62 offsetComponentRegex = regexp.MustCompile(`([+-][0-9]+)|(-?/[1-9][0-9]*)`)63 offsetTrimCharsRegex = regexp.MustCompile(`[^0-9/+-]`)64 activeTempFiles = []string{}
117 unmodified lines
182 infoSep string183 separator labelPrinter184 separatorLen int185 spinner []string186 promptString string187 prompt func()188 promptLen int189 borderLabel labelPrinter190 borderLabelLen int
479 unmodified lines
670 infoStyle: opts.InfoStyle,671 infoSep: opts.InfoSep,672 separator: nil,673 spinner: makeSpinner(opts.Unicode),674 promptString: opts.Prompt,675 queryLen: [2]int{0, 0},676 layout: opts.Layout,677 fullscreen: fullscreen,678 keepRight: opts.KeepRight,
1676 unmodified lines
2355 return true, match[1:], flags2356 }23572358 if strings.HasPrefix(match, "{fzf:") {2357 // Both {fzf:query} and {fzf:action} are not determined by the current item2359 // {fzf:*} are not determined by the current item2360 flags.forceUpdate = true2361 return false, match, flags2362 }2363
58 unmodified lines
2422 }2423 activeTempFiles = []string{}2424}24252426type replacePlaceholderParams struct {2427 template string2428 stripAnsi bool2429 delimiter Delimiter2430 printsep string2431 forcePlus bool2432 query string2433 allItems []*Item2434 lastAction actionType2435 prompt string2436}24372438func (t *Terminal) replacePlaceholder(template string, forcePlus bool, input string, list []*Item) string {2425 return replacePlaceholder(2426 template, t.ansi, t.delimiter, t.printsep, forcePlus, input, list, t.lastAction)2439 return replacePlaceholder(replacePlaceholderParams{2440 template: template,2441 stripAnsi: t.ansi,2442 delimiter: t.delimiter,2443 printsep: t.printsep,2444 forcePlus: forcePlus,2445 query: input,2446 allItems: list,2447 lastAction: t.lastAction,2448 prompt: t.promptString,2449 })2450}24512452func (t *Terminal) evaluateScrollOffset() int {2453 if t.pwindow == nil {
29 unmodified lines
2483 }2484 return util.Max(0, base)2485}24862464func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems []*Item, lastAction actionType) string {2465 current := allItems[:1]2466 selected := allItems[1:]2487func replacePlaceholder(params replacePlaceholderParams) string {2488 current := params.allItems[:1]2489 selected := params.allItems[1:]2490 if current[0] == nil {2491 current = []*Item{}2492 }2493 if selected[0] == nil {2494 selected = []*Item{}2495 }24962497 // replace placeholders one by one2475 return placeholder.ReplaceAllStringFunc(template, func(match string) string {2498 return placeholder.ReplaceAllStringFunc(params.template, func(match string) string {2499 escaped, match, flags := parsePlaceholder(match)25002501 // this function implements the effects a placeholder has on items2502 var replace func(*Item) string
1 unmodified line
2504 // placeholder types (escaped, query type, item type, token type)2505 switch {2506 case escaped:2507 return match2485 case match == "{fzf:action}":2486 name := ""2487 for i, r := range lastAction.String()[3:] {2488 if i > 0 && r >= 'A' && r <= 'Z' {2489 name += "-"2490 }2491 name += string(r)2492 }2493 return strings.ToLower(name)2508 case match == "{q}" || match == "{fzf:query}":2495 return quoteEntry(query)2509 return quoteEntry(params.query)2510 case match == "{}":2511 replace = func(item *Item) string {2512 switch {2513 case flags.number:
2 unmodified lines
2516 return ""2517 }2518 return strconv.Itoa(n)2519 case flags.file:2506 return item.AsString(stripAnsi)2520 return item.AsString(params.stripAnsi)2521 default:2508 return quoteEntry(item.AsString(stripAnsi))2522 return quoteEntry(item.AsString(params.stripAnsi))2523 }2524 }2525 case match == "{fzf:action}":2526 name := ""2527 for i, r := range params.lastAction.String()[3:] {2528 if i > 0 && r >= 'A' && r <= 'Z' {2529 name += "-"2530 }2531 name += string(r)2532 }2533 return strings.ToLower(name)2534 case match == "{fzf:prompt}":2535 return quoteEntry(params.prompt)2536 default:2537 // token type and also failover (below)2538 rangeExpressions := strings.Split(match[1:len(match)-1], ",")2539 ranges := make([]Range, len(rangeExpressions))
6 unmodified lines
2546 ranges[idx] = r2547 }25482549 replace = func(item *Item) string {2525 tokens := Tokenize(item.AsString(stripAnsi), delimiter)2550 tokens := Tokenize(item.AsString(params.stripAnsi), params.delimiter)2551 trans := Transform(tokens, ranges)2552 str := joinTokens(trans)25532554 // trim the last delimiter2530 if delimiter.str != nil {2531 str = strings.TrimSuffix(str, *delimiter.str)2532 } else if delimiter.regex != nil {2533 delims := delimiter.regex.FindAllStringIndex(str, -1)2555 if params.delimiter.str != nil {2556 str = strings.TrimSuffix(str, *params.delimiter.str)2557 } else if params.delimiter.regex != nil {2558 delims := params.delimiter.regex.FindAllStringIndex(str, -1)2559 // make sure the delimiter is at the very end of the string2560 if len(delims) > 0 && delims[len(delims)-1][1] == len(str) {2561 str = str[:delims[len(delims)-1][0]]2562 }
11 unmodified lines
25742575 // apply 'replace' function over proper set of items and return result25762577 items := current2553 if flags.plus || forcePlus {2578 if flags.plus || params.forcePlus {2579 items = selected2580 }2581 replacements := make([]string, len(items))2582
1 unmodified line
2584 replacements[idx] = replace(item)2585 }25862587 if flags.file {2563 return writeTemporaryFile(replacements, printsep)2588 return writeTemporaryFile(replacements, params.printsep)2589 }2590 return strings.Join(replacements, " ")2591 })2592}
733 unmodified lines
3326 req(reqPreviewRefresh)3327 }3328 case actTransformPrompt:3329 prompt := t.executeCommand(a.a, false, true, true, true)3330 t.promptString = prompt3331 t.prompt, t.promptLen = t.parsePrompt(prompt)3332 req(reqPrompt)3333 case actTransformQuery:3334 query := t.executeCommand(a.a, false, true, true, true)
85 unmodified lines
3420 t.previewLabel, t.previewLabelLen = t.ansiLabelPrinter(label, &tui.ColPreviewLabel, false)3421 req(reqRedrawPreviewLabel)3422 }3423 case actChangePrompt:3424 t.promptString = a.a3425 t.prompt, t.promptLen = t.parsePrompt(a.a)3426 req(reqPrompt)3427 case actPreview:3428 updatePreviewWindow(true)
700 unmodified lines
modified:CHANGELOG.md+3 added-2 removed
15 unmodified lines
16 --bind 'enter:transform:[[ -n {} ]] && echo accept || echo "change-header:Invalid selection"' \17 --bind 'focus:transform:[[ -n {} ]] && exit; [[ {fzf:action} =~ up$ ]] && echo up || echo down'18 ```19- Added placeholder expressions20 - `{fzf:action}` - the name of the last action performed21 - `{fzf:query}` - synonym for `{q}`20 - `{fzf:action}` - The name of the last action performed21 - `{fzf:prompt}` - Prompt string (including ANSI color codes)22 - `{fzf:query}` - Synonym for `{q}`23- Added support for negative height24 ```sh25 # Terminal height minus 1, so you can still see the command line26 fzf --height=-1
1780 unmodified lines