Implement change-preview and change-preview-window actions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The new actions are named with 'change-' prefix to differentiate from the pre-existing, one-off 'preview(...)' action. Fix #2360 Fix #2505 Fix #2666 Related #2435 Related #2376 - Can set up multiple bindings with different change-preview-window actions - Not possible to "rotate" through the options with a single binding - Enlarge or shrink not possible
authored by Junegunn Choi · committed by Junegunn Choi · parent 7da287e · Browse files · 5 files·+367 added−221 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+367 added−221 removed
- tests:+49 added−0 removed
- other:+318 added−221 removed
Provenance
- Commit
20b4e69- Tree
d2c2b35- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
7da287e
5 files changed+367 added−221 removed
modified:man/man1/fzf.1+58 added-56 removed
19 unmodified lines20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22 THE SOFTWARE.23 ..24-.TH fzf 1 "Nov 2021" "fzf 0.28.0" "fzf - a command-line fuzzy finder"24+.TH fzf 1 "Dec 2021" "fzf 0.29.0" "fzf - a command-line fuzzy finder"25 26 .SH NAME27 fzf - a command-line fuzzy finder28 780 unmodified lines809 .SS AVAILABLE ACTIONS:810 A key or an event can be bound to one or more of the following actions.811 812 \fBACTION: DEFAULT BINDINGS (NOTES):813- \fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR814- \fBaccept\fR \fIenter double-click\fR815- \fBaccept-non-empty\fR (same as \fBaccept\fR except that it prevents fzf from exiting without selection)816- \fBbackward-char\fR \fIctrl-b left\fR817- \fBbackward-delete-char\fR \fIctrl-h bspace\fR818- \fBbackward-delete-char/eof\fR (same as \fBbackward-delete-char\fR except aborts fzf if query is empty)819- \fBbackward-kill-word\fR \fIalt-bs\fR820- \fBbackward-word\fR \fIalt-b shift-left\fR821- \fBbeginning-of-line\fR \fIctrl-a home\fR822- \fBcancel\fR (clear query string if not empty, abort fzf otherwise)823- \fBchange-prompt(...)\fR (change prompt to the given string)824- \fBclear-screen\fR \fIctrl-l\fR825- \fBclear-selection\fR (clear multi-selection)826- \fBclose\fR (close preview window if open, abort fzf otherwise)827- \fBclear-query\fR (clear query string)828- \fBdelete-char\fR \fIdel\fR829- \fBdelete-char/eof\fR \fIctrl-d\fR (same as \fBdelete-char\fR except aborts fzf if query is empty)813+ \fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR814+ \fBaccept\fR \fIenter double-click\fR815+ \fBaccept-non-empty\fR (same as \fBaccept\fR except that it prevents fzf from exiting without selection)816+ \fBbackward-char\fR \fIctrl-b left\fR817+ \fBbackward-delete-char\fR \fIctrl-h bspace\fR818+ \fBbackward-delete-char/eof\fR (same as \fBbackward-delete-char\fR except aborts fzf if query is empty)819+ \fBbackward-kill-word\fR \fIalt-bs\fR820+ \fBbackward-word\fR \fIalt-b shift-left\fR821+ \fBbeginning-of-line\fR \fIctrl-a home\fR822+ \fBcancel\fR (clear query string if not empty, abort fzf otherwise)823+ \fBchange-preview(...)\fR (change \fB--preview\fR option)824+ \fBchange-preview-window(...)\fR (change \fB--preview-window\fR option)825+ \fBchange-prompt(...)\fR (change prompt to the given string)826+ \fBclear-screen\fR \fIctrl-l\fR827+ \fBclear-selection\fR (clear multi-selection)828+ \fBclose\fR (close preview window if open, abort fzf otherwise)829+ \fBclear-query\fR (clear query string)830+ \fBdelete-char\fR \fIdel\fR831+ \fBdelete-char/eof\fR \fIctrl-d\fR (same as \fBdelete-char\fR except aborts fzf if query is empty)832 \fBdeselect\fR831- \fBdeselect-all\fR (deselect all matches)832- \fBdisable-search\fR (disable search functionality)833- \fBdown\fR \fIctrl-j ctrl-n down\fR834- \fBenable-search\fR (enable search functionality)835- \fBend-of-line\fR \fIctrl-e end\fR836- \fBexecute(...)\fR (see below for the details)837- \fBexecute-silent(...)\fR (see below for the details)838- \fBfirst\fR (move to the first match)839- \fBforward-char\fR \fIctrl-f right\fR840- \fBforward-word\fR \fIalt-f shift-right\fR833+ \fBdeselect-all\fR (deselect all matches)834+ \fBdisable-search\fR (disable search functionality)835+ \fBdown\fR \fIctrl-j ctrl-n down\fR836+ \fBenable-search\fR (enable search functionality)837+ \fBend-of-line\fR \fIctrl-e end\fR838+ \fBexecute(...)\fR (see below for the details)839+ \fBexecute-silent(...)\fR (see below for the details)840+ \fBfirst\fR (move to the first match)841+ \fBforward-char\fR \fIctrl-f right\fR842+ \fBforward-word\fR \fIalt-f shift-right\fR843 \fBignore\fR842- \fBjump\fR (EasyMotion-like 2-keystroke movement)843- \fBjump-accept\fR (jump and accept)844+ \fBjump\fR (EasyMotion-like 2-keystroke movement)845+ \fBjump-accept\fR (jump and accept)846 \fBkill-line\fR845- \fBkill-word\fR \fIalt-d\fR846- \fBlast\fR (move to the last match)847- \fBnext-history\fR (\fIctrl-n\fR on \fB--history\fR)848- \fBpage-down\fR \fIpgdn\fR849- \fBpage-up\fR \fIpgup\fR847+ \fBkill-word\fR \fIalt-d\fR848+ \fBlast\fR (move to the last match)849+ \fBnext-history\fR (\fIctrl-n\fR on \fB--history\fR)850+ \fBpage-down\fR \fIpgdn\fR851+ \fBpage-up\fR \fIpgup\fR852 \fBhalf-page-down\fR853 \fBhalf-page-up\fR852- \fBpreview(...)\fR (see below for the details)853- \fBpreview-down\fR \fIshift-down\fR854- \fBpreview-up\fR \fIshift-up\fR854+ \fBpreview(...)\fR (see below for the details)855+ \fBpreview-down\fR \fIshift-down\fR856+ \fBpreview-up\fR \fIshift-up\fR857 \fBpreview-page-down\fR858 \fBpreview-page-up\fR859 \fBpreview-half-page-down\fR860 \fBpreview-half-page-up\fR861 \fBpreview-bottom\fR862 \fBpreview-top\fR861- \fBprevious-history\fR (\fIctrl-p\fR on \fB--history\fR)862- \fBprint-query\fR (print query and exit)863- \fBput\fR (put the character to the prompt)863+ \fBprevious-history\fR (\fIctrl-p\fR on \fB--history\fR)864+ \fBprint-query\fR (print query and exit)865+ \fBput\fR (put the character to the prompt)866 \fBrefresh-preview\fR865- \fBreload(...)\fR (see below for the details)866- \fBreplace-query\fR (replace query string with the current selection)867+ \fBreload(...)\fR (see below for the details)868+ \fBreplace-query\fR (replace query string with the current selection)869 \fBselect\fR868- \fBselect-all\fR (select all matches)869- \fBtoggle\fR (\fIright-click\fR)870- \fBtoggle-all\fR (toggle all matches)871- \fBtoggle+down\fR \fIctrl-i (tab)\fR872- \fBtoggle-in\fR (\fB--layout=reverse*\fR ? \fBtoggle+up\fR : \fBtoggle+down\fR)873- \fBtoggle-out\fR (\fB--layout=reverse*\fR ? \fBtoggle+down\fR : \fBtoggle+up\fR)870+ \fBselect-all\fR (select all matches)871+ \fBtoggle\fR (\fIright-click\fR)872+ \fBtoggle-all\fR (toggle all matches)873+ \fBtoggle+down\fR \fIctrl-i (tab)\fR874+ \fBtoggle-in\fR (\fB--layout=reverse*\fR ? \fBtoggle+up\fR : \fBtoggle+down\fR)875+ \fBtoggle-out\fR (\fB--layout=reverse*\fR ? \fBtoggle+down\fR : \fBtoggle+up\fR)876 \fBtoggle-preview\fR877 \fBtoggle-preview-wrap\fR876- \fBtoggle-search\fR (toggle search functionality)878+ \fBtoggle-search\fR (toggle search functionality)879 \fBtoggle-sort\fR878- \fBtoggle+up\fR \fIbtab (shift-tab)\fR879- \fBunbind(...)\fR (unbind bindings)880- \fBunix-line-discard\fR \fIctrl-u\fR881- \fBunix-word-rubout\fR \fIctrl-w\fR882- \fBup\fR \fIctrl-k ctrl-p up\fR883- \fByank\fR \fIctrl-y\fR880+ \fBtoggle+up\fR \fIbtab (shift-tab)\fR881+ \fBunbind(...)\fR (unbind bindings)882+ \fBunix-line-discard\fR \fIctrl-u\fR883+ \fBunix-word-rubout\fR \fIctrl-w\fR884+ \fBup\fR \fIctrl-k ctrl-p up\fR885+ \fByank\fR \fIctrl-y\fR886 887 .SS ACTION COMPOSITION888 889 Multiple actions can be chained using \fB+\fR separator.114 unmodified linesmodified:src/options.go+43 added-2 removed
174 unmodified lines175 border tui.BorderShape176 headerLines int177 }178 179+func (a previewOpts) sameLayout(b previewOpts) bool {180+ return a.size == b.size && a.position == b.position && a.border == b.border && a.hidden == b.hidden181+}182+183+func (a previewOpts) sameContentLayout(b previewOpts) bool {184+ return a.wrap == b.wrap && a.headerLines == b.headerLines185+}186+187 // Options stores the values of command-line options188 type Options struct {189 Fuzzy bool190 FuzzyAlgo algo.Algo603 unmodified lines794 func init() {795 // Backreferences are not supported.796 // "~!@#$%^&*;/|".each_char.map { |c| Regexp.escape(c) }.map { |c| "#{c}[^#{c}]*#{c}" }.join('|')797 executeRegexp = regexp.MustCompile(790- `(?si)[:+](execute(?:-multi|-silent)?|reload|preview|change-prompt|unbind):.+|[:+](execute(?:-multi|-silent)?|reload|preview|change-prompt|unbind)(\([^)]*\)|\[[^\]]*\]|~[^~]*~|![^!]*!|@[^@]*@|\#[^\#]*\#|\$[^\$]*\$|%[^%]*%|\^[^\^]*\^|&[^&]*&|\*[^\*]*\*|;[^;]*;|/[^/]*/|\|[^\|]*\|)`)798+ `(?si)[:+](execute(?:-multi|-silent)?|reload|preview|change-prompt|change-preview-window|change-preview|unbind):.+|[:+](execute(?:-multi|-silent)?|reload|preview|change-prompt|change-preview-window|change-preview|unbind)(\([^)]*\)|\[[^\]]*\]|~[^~]*~|![^!]*!|@[^@]*@|\#[^\#]*\#|\$[^\$]*\$|%[^%]*%|\^[^\^]*\^|&[^&]*&|\*[^\*]*\*|;[^;]*;|/[^/]*/|\|[^\|]*\|)`)799 }800 801 func parseKeymap(keymap map[tui.Event][]action, str string) {802 masked := executeRegexp.ReplaceAllStringFunc(str, func(src string) string {3 unmodified lines806 }807 prefix := symbol + "execute"808 if strings.HasPrefix(src[1:], "reload") {809 prefix = symbol + "reload"810+ } else if strings.HasPrefix(src[1:], "change-preview-window") {811+ prefix = symbol + "change-preview-window"812+ } else if strings.HasPrefix(src[1:], "change-preview") {813+ prefix = symbol + "change-preview"814 } else if strings.HasPrefix(src[1:], "preview") {815 prefix = symbol + "preview"816 } else if strings.HasPrefix(src[1:], "unbind") {817 prefix = symbol + "unbind"195 unmodified lines1013 case actReload:1014 offset = len("reload")1015 case actPreview:1016 offset = len("preview")1017+ case actChangePreviewWindow:1018+ offset = len("change-preview-window")1019+ case actChangePreview:1020+ offset = len("change-preview")1021 case actChangePrompt:1022 offset = len("change-prompt")1023 case actUnbind:1024 offset = len("unbind")18 unmodified lines1043 actions = append(actions, action{t: t, a: actionArg})1044 }1045 if t == actUnbind {1046 parseKeyChords(actionArg, "unbind target required")1047+ } else if t == actChangePreviewWindow {1048+ opts := previewOpts{}1049+ parsePreviewWindow(&opts, actionArg)1050 }1051 }1052 }1053 prevSpec = ""17 unmodified lines1071 case "unbind":1072 return actUnbind1073 case "preview":1074 return actPreview1075+ case "change-preview-window":1076+ return actChangePreviewWindow1077+ case "change-preview":1078+ return actChangePreview1079 case "change-prompt":1080 return actChangePrompt1081 case "execute":1082 return actExecute572 unmodified lines1655 1656 // Extend the default key map1657 keymap := defaultKeymap()1658 for key, actions := range opts.Keymap {1659+ lastChangePreviewWindow := action{t: actIgnore}1660 for _, act := range actions {1637- if act.t == actToggleSort {1661+ switch act.t {1662+ case actToggleSort:1663+ // To display "+S"/"-S" on info line1664 opts.ToggleSort = true1665+ case actChangePreviewWindow:1666+ lastChangePreviewWindow = act1667 }1668 }1669+ // Re-organize actions so that we only keep the last change-preview-window1670+ // and it comes first in the list.1671+ // * change-preview-window(up,+10)+preview(sleep 3; cat {})+change-preview-window(up,+20)1672+ // -> change-preview-window(up,+20)+preview(sleep 3; cat {})1673+ if lastChangePreviewWindow.t == actChangePreviewWindow {1674+ reordered := []action{lastChangePreviewWindow}1675+ for _, act := range actions {1676+ if act.t != actChangePreviewWindow {1677+ reordered = append(reordered, act)1678+ }1679+ }1680+ actions = reordered1681+ }1682 keymap[key] = actions1683 }1684 opts.Keymap = keymap1685 47 unmodified linesmodified:src/terminal.go+210 added-163 removed
102 unmodified lines103 var emptyLine = itemLine{}104 105 // Terminal represents terminal input/output106 type Terminal struct {107- initDelay time.Duration108- infoStyle infoStyle109- spinner []string110- prompt func()111- promptLen int112- pointer string113- pointerLen int114- pointerEmpty string115- marker string116- markerLen int117- markerEmpty string118- queryLen [2]int119- layout layoutType120- fullscreen bool121- keepRight bool122- hscroll bool123- hscrollOff int124- scrollOff int125- wordRubout string126- wordNext string127- cx int128- cy int129- offset int130- xoffset int131- yanked []rune132- input []rune133- multi int134- sort bool135- toggleSort bool136- delimiter Delimiter137- expect map[tui.Event]string138- keymap map[tui.Event][]action139- pressed string140- printQuery bool141- history *History142- cycle bool143- headerFirst bool144- headerLines int145- header []string146- header0 []string147- ansi bool148- tabstop int149- margin [4]sizeSpec150- padding [4]sizeSpec151- strong tui.Attr152- unicode bool153- borderShape tui.BorderShape154- cleanExit bool155- paused bool156- border tui.Window157- window tui.Window158- pborder tui.Window159- pwindow tui.Window160- count int161- progress int162- reading bool163- running bool164- failed *string165- jumping jumpMode166- jumpLabels string167- printer func(string)168- printsep string169- merger *Merger170- selected map[int32]selectedItem171- version int64172- reqBox *util.EventBox173- previewOpts previewOpts174- previewer previewer175- previewed previewed176- previewBox *util.EventBox177- eventBox *util.EventBox178- mutex sync.Mutex179- initFunc func()180- prevLines []itemLine181- suppress bool182- sigstop bool183- startChan chan bool184- killChan chan int185- slab *util.Slab186- theme *tui.ColorTheme187- tui tui.Renderer188- executing *util.AtomicBool107+ initDelay time.Duration108+ infoStyle infoStyle109+ spinner []string110+ prompt func()111+ promptLen int112+ pointer string113+ pointerLen int114+ pointerEmpty string115+ marker string116+ markerLen int117+ markerEmpty string118+ queryLen [2]int119+ layout layoutType120+ fullscreen bool121+ keepRight bool122+ hscroll bool123+ hscrollOff int124+ scrollOff int125+ wordRubout string126+ wordNext string127+ cx int128+ cy int129+ offset int130+ xoffset int131+ yanked []rune132+ input []rune133+ multi int134+ sort bool135+ toggleSort bool136+ delimiter Delimiter137+ expect map[tui.Event]string138+ keymap map[tui.Event][]action139+ pressed string140+ printQuery bool141+ history *History142+ cycle bool143+ headerFirst bool144+ headerLines int145+ header []string146+ header0 []string147+ ansi bool148+ tabstop int149+ margin [4]sizeSpec150+ padding [4]sizeSpec151+ strong tui.Attr152+ unicode bool153+ borderShape tui.BorderShape154+ cleanExit bool155+ paused bool156+ border tui.Window157+ window tui.Window158+ pborder tui.Window159+ pwindow tui.Window160+ count int161+ progress int162+ reading bool163+ running bool164+ failed *string165+ jumping jumpMode166+ jumpLabels string167+ printer func(string)168+ printsep string169+ merger *Merger170+ selected map[int32]selectedItem171+ version int64172+ reqBox *util.EventBox173+ initialPreviewOpts previewOpts174+ previewOpts previewOpts175+ previewer previewer176+ previewed previewed177+ previewBox *util.EventBox178+ eventBox *util.EventBox179+ mutex sync.Mutex180+ initFunc func()181+ prevLines []itemLine182+ suppress bool183+ sigstop bool184+ startChan chan bool185+ killChan chan int186+ slab *util.Slab187+ theme *tui.ColorTheme188+ tui tui.Renderer189+ executing *util.AtomicBool190 }191 192 type selectedItem struct {193 at time.Time92 unmodified lines286 actToggleSort287 actTogglePreview288 actTogglePreviewWrap289 actPreview290+ actChangePreview291+ actChangePreviewWindow292 actPreviewTop293 actPreviewBottom294 actPreviewUp295 actPreviewDown30 unmodified lines326 command *string327 }328 329 type previewRequest struct {327- template string328- pwindow tui.Window329- list []*Item330+ template string331+ pwindow tui.Window332+ scrollOffset int333+ list []*Item334 }335 336 type previewResult struct {337 version int6481 unmodified lines419 420 func hasPreviewAction(opts *Options) bool {421 for _, actions := range opts.Keymap {422 for _, action := range actions {419- if action.t == actPreview {423+ if action.t == actPreview || action.t == actChangePreview {424 return true425 }426 }427 }71 unmodified lines499 wordRubout = fmt.Sprintf("%s[^%s]", sep, sep)500 wordNext = fmt.Sprintf("[^%s]%s|(.$)", sep, sep)501 }502 t := Terminal{499- initDelay: delay,500- infoStyle: opts.InfoStyle,501- spinner: makeSpinner(opts.Unicode),502- queryLen: [2]int{0, 0},503- layout: opts.Layout,504- fullscreen: fullscreen,505- keepRight: opts.KeepRight,506- hscroll: opts.Hscroll,507- hscrollOff: opts.HscrollOff,508- scrollOff: opts.ScrollOff,509- wordRubout: wordRubout,510- wordNext: wordNext,511- cx: len(input),512- cy: 0,513- offset: 0,514- xoffset: 0,515- yanked: []rune{},516- input: input,517- multi: opts.Multi,518- sort: opts.Sort > 0,519- toggleSort: opts.ToggleSort,520- delimiter: opts.Delimiter,521- expect: opts.Expect,522- keymap: opts.Keymap,523- pressed: "",524- printQuery: opts.PrintQuery,525- history: opts.History,526- margin: opts.Margin,527- padding: opts.Padding,528- unicode: opts.Unicode,529- borderShape: opts.BorderShape,530- cleanExit: opts.ClearOnExit,531- paused: opts.Phony,532- strong: strongAttr,533- cycle: opts.Cycle,534- headerFirst: opts.HeaderFirst,535- headerLines: opts.HeaderLines,536- header: header,537- header0: header,538- ansi: opts.Ansi,539- tabstop: opts.Tabstop,540- reading: true,541- running: true,542- failed: nil,543- jumping: jumpDisabled,544- jumpLabels: opts.JumpLabels,545- printer: opts.Printer,546- printsep: opts.PrintSep,547- merger: EmptyMerger,548- selected: make(map[int32]selectedItem),549- reqBox: util.NewEventBox(),550- previewOpts: opts.Preview,551- previewer: previewer{0, []string{}, 0, showPreviewWindow, false, true, false, ""},552- previewed: previewed{0, 0, 0, false},553- previewBox: previewBox,554- eventBox: eventBox,555- mutex: sync.Mutex{},556- suppress: true,557- sigstop: false,558- slab: util.MakeSlab(slab16Size, slab32Size),559- theme: opts.Theme,560- startChan: make(chan bool, 1),561- killChan: make(chan int),562- tui: renderer,563- initFunc: func() { renderer.Init() },564- executing: util.NewAtomicBool(false)}503+ initDelay: delay,504+ infoStyle: opts.InfoStyle,505+ spinner: makeSpinner(opts.Unicode),506+ queryLen: [2]int{0, 0},507+ layout: opts.Layout,508+ fullscreen: fullscreen,509+ keepRight: opts.KeepRight,510+ hscroll: opts.Hscroll,511+ hscrollOff: opts.HscrollOff,512+ scrollOff: opts.ScrollOff,513+ wordRubout: wordRubout,514+ wordNext: wordNext,515+ cx: len(input),516+ cy: 0,517+ offset: 0,518+ xoffset: 0,519+ yanked: []rune{},520+ input: input,521+ multi: opts.Multi,522+ sort: opts.Sort > 0,523+ toggleSort: opts.ToggleSort,524+ delimiter: opts.Delimiter,525+ expect: opts.Expect,526+ keymap: opts.Keymap,527+ pressed: "",528+ printQuery: opts.PrintQuery,529+ history: opts.History,530+ margin: opts.Margin,531+ padding: opts.Padding,532+ unicode: opts.Unicode,533+ borderShape: opts.BorderShape,534+ cleanExit: opts.ClearOnExit,535+ paused: opts.Phony,536+ strong: strongAttr,537+ cycle: opts.Cycle,538+ headerFirst: opts.HeaderFirst,539+ headerLines: opts.HeaderLines,540+ header: header,541+ header0: header,542+ ansi: opts.Ansi,543+ tabstop: opts.Tabstop,544+ reading: true,545+ running: true,546+ failed: nil,547+ jumping: jumpDisabled,548+ jumpLabels: opts.JumpLabels,549+ printer: opts.Printer,550+ printsep: opts.PrintSep,551+ merger: EmptyMerger,552+ selected: make(map[int32]selectedItem),553+ reqBox: util.NewEventBox(),554+ initialPreviewOpts: opts.Preview,555+ previewOpts: opts.Preview,556+ previewer: previewer{0, []string{}, 0, showPreviewWindow, false, true, false, ""},557+ previewed: previewed{0, 0, 0, false},558+ previewBox: previewBox,559+ eventBox: eventBox,560+ mutex: sync.Mutex{},561+ suppress: true,562+ sigstop: false,563+ slab: util.MakeSlab(slab16Size, slab32Size),564+ theme: opts.Theme,565+ startChan: make(chan bool, 1),566+ killChan: make(chan int),567+ tui: renderer,568+ initFunc: func() { renderer.Init() },569+ executing: util.NewAtomicBool(false)}570 t.prompt, t.promptLen = t.parsePrompt(opts.Prompt)571 t.pointer, t.pointerLen = t.processTabs([]rune(opts.Pointer), 0)572 t.marker, t.markerLen = t.processTabs([]rune(opts.Marker), 0)573 // Pre-calculated empty pointer and marker signs1072 unmodified lines1646 return replacePlaceholder(1647 template, t.ansi, t.delimiter, t.printsep, forcePlus, input, list)1648 }1649 1645-func (t *Terminal) evaluateScrollOffset(list []*Item, height int) int {1650+func (t *Terminal) evaluateScrollOffset() int {1651+ if t.pwindow == nil {1652+ return 01653+ }1654+1655+ // We only need the current item to calculate the scroll offset1656 offsetExpr := offsetTrimCharsRegex.ReplaceAllString(1647- t.replacePlaceholder(t.previewOpts.scroll, false, "", list), "")1657+ t.replacePlaceholder(t.previewOpts.scroll, false, "", []*Item{t.currentItem(), nil}), "")1658 1659 atoi := func(s string) int {1660 n, e := strconv.Atoi(s)1661 if e != nil {2 unmodified lines1664 return n1665 }1666 1667 base := -11668+ height := util.Max(0, t.pwindow.Height()-t.previewOpts.headerLines)1669 for _, component := range offsetComponentRegex.FindAllString(offsetExpr, -1) {1670 if strings.HasPrefix(component, "-/") {1671 component = component[1:]1672 }1673 if component[0] == '/' {1674 denom := atoi(component[1:])1664- if denom == 0 {1665- return base1675+ if denom != 0 {1676+ base -= height / denom1677 }1667- return base - height/denom1678+ break1679 }1680 base += atoi(component)1681 }1671- return base1682+ return util.Max(0, base)1683 }1684 1685 func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems []*Item) string {1686 current := allItems[:1]295 unmodified lines1982 for {1983 var items []*Item1984 var commandTemplate string1985 var pwindow tui.Window1986+ initialOffset := 01987 t.previewBox.Wait(func(events *util.Events) {1988 for req, value := range *events {1989 switch req {1990 case reqPreviewEnqueue:1991 request := value.(previewRequest)1992 commandTemplate = request.template1993+ initialOffset = request.scrollOffset1994 items = request.list1995 pwindow = request.pwindow1996 }1997 }3 unmodified lines2001 // We don't display preview window if no match2002 if items[0] != nil {2003 _, query := t.Input()2004 command := t.replacePlaceholder(commandTemplate, false, string(query), items)1992- initialOffset := 02005 cmd := util.ExecCommand(command, true)2006 if pwindow != nil {2007 height := pwindow.Height()1996- initialOffset = util.Max(0, t.evaluateScrollOffset(items, util.Max(0, height-t.previewOpts.headerLines)))2008 env := os.Environ()2009 lines := fmt.Sprintf("LINES=%d", height)2010 columns := fmt.Sprintf("COLUMNS=%d", pwindow.Width())2011 env = append(env, lines)126 unmodified lines2138 refreshPreview := func(command string) {2139 if len(command) > 0 && t.isPreviewEnabled() {2140 _, list := t.buildPlusList(command, false)2141 t.cancelPreview()2131- t.previewBox.Set(reqPreviewEnqueue, previewRequest{command, t.pwindow, list})2142+ t.previewBox.Set(reqPreviewEnqueue, previewRequest{command, t.pwindow, t.evaluateScrollOffset(), list})2143 }2144 }2145 2146 go func() {116 unmodified lines2263 looping = false2264 }2265 }2266 }2256- togglePreview := func(enabled bool) {2267+ togglePreview := func(enabled bool) bool {2268 if t.previewer.enabled != enabled {2269 t.previewer.enabled = enabled2270+ // We need to immediately update t.pwindow so we don't use reqRedraw2271 t.tui.Clear()2272 t.resizeWindows()2273 req(reqPrompt, reqList, reqInfo, reqHeader)2274+ return true2275 }2276+ return false2277 }2278 toggle := func() bool {2279 current := t.currentItem()2280 if current != nil && t.toggleItem(current) {59 unmodified lines2340 valid, list := t.buildPlusList(t.previewOpts.command, false)2341 if valid {2342 t.cancelPreview()2343 t.previewBox.Set(reqPreviewEnqueue,2330- previewRequest{t.previewOpts.command, t.pwindow, list})2344+ previewRequest{t.previewOpts.command, t.pwindow, t.evaluateScrollOffset(), list})2345 }2346 }2347 }2348 case actTogglePreviewWrap:371 unmodified lines2720 keys := parseKeyChords(a.a, "PANIC")2721 for key := range keys {2722 delete(t.keymap, key)2723 }2724+ case actChangePreview:2725+ if t.previewOpts.command != a.a {2726+ togglePreview(len(a.a) > 0)2727+ t.previewOpts.command = a.a2728+ refreshPreview(t.previewOpts.command)2729+ }2730+ case actChangePreviewWindow:2731+ currentPreviewOpts := t.previewOpts2732+2733+ // Reset preview options and apply the additional options2734+ t.previewOpts = t.initialPreviewOpts2735+ parsePreviewWindow(&t.previewOpts, a.a)2736+2737+ if t.previewOpts.hidden {2738+ togglePreview(false)2739+ } else {2740+ // Full redraw2741+ if !currentPreviewOpts.sameLayout(t.previewOpts) {2742+ if togglePreview(true) {2743+ refreshPreview(t.previewOpts.command)2744+ } else {2745+ req(reqRedraw)2746+ }2747+ } else if !currentPreviewOpts.sameContentLayout(t.previewOpts) {2748+ t.previewed.version = 02749+ req(reqPreviewRefresh)2750+ }2751+2752+ // Adjust scroll offset2753+ if t.hasPreviewWindow() && currentPreviewOpts.scroll != t.previewOpts.scroll {2754+ scrollPreviewTo(t.evaluateScrollOffset())2755+ }2756+ }2757 }2758 return true2759 }2760 119 unmodified linesmodified:test/test_go.rb+49 added
2140 unmodified lines2141 2142 assert_equal expected.chomp, lines.take(6).join("\n")2143 end2144 end2145+2146+ def test_change_preview_window2147+ tmux.send_keys "seq 1000 | #{FZF} --preview 'echo [[{}]]' --preview-window border-none --bind '" \2148+ 'a:change-preview(echo __{}__),' \2149+ 'b:change-preview-window(down)+change-preview(echo =={}==)+change-preview-window(up),' \2150+ 'c:change-preview(),d:change-preview-window(hidden),' \2151+ "e:preview(printf ::%${FZF_PREVIEW_COLUMNS}s{})+change-preview-window(up),f:change-preview-window(up,wrap)'", :Enter2152+ tmux.until { |lines| assert_equal 1000, lines.item_count }2153+ tmux.until { |lines| assert_includes lines[0], '[[1]]' }2154+2155+ # change-preview action permanently changes the preview command set by --preview2156+ tmux.send_keys 'a'2157+ tmux.until { |lines| assert_includes lines[0], '__1__' }2158+ tmux.send_keys :Up2159+ tmux.until { |lines| assert_includes lines[0], '__2__' }2160+2161+ # When multiple change-preview-window actions are bound to a single key,2162+ # the last one wins and the updated options are immediately applied to the new preview2163+ tmux.send_keys 'b'2164+ tmux.until { |lines| assert_equal '==2==', lines[0] }2165+ tmux.send_keys :Up2166+ tmux.until { |lines| assert_equal '==3==', lines[0] }2167+2168+ # change-preview with an empty preview command closes the preview window2169+ tmux.send_keys 'c'2170+ tmux.until { |lines| refute_includes lines[0], '==' }2171+2172+ # change-preview again to re-open the preview window2173+ tmux.send_keys 'a'2174+ tmux.until { |lines| assert_equal '__3__', lines[0] }2175+2176+ # Hide the preview window with hidden flag2177+ tmux.send_keys 'd'2178+ tmux.until { |lines| refute_includes lines[0], '__3__' }2179+2180+ # One-off preview2181+ tmux.send_keys 'e'2182+ tmux.until do |lines|2183+ assert_equal '::', lines[0]2184+ refute_includes lines[1], '3'2185+ end2186+2187+ # Wrapped2188+ tmux.send_keys 'f'2189+ tmux.until do |lines|2190+ assert_equal '::', lines[0]2191+ assert_equal ' 3', lines[1]2192+ end2193+ end2194 end2195 2196 module TestShell2197 def setup478 unmodified linesmodified:CHANGELOG.md+7 added
1 CHANGELOG2 =========3 4+0.29.05+------6+- Added `change-preview(...)` action to change the `--preview` command7+ - cf. `preview(...)` is a one-off action that doesn't change the default8+ preview command9+- Added `change-preview-window(...)` action10+11 0.28.012 ------13 - Added `--header-first` option to print header before the prompt line14 ```sh1186 unmodified lines