Add 'transform' action to conditionally perform a series of actions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
'transform' action runs an external command that prints a series of actions to perform. # Disallow selecting an empty line echo -e "1. Hello\n2. Goodbye\n\n3. Exit" | fzf --reverse --header 'Select one' \ --bind 'enter:transform:[[ -n {} ]] && echo accept || echo "change-header:Invalid selection"' # Move cursor past the empty line echo -e "1. Hello\n2. Goodbye\n\n3. Exit" | fzf --reverse --header 'Select one' \ --bind 'enter:transform:[[ -n {} ]] && echo accept || echo "change-header:Invalid selection"' \ --bind 'focus:transform:[[ -n {} ]] && exit; [[ {fzf:action} =~ up$ ]] && echo up || echo down' Close #3368 Close #2980
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+255 added−52 removed
- tests:+7 added−0 removed
- other:+248 added−52 removed
Provenance
- Commit
1707b8c- Tree
268e695- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
41d4d70
10 files changed+255 added−52 removed
modified:man/man1/fzf.1+9 added-4 removed
572 unmodified lines573 574 When using a field index expression, leading and trailing whitespace is stripped575 from the replacement string. To preserve the whitespace, use the \fBs\fR flag.576 577-Also, \fB{q}\fR is replaced to the current query string, and \fB{n}\fR is578-replaced to zero-based ordinal index of the line. Use \fB{+n}\fR if you want579-all index numbers when multiple lines are selected.580-577 A placeholder expression with \fBf\fR flag is replaced to the path of578 a temporary file that holds the evaluated list. This is useful when you579 multi-select a large number of items and the length of the evaluated string may580 exceed \fBARG_MAX\fR.3 unmodified lines584 # This won't work properly without 'f' flag due to ARG_MAX limit.585 seq 100000 | fzf --multi --bind ctrl-a:select-all \\586 --preview "awk '{sum+=\\$1} END {print sum}' {+f}"\fR587 588+Also,589+590+* \fB{q}\fR (or \fB{fzf:query}\fR) is replaced to the current query string591+.br592+* \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+597 Note that you can escape a placeholder pattern by prepending a backslash.598 599 Preview window will be updated even when there is no match for the current600 query if any of the placeholder expressions evaluates to a non-empty string786 unmodified linesadded:src/actiontype_string.go+127 added
1+// Code generated by "stringer -type=actionType"; DO NOT EDIT.2+3+package fzf4+5+import "strconv"6+7+func _() {8+ // An "invalid array index" compiler error signifies that the constant values have changed.9+ // Re-run the stringer command to generate them again.10+ var x [1]struct{}11+ _ = x[actIgnore-0]12+ _ = x[actStart-1]13+ _ = x[actClick-2]14+ _ = x[actInvalid-3]15+ _ = x[actChar-4]16+ _ = x[actMouse-5]17+ _ = x[actBeginningOfLine-6]18+ _ = x[actAbort-7]19+ _ = x[actAccept-8]20+ _ = x[actAcceptNonEmpty-9]21+ _ = x[actAcceptOrPrintQuery-10]22+ _ = x[actBackwardChar-11]23+ _ = x[actBackwardDeleteChar-12]24+ _ = x[actBackwardDeleteCharEof-13]25+ _ = x[actBackwardWord-14]26+ _ = x[actCancel-15]27+ _ = x[actChangeBorderLabel-16]28+ _ = x[actChangeHeader-17]29+ _ = x[actChangePreviewLabel-18]30+ _ = x[actChangePrompt-19]31+ _ = x[actChangeQuery-20]32+ _ = x[actClearScreen-21]33+ _ = x[actClearQuery-22]34+ _ = x[actClearSelection-23]35+ _ = x[actClose-24]36+ _ = x[actDeleteChar-25]37+ _ = x[actDeleteCharEof-26]38+ _ = x[actEndOfLine-27]39+ _ = x[actForwardChar-28]40+ _ = x[actForwardWord-29]41+ _ = x[actKillLine-30]42+ _ = x[actKillWord-31]43+ _ = x[actUnixLineDiscard-32]44+ _ = x[actUnixWordRubout-33]45+ _ = x[actYank-34]46+ _ = x[actBackwardKillWord-35]47+ _ = x[actSelectAll-36]48+ _ = x[actDeselectAll-37]49+ _ = x[actToggle-38]50+ _ = x[actToggleSearch-39]51+ _ = x[actToggleAll-40]52+ _ = x[actToggleDown-41]53+ _ = x[actToggleUp-42]54+ _ = x[actToggleIn-43]55+ _ = x[actToggleOut-44]56+ _ = x[actToggleTrack-45]57+ _ = x[actToggleHeader-46]58+ _ = x[actTrack-47]59+ _ = x[actDown-48]60+ _ = x[actUp-49]61+ _ = x[actPageUp-50]62+ _ = x[actPageDown-51]63+ _ = x[actPosition-52]64+ _ = x[actHalfPageUp-53]65+ _ = x[actHalfPageDown-54]66+ _ = x[actOffsetUp-55]67+ _ = x[actOffsetDown-56]68+ _ = x[actJump-57]69+ _ = x[actJumpAccept-58]70+ _ = x[actPrintQuery-59]71+ _ = x[actRefreshPreview-60]72+ _ = x[actReplaceQuery-61]73+ _ = x[actToggleSort-62]74+ _ = x[actShowPreview-63]75+ _ = x[actHidePreview-64]76+ _ = x[actTogglePreview-65]77+ _ = x[actTogglePreviewWrap-66]78+ _ = x[actTransform-67]79+ _ = x[actTransformBorderLabel-68]80+ _ = x[actTransformHeader-69]81+ _ = x[actTransformPreviewLabel-70]82+ _ = x[actTransformPrompt-71]83+ _ = x[actTransformQuery-72]84+ _ = x[actPreview-73]85+ _ = x[actChangePreview-74]86+ _ = x[actChangePreviewWindow-75]87+ _ = x[actPreviewTop-76]88+ _ = x[actPreviewBottom-77]89+ _ = x[actPreviewUp-78]90+ _ = x[actPreviewDown-79]91+ _ = x[actPreviewPageUp-80]92+ _ = x[actPreviewPageDown-81]93+ _ = x[actPreviewHalfPageUp-82]94+ _ = x[actPreviewHalfPageDown-83]95+ _ = x[actPrevHistory-84]96+ _ = x[actPrevSelected-85]97+ _ = x[actPut-86]98+ _ = x[actNextHistory-87]99+ _ = x[actNextSelected-88]100+ _ = x[actExecute-89]101+ _ = x[actExecuteSilent-90]102+ _ = x[actExecuteMulti-91]103+ _ = x[actSigStop-92]104+ _ = x[actFirst-93]105+ _ = x[actLast-94]106+ _ = x[actReload-95]107+ _ = x[actReloadSync-96]108+ _ = x[actDisableSearch-97]109+ _ = x[actEnableSearch-98]110+ _ = x[actSelect-99]111+ _ = x[actDeselect-100]112+ _ = x[actUnbind-101]113+ _ = x[actRebind-102]114+ _ = x[actBecome-103]115+ _ = x[actResponse-104]116+}117+118+const _actionType_name = "actIgnoreactStartactClickactInvalidactCharactMouseactBeginningOfLineactAbortactAcceptactAcceptNonEmptyactAcceptOrPrintQueryactBackwardCharactBackwardDeleteCharactBackwardDeleteCharEofactBackwardWordactCancelactChangeBorderLabelactChangeHeaderactChangePreviewLabelactChangePromptactChangeQueryactClearScreenactClearQueryactClearSelectionactCloseactDeleteCharactDeleteCharEofactEndOfLineactForwardCharactForwardWordactKillLineactKillWordactUnixLineDiscardactUnixWordRuboutactYankactBackwardKillWordactSelectAllactDeselectAllactToggleactToggleSearchactToggleAllactToggleDownactToggleUpactToggleInactToggleOutactToggleTrackactToggleHeaderactTrackactDownactUpactPageUpactPageDownactPositionactHalfPageUpactHalfPageDownactOffsetUpactOffsetDownactJumpactJumpAcceptactPrintQueryactRefreshPreviewactReplaceQueryactToggleSortactShowPreviewactHidePreviewactTogglePreviewactTogglePreviewWrapactTransformactTransformBorderLabelactTransformHeaderactTransformPreviewLabelactTransformPromptactTransformQueryactPreviewactChangePreviewactChangePreviewWindowactPreviewTopactPreviewBottomactPreviewUpactPreviewDownactPreviewPageUpactPreviewPageDownactPreviewHalfPageUpactPreviewHalfPageDownactPrevHistoryactPrevSelectedactPutactNextHistoryactNextSelectedactExecuteactExecuteSilentactExecuteMultiactSigStopactFirstactLastactReloadactReloadSyncactDisableSearchactEnableSearchactSelectactDeselectactUnbindactRebindactBecomeactResponse"119+120+var _actionType_index = [...]uint16{0, 9, 17, 25, 35, 42, 50, 68, 76, 85, 102, 123, 138, 159, 183, 198, 207, 227, 242, 263, 278, 292, 306, 319, 336, 344, 357, 373, 385, 399, 413, 424, 435, 453, 470, 477, 496, 508, 522, 531, 546, 558, 571, 582, 593, 605, 619, 634, 642, 649, 654, 663, 674, 685, 698, 713, 724, 737, 744, 757, 770, 787, 802, 815, 829, 843, 859, 879, 891, 914, 932, 956, 974, 991, 1001, 1017, 1039, 1052, 1068, 1080, 1094, 1110, 1128, 1148, 1170, 1184, 1199, 1205, 1219, 1234, 1244, 1260, 1275, 1285, 1293, 1300, 1309, 1322, 1338, 1353, 1362, 1373, 1382, 1391, 1400, 1411}121+122+func (i actionType) String() string {123+ if i < 0 || i >= actionType(len(_actionType_index)-1) {124+ return "actionType(" + strconv.FormatInt(int64(i), 10) + ")"125+ }126+ return _actionType_name[_actionType_index[i]:_actionType_index[i+1]]127+}modified:src/options.go+6 added-4 removed
977 unmodified lines978 )979 980 func init() {981 executeRegexp = regexp.MustCompile(982- `(?si)[:+](become|execute(?:-multi|-silent)?|reload(?:-sync)?|preview|(?:change|transform)-(?:header|query|prompt|border-label|preview-label)|change-preview-window|change-preview|(?:re|un)bind|pos|put)`)982+ `(?si)[:+](become|execute(?:-multi|-silent)?|reload(?:-sync)?|preview|(?:change|transform)-(?:header|query|prompt|border-label|preview-label)|transform|change-preview-window|change-preview|(?:re|un)bind|pos|put)`)983 splitRegexp = regexp.MustCompile("[,:]+")984 actionNameRegexp = regexp.MustCompile("(?i)^[a-z-]+")985 }986 98 unmodified lines1085 appendAction(actBackwardChar)1086 case "backward-delete-char":1087 appendAction(actBackwardDeleteChar)1088 case "backward-delete-char/eof":1089- appendAction(actBackwardDeleteCharEOF)1089+ appendAction(actBackwardDeleteCharEof)1090 case "backward-word":1091 appendAction(actBackwardWord)1092 case "clear-screen":1093 appendAction(actClearScreen)1094 case "delete-char":1095 appendAction(actDeleteChar)1096 case "delete-char/eof":1097- appendAction(actDeleteCharEOF)1097+ appendAction(actDeleteCharEof)1098 case "deselect":1099 appendAction(actDeselect)1100 case "end-of-line":1101 appendAction(actEndOfLine)110 unmodified lines1212 case "disable-search":1213 appendAction(actDisableSearch)1214 case "put":1215 if putAllowed {1216- appendAction(actRune)1216+ appendAction(actChar)1217 } else {1218 exit("unable to put non-printable character")1219 }1220 default:111 unmodified lines1332 case "execute-multi":1333 return actExecuteMulti1334 case "put":1335 return actPut1336+ case "transform":1337+ return actTransform1338 case "transform-border-label":1339 return actTransformBorderLabel1340 case "transform-preview-label":1341 return actTransformPreviewLabel832 unmodified linesmodified:src/terminal_test.go+31 added-26 removed
50 unmodified lines51 Test multiple placeholders and the function parameters.52 */53 54 // {}, preserve ansi55- result = replacePlaceholder("echo {}", false, Delimiter{}, printsep, false, "query", items1)55+ result = replacePlaceholder("echo {}", false, Delimiter{}, printsep, false, "query", items1, actIgnore)56 checkFormat("echo {{.O}} foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}")57 58 // {}, strip ansi59- result = replacePlaceholder("echo {}", true, Delimiter{}, printsep, false, "query", items1)59+ result = replacePlaceholder("echo {}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)60 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}")61 62 // {}, with multiple items63- result = replacePlaceholder("echo {}", true, Delimiter{}, printsep, false, "query", items2)63+ result = replacePlaceholder("echo {}", true, Delimiter{}, printsep, false, "query", items2, actIgnore)64 checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}")65 66 // {..}, strip leading whitespaces, preserve ansi67- result = replacePlaceholder("echo {..}", false, Delimiter{}, printsep, false, "query", items1)67+ result = replacePlaceholder("echo {..}", false, Delimiter{}, printsep, false, "query", items1, actIgnore)68 checkFormat("echo {{.O}}foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}")69 70 // {..}, strip leading whitespaces, strip ansi71- result = replacePlaceholder("echo {..}", true, Delimiter{}, printsep, false, "query", items1)71+ result = replacePlaceholder("echo {..}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)72 checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}")73 74 // {q}75- result = replacePlaceholder("echo {} {q}", true, Delimiter{}, printsep, false, "query", items1)75+ result = replacePlaceholder("echo {} {q}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)76 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}} {{.O}}query{{.O}}")77 78 // {q}, multiple items79- result = replacePlaceholder("echo {+}{q}{+}", true, Delimiter{}, printsep, false, "query 'string'", items2)79+ result = replacePlaceholder("echo {+}{q}{+}", true, Delimiter{}, printsep, false, "query 'string'", items2, actIgnore)80 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}}")81 82- result = replacePlaceholder("echo {}{q}{}", true, Delimiter{}, printsep, false, "query 'string'", items2)82+ result = replacePlaceholder("echo {}{q}{}", true, Delimiter{}, printsep, false, "query 'string'", items2, actIgnore)83 checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}{{.O}}query {{.I}}string{{.I}}{{.O}}{{.O}}foo{{.I}}bar baz{{.O}}")84 85- result = replacePlaceholder("echo {1}/{2}/{2,1}/{-1}/{-2}/{}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items1)85+ result = replacePlaceholder("echo {1}/{2}/{2,1}/{-1}/{-2}/{}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items1, actIgnore)86 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}}")87 88- result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items2)88+ result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items2, actIgnore)89 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}}")90 91- result = replacePlaceholder("echo {+1}/{+2}/{+-1}/{+-2}/{+..}/{n.t}/\\{}/\\{1}/\\{q}/{+3}", true, Delimiter{}, printsep, false, "query", items2)91+ result = replacePlaceholder("echo {+1}/{+2}/{+-1}/{+-2}/{+..}/{n.t}/\\{}/\\{1}/\\{q}/{+3}", true, Delimiter{}, printsep, false, "query", items2, actIgnore)92 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}}")93 94 // forcePlus95- result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, true, "query", items2)95+ result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, true, "query", items2, actIgnore)96 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}}")97 98 // Whitespace preserving flag with "'" delimiter99- result = replacePlaceholder("echo {s1}", true, Delimiter{str: &delim}, printsep, false, "query", items1)99+ result = replacePlaceholder("echo {s1}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)100 checkFormat("echo {{.O}} foo{{.O}}")101 102- result = replacePlaceholder("echo {s2}", true, Delimiter{str: &delim}, printsep, false, "query", items1)102+ result = replacePlaceholder("echo {s2}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)103 checkFormat("echo {{.O}}bar baz{{.O}}")104 105- result = replacePlaceholder("echo {s}", true, Delimiter{str: &delim}, printsep, false, "query", items1)105+ result = replacePlaceholder("echo {s}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)106 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}")107 108- result = replacePlaceholder("echo {s..}", true, Delimiter{str: &delim}, printsep, false, "query", items1)108+ result = replacePlaceholder("echo {s..}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)109 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}")110 111 // Whitespace preserving flag with regex delimiter112 regex = regexp.MustCompile(`\w+`)113 114- result = replacePlaceholder("echo {s1}", true, Delimiter{regex: regex}, printsep, false, "query", items1)114+ result = replacePlaceholder("echo {s1}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)115 checkFormat("echo {{.O}} {{.O}}")116 117- result = replacePlaceholder("echo {s2}", true, Delimiter{regex: regex}, printsep, false, "query", items1)117+ result = replacePlaceholder("echo {s2}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)118 checkFormat("echo {{.O}}{{.I}}{{.O}}")119 120- result = replacePlaceholder("echo {s3}", true, Delimiter{regex: regex}, printsep, false, "query", items1)120+ result = replacePlaceholder("echo {s3}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)121 checkFormat("echo {{.O}} {{.O}}")122 123 // No match124- result = replacePlaceholder("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, nil})124+ result = replacePlaceholder("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, nil}, actIgnore)125 check("echo /")126 127 // No match, but with selections128- result = replacePlaceholder("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, item1})128+ result = replacePlaceholder("echo {}/{+}", true, Delimiter{}, printsep, false, "query", []*Item{nil, item1}, actIgnore)129 checkFormat("echo /{{.O}} foo{{.I}}bar baz{{.O}}")130 131 // String delimiter132- result = replacePlaceholder("echo {}/{1}/{2}", true, Delimiter{str: &delim}, printsep, false, "query", items1)132+ result = replacePlaceholder("echo {}/{1}/{2}", true, Delimiter{str: &delim}, printsep, false, "query", items1, actIgnore)133 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}/{{.O}}foo{{.O}}/{{.O}}bar baz{{.O}}")134 135 // Regex delimiter136 regex = regexp.MustCompile("[oa]+")137 // foo'bar baz138- result = replacePlaceholder("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, printsep, false, "query", items1)138+ result = replacePlaceholder("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, printsep, false, "query", items1, actIgnore)139 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}/{{.O}}f{{.O}}/{{.O}}r b{{.O}}/{{.O}}{{.I}}bar b{{.O}}")140 141 /*142 Test single placeholders, but focus on the placeholders' parameters (e.g. flags).54 unmodified lines197 // III. query type placeholder198 // query flag is not removed after parsing, so it gets doubled199 // while the double q is invalid, it is useful here for testing purposes200 templateToOutput[`{q}`] = "{{.O}}" + query + "{{.O}}"201+ templateToOutput[`{fzf:query}`] = "{{.O}}" + query + "{{.O}}"202+ templateToOutput[`{fzf:action}`] = "backward-delete-char-eof"203 204 // IV. escaping placeholder205 templateToOutput[`\{}`] = `{}`206+ templateToOutput[`\{q}`] = `{q}`207+ templateToOutput[`\{fzf:query}`] = `{fzf:query}`208+ templateToOutput[`\{fzf:action}`] = `{fzf:action}`209 templateToOutput[`\{++}`] = `{++}`210 templateToOutput[`{++}`] = templateToOutput[`{+}`]211 212 for giveTemplate, wantOutput := range templateToOutput {208- result = replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)213+ result = replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3, actBackwardDeleteCharEof)214 checkFormat(wantOutput)215 }216 for giveTemplate, wantOutput := range templateToFile {212- path := replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)217+ path := replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3, actIgnore)218 219 data, err := readFile(path)220 if err != nil {221 t.Errorf("Cannot read the content of the temp file %s.", path)348 unmodified lines570 for idx, test := range tests {571 gotOutput := replacePlaceholder(572 test.give.template, stripAnsi, delimiter, printsep, forcePlus,573 test.give.query,569- test.give.allItems)574+ test.give.allItems, actIgnore)575 switch {576 case test.want.output != "":577 if gotOutput != test.want.output {578 t.Errorf("tests[%v]:\ngave{\n\ttemplate: '%s',\n\tquery: '%s',\n\tallItems: %s}\nand got '%s',\nbut want '%s'",65 unmodified linesmodified:src/terminal.go+46 added-16 removed
50 unmodified lines51 var offsetComponentRegex *regexp.Regexp52 var offsetTrimCharsRegex *regexp.Regexp53 var activeTempFiles []string54 var passThroughRegex *regexp.Regexp55+var actionTypeRegex *regexp.Regexp56 57 const clearCode string = "\x1b[2J"58 59 func init() {59- placeholder = regexp.MustCompile(`\\?(?:{[+sf]*[0-9,-.]*}|{q}|{\+?f?nf?})`)60+ placeholder = regexp.MustCompile(`\\?(?:{[+sf]*[0-9,-.]*}|{q}|{fzf:(?:query|action)}|{\+?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{}220 unmodified lines285 theme *tui.ColorTheme286 tui tui.Renderer287 executing *util.AtomicBool288 termSize tui.TermSize289+ lastAction actionType290 }291 292 type selectedItem struct {293 at time.Time39 unmodified lines333 t actionType334 a string335 }336 337+//go:generate stringer -type=actionType338 type actionType int339 340 const (341 actIgnore actionType = iota342+ actStart343+ actClick344 actInvalid340- actRune345+ actChar346 actMouse347 actBeginningOfLine348 actAbort349 actAccept350 actAcceptNonEmpty351 actAcceptOrPrintQuery352 actBackwardChar353 actBackwardDeleteChar349- actBackwardDeleteCharEOF354+ actBackwardDeleteCharEof355 actBackwardWord356 actCancel357 actChangeBorderLabel358 actChangeHeader4 unmodified lines363 actClearQuery364 actClearSelection365 actClose366 actDeleteChar362- actDeleteCharEOF367+ actDeleteCharEof368 actEndOfLine369 actForwardChar370 actForwardWord371 actKillLine32 unmodified lines404 actShowPreview405 actHidePreview406 actTogglePreview407 actTogglePreviewWrap408+ actTransform409 actTransformBorderLabel410 actTransformHeader411 actTransformPreviewLabel412 actTransformPrompt33 unmodified lines446 )447 448 func processExecution(action actionType) bool {449 switch action {444- case actTransformBorderLabel,450+ case actTransform,451+ actTransformBorderLabel,452 actTransformHeader,453 actTransformPreviewLabel,454 actTransformPrompt,455 actTransformQuery,456 actPreview,457 actChangePreview,458+ actRefreshPreview,459 actExecute,460 actExecuteSilent,461 actExecuteMulti,462 actReload,58 unmodified lines521 add(tui.CtrlC, actAbort)522 add(tui.CtrlG, actAbort)523 add(tui.CtrlQ, actAbort)524 add(tui.ESC, actAbort)517- add(tui.CtrlD, actDeleteCharEOF)525+ add(tui.CtrlD, actDeleteCharEof)526 add(tui.CtrlE, actEndOfLine)527 add(tui.CtrlF, actForwardChar)528 add(tui.CtrlH, actBackwardDeleteChar)529 add(tui.BSpace, actBackwardDeleteChar)33 unmodified lines563 add(tui.SUp, actPreviewUp)564 add(tui.SDown, actPreviewDown)565 566 add(tui.Mouse, actMouse)559- add(tui.LeftClick, actIgnore)567+ add(tui.LeftClick, actClick)568 add(tui.RightClick, actToggle)569 add(tui.SLeftClick, actToggle)570 add(tui.SRightClick, actToggle)571 175 unmodified lines747 serverOutputChan: make(chan string),748 eventChan: make(chan tui.Event, 3), // load / zero|one | GetChar749 tui: renderer,750 initFunc: func() { renderer.Init() },743- executing: util.NewAtomicBool(false)}751+ executing: util.NewAtomicBool(false),752+ lastAction: actStart}753 t.prompt, t.promptLen = t.parsePrompt(opts.Prompt)754 t.pointer, t.pointerLen = t.processTabs([]rune(opts.Pointer), 0)755 t.marker, t.markerLen = t.processTabs([]rune(opts.Marker), 0)756 // Pre-calculated empty pointer and marker signs1595 unmodified lines2352 // Escaped placeholder pattern2353 return true, match[1:], flags2354 }2355 2356+ if strings.HasPrefix(match, "{fzf:") {2357+ return false, match, flags2358+ }2359+2360 skipChars := 12361 for _, char := range match[1:] {2362 switch char {2363 case '+':56 unmodified lines2420 }2421 2422 func (t *Terminal) replacePlaceholder(template string, forcePlus bool, input string, list []*Item) string {2423 return replacePlaceholder(2411- template, t.ansi, t.delimiter, t.printsep, forcePlus, input, list)2424+ template, t.ansi, t.delimiter, t.printsep, forcePlus, input, list, t.lastAction)2425 }2426 2427 func (t *Terminal) evaluateScrollOffset() int {2428 if t.pwindow == nil {29 unmodified lines2458 }2459 return util.Max(0, base)2460 }2461 2449-func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems []*Item) string {2462+func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems []*Item, lastAction actionType) string {2463 current := allItems[:1]2464 selected := allItems[1:]2465 if current[0] == nil {2466 current = []*Item{}12 unmodified lines2479 // placeholder types (escaped, query type, item type, token type)2480 switch {2481 case escaped:2482 return match2470- case match == "{q}":2483+ case match == "{fzf:action}":2484+ name := ""2485+ for i, r := range lastAction.String()[3:] {2486+ if i > 0 && r >= 'A' && r <= 'Z' {2487+ name += "-"2488+ }2489+ name += string(r)2490+ }2491+ return strings.ToLower(name)2492+ case match == "{q}" || match == "{fzf:query}":2493 return quoteEntry(query)2494 case match == "{}":2495 replace = func(item *Item) string {2496 switch {731 unmodified lines3228 return true3229 }3230 doAction = func(a *action) bool {3231 switch a.t {3210- case actIgnore:3232+ case actIgnore, actStart, actClick:3233 case actResponse:3234 t.serverOutputChan <- t.dumpStatus(parseGetParams(a.a))3235 case actBecome:3236 valid, list := t.buildPlusList(a.a, false)138 unmodified lines3375 if t.pborder != nil {3376 t.previewLabel, t.previewLabelLen = t.ansiLabelPrinter(a.a, &tui.ColPreviewLabel, false)3377 req(reqRedrawPreviewLabel)3378 }3379+ case actTransform:3380+ body := t.executeCommand(a.a, false, true, true, false)3381+ actions := parseSingleActionList(strings.Trim(body, "\r\n"), func(message string) {})3382+ t.serverInputChan <- actions3383 case actTransformBorderLabel:3384 if t.border != nil {3385 label := t.executeCommand(a.a, false, true, true, true)3386 t.borderLabel, t.borderLabelLen = t.ansiLabelPrinter(label, &tui.ColBorderLabel, false)22 unmodified lines3409 case actAbort:3410 req(reqQuit)3411 case actDeleteChar:3412 t.delChar()3387- case actDeleteCharEOF:3413+ case actDeleteCharEof:3414 if !t.delChar() && t.cx == 0 {3415 req(reqQuit)3416 }3417 case actEndOfLine:5 unmodified lines3423 t.yanked = t.input3424 t.input = []rune{}3425 t.cx = 03426 }3401- case actBackwardDeleteCharEOF:3427+ case actBackwardDeleteCharEof:3428 if len(t.input) == 0 {3429 req(reqQuit)3430 } else if t.cx > 0 {3431 t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)210 unmodified lines3642 if t.cx < len(t.input) {3643 t.yanked = copySlice(t.input[t.cx:])3644 t.input = t.input[:t.cx]3645 }3620- case actRune:3646+ case actChar:3647 prefix := copySlice(t.input[:t.cx])3648 t.input = append(append(prefix, event.Char), t.input[t.cx:]...)3649 t.cx++3650 case actPrevHistory:269 unmodified lines3920 }3921 }3922 }3923 }3924+3925+ if !processExecution(a.t) {3926+ t.lastAction = a.t3927+ }3928 return true3929 }3930 3931 if t.jumping == jumpDisabled || len(actions) > 0 {5 unmodified lines3937 if len(actions) == 0 {3938 actions = t.keymap[event.Comparable()]3939 }3940 if len(actions) == 0 && event.Type == tui.Rune {3911- doAction(&action{t: actRune})3941+ doAction(&action{t: actChar})3942 } else if !doActions(actions) {3943 continue3944 }3945 t.truncateQuery()154 unmodified linesmodified:test/test_go.rb+7 added
2014 unmodified lines2015 tmux.send_keys 'C-u'2016 tmux.until { |lines| assert_equal '> RAB', lines[-1] }2017 end2018 2019+ def test_transform2020+ tmux.send_keys %{#{FZF} --bind 'focus:transform:echo "change-prompt({fzf:action})"'}, :Enter2021+ tmux.until { |lines| assert_equal 'start', lines[-1] }2022+ tmux.send_keys :Up2023+ tmux.until { |lines| assert_equal 'up', lines[-1] }2024+ end2025+2026 def test_clear_selection2027 tmux.send_keys %(seq 100 | #{FZF} --multi --bind space:clear-selection), :Enter2028 tmux.until { |lines| assert_equal 100, lines.match_count }2029 tmux.send_keys :Tab1549 unmodified linesmodified:CHANGELOG.md+16 added
1 unmodified line2 =========3 4 0.45.05 ------6+- Added `transform` action to conditionally perform a series of actions7+ ```sh8+ # Disallow selecting an empty line9+ echo -e "1. Hello\n2. Goodbye\n\n3. Exit" |10+ fzf --reverse --header 'Select one' \11+ --bind 'enter:transform:[[ -n {} ]] && echo accept || echo "change-header:Invalid selection"'12+13+ # Move cursor past the empty line14+ echo -e "1. Hello\n2. Goodbye\n\n3. Exit" |15+ fzf --reverse --header 'Select one' \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}`22 - Added support for negative height23 ```sh24 # Terminal height minus 1, so you can still see the command line25 fzf --height=-11780 unmodified linesmodified:go.mod+3 added-1 removed
12 unmodified lines13 14 require (15 github.com/gdamore/encoding v1.0.0 // indirect16 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect17- golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect17+ golang.org/x/mod v0.14.0 // indirect18+ golang.org/x/sync v0.5.0 // indirect19 golang.org/x/text v0.5.0 // indirect20+ golang.org/x/tools v0.16.1 // indirect21 )22 23 go 1.17modified:go.sum+6 added
17 unmodified lines18 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=19 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=20 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=21 golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=22+golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=23+golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=24 golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=25 golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=26 golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=27 golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=28 golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=29 golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw=30 golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=31+golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=32+golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=33 golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=34 golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=35 golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=36 golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=12 unmodified lines49 golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=50 golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=51 golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=52 golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=53+golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA=54+golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=55 golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=modified:Makefile+4 added-1 removed
87 unmodified lines88 cd src && SHELL=/bin/sh GOOS= $(GO) test -v -tags "$(TAGS)" -run=Bench -bench=. -benchmem89 90 install: bin/fzf91 92+generate:93+ PATH=$(PATH):$(GOPATH)/bin $(GO) generate ./...94+95 build:96 goreleaser build --rm-dist --snapshot --skip-post-hooks97 98 release:84 unmodified lines183 update:184 $(GO) get -u185 $(GO) mod tidy186 184-.PHONY: all build release test bench install clean docker docker-test update187+.PHONY: all generate build release test bench install clean docker docker-test update