Skip to content
Myr

Add preview window option for setting the initial scroll offset

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

Close #1057 Close #2120 # Initial scroll offset is set to the line number of each line of # git grep output *minus* 5 lines git grep --line-number '' | fzf --delimiter : --preview 'nl {1}' --preview-window +{2}-5

authored by Junegunn Choi · committed by Junegunn Choi · parent c0a83b2 · Browse files · 5 files+97 added−17 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+97 added−17 removed

  • tests:+18 added−0 removed
  • other:+79 added−17 removed

5 files+97 added−17 removed

modified:man/man1/fzf.1+17 added-4 removed
19 unmodified lines
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22THE SOFTWARE.23..24.TH fzf 1 "Jun 2020" "fzf 0.22.0" "fzf - a command-line fuzzy finder"24.TH fzf 1 "Jul 2020" "fzf 0.22.0" "fzf - a command-line fuzzy finder"2526.SH NAME27fzf - a command-line fuzzy finder28
351 unmodified lines
380Preview window will be updated even when there is no match for the current381query if any of the placeholder expressions evaluates to a non-empty string.382.RE383.TP384.BI "--preview-window=" "[POSITION][:SIZE[%]][:noborder][:wrap][:hidden]"384.BI "--preview-window=" "[POSITION][:SIZE[%]][:noborder][:wrap][:hidden][:+SCROLL[-OFFSET]]"385Determines the layout of the preview window. If the argument contains386\fB:hidden\fR, the preview window will be hidden by default until387\fBtoggle-preview\fR action is triggered. Long lines are truncated by default.388Line wrap can be enabled with \fB:wrap\fR flag.389390If size is given as 0, preview window will not be visible, but fzf will still391execute the command in the background.392393\fB+SCROLL[-OFFSET]\fR determines the initial scroll offset of the preview394window. \fBSCROLL\fR can be either a numeric integer or a single-field index395expression that refers to a numeric integer. The optional \fB-OFFSET\fR part is396for adjusting the base offset so that you can see the text above it. It should397be given as a numeric integer.398399.RS400.B POSITION: (default: right)401 \fBup402 \fBdown
2 unmodified lines
405.RE406407.RS408e.g.409 \fB# Non-default scroll window positions and sizes403 \fBfzf --preview="head {}" --preview-window=up:30%404 fzf --preview="file {}" --preview-window=down:1\fR410 fzf --preview="head {}" --preview-window=up:30%411 fzf --preview="file {}" --preview-window=down:1412413 # Initial scroll offset is set to the line number of each line of414 # git grep output *minus* 5 lines415 git grep --line-number '' |416 fzf --delimiter : --preview 'nl {1}' --preview-window +{2}-5\fR417418.RE419.SS Scripting420.TP421.BI "-q, --query=" "STR"
414 unmodified lines
modified:src/options.go+8 added-4 removed
78 unmodified lines
7980 Preview81 --preview=COMMAND Command to preview highlighted line ({})82 --preview-window=OPT Preview window layout (default: right:50%)83 [up|down|left|right][:SIZE[%]][:wrap][:hidden]83 [up|down|left|right][:SIZE[%]][:wrap][:hidden][:+SCROLL[-OFFSET]]8485 Scripting86 -q, --query=STR Start the finder with the given query87 -1, --select-1 Automatically select the only match
70 unmodified lines
158type previewOpts struct {159 command string160 position windowPosition161 size sizeSpec162 scroll string163 hidden bool164 wrap bool165 border bool166}
93 unmodified lines
260 Filter: nil,261 ToggleSort: false,262 Expect: make(map[int]string),263 Keymap: make(map[int][]action),263 Preview: previewOpts{"", posRight, sizeSpec{50, true}, false, false, true},264 Preview: previewOpts{"", posRight, sizeSpec{50, true}, "", false, false, true},265 PrintQuery: false,266 ReadZero: false,267 Printer: func(str string) { fmt.Println(str) },268 PrintSep: "\n",
725 unmodified lines
994 opts.wrap = false995996 tokens := strings.Split(input, ":")997 sizeRegex := regexp.MustCompile("^[0-9]+%?$")998 offsetRegex := regexp.MustCompile("^\\+([0-9]+|{[0-9]+})(-[0-9]+)?$")999 for _, token := range tokens {1000 switch token {1001 case "":1002 case "hidden":
14 unmodified lines
1017 opts.border = false1018 default:1019 if sizeRegex.MatchString(token) {1020 opts.size = parseSize(token, 99, "window size")1021 } else if offsetRegex.MatchString(token) {1022 opts.scroll = token[1:]1023 } else {1020 errorExit("invalid preview window layout: " + input)1024 errorExit("invalid preview window option: " + token)1025 }1026 }1027 }1028 if !opts.size.percent && opts.size.size > 0 {
244 unmodified lines
1273 case "--no-preview":1274 opts.Preview.command = ""1275 case "--preview-window":1276 parsePreviewWindow(&opts.Preview,1273 nextString(allArgs, &i, "preview window layout required: [up|down|left|right][:SIZE[%]][:noborder][:wrap][:hidden]"))1277 nextString(allArgs, &i, "preview window layout required: [up|down|left|right][:SIZE[%]][:noborder][:wrap][:hidden][:+SCROLL[-OFFSET]]"))1278 case "--height":1279 opts.Height = parseHeight(nextString(allArgs, &i, "height required: HEIGHT[%]"))1280 case "--min-height":1281 opts.MinHeight = nextInt(allArgs, &i, "height required: HEIGHT")
206 unmodified lines
modified:src/terminal.go+47 added-9 removed
260 unmodified lines
261 template string262 list []*Item263}264265type previewResult struct {266 content string267 offset int268}269270func toActions(types ...actionType) []action {271 actions := make([]action, len(types))272 for idx, t := range types {273 actions[idx] = action{t: t, a: ""}
1077 unmodified lines
1351 }1352 activeTempFiles = []string{}1353}13541355func (t *Terminal) replacePlaceholder(template string, forcePlus bool, input string, list []*Item) string {1356 return replacePlaceholder(1357 template, t.ansi, t.delimiter, t.printsep, forcePlus, input, list)1358}13591360// Ascii to positive integer1361func atopi(s string) int {1362 n, e := strconv.Atoi(strings.ReplaceAll(s, "'", ""))1363 if e != nil || n < 1 {1364 return 01365 }1366 return n1367}13681369func (t *Terminal) evaluateScrollOffset(list []*Item) int {1370 offsetExpr := t.replacePlaceholder(t.preview.scroll, false, "", list)1371 nums := strings.Split(offsetExpr, "-")1372 switch len(nums) {1373 case 0:1374 return 01375 case 1, 2:1376 base := atopi(nums[0])1377 if base == 0 {1378 return 01379 } else if len(nums) == 1 {1380 return base - 11381 }1382 return base - atopi(nums[1]) - 11383 default:1384 return 01385 }1386}13871388func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems []*Item) string {1389 current := allItems[:1]1390 selected := allItems[1:]1391 if current[0] == nil {
90 unmodified lines
1482 valid, list := t.buildPlusList(template, forcePlus)1483 if !valid {1484 return1485 }1448 command := replacePlaceholder(template, t.ansi, t.delimiter, t.printsep, forcePlus, string(t.input), list)1486 command := t.replacePlaceholder(template, forcePlus, string(t.input), list)1487 cmd := util.ExecCommand(command, false)1488 if !background {1489 cmd.Stdin = os.Stdin1490 cmd.Stdout = os.Stdout
175 unmodified lines
1666 events.Clear()1667 })1668 // We don't display preview window if no match1669 if items[0] != nil {1632 command := replacePlaceholder(commandTemplate,1633 t.ansi, t.delimiter, t.printsep, false, string(t.Input()), items)1670 command := t.replacePlaceholder(commandTemplate, false, string(t.Input()), items)1671 offset := t.evaluateScrollOffset(items)1672 cmd := util.ExecCommand(command, true)1673 if t.pwindow != nil {1674 env := os.Environ()1675 lines := fmt.Sprintf("LINES=%d", t.pwindow.Height())
34 unmodified lines
1710 }()1711 cmd.Wait()1712 finishChan <- true1713 if out.Len() > 0 || !<-updateChan {1676 t.reqBox.Set(reqPreviewDisplay, out.String())1714 t.reqBox.Set(reqPreviewDisplay, previewResult{out.String(), offset})1715 }1716 cleanTemporaryFiles()1717 } else {1680 t.reqBox.Set(reqPreviewDisplay, "")1718 t.reqBox.Set(reqPreviewDisplay, previewResult{"", 0})1719 }1720 }1721 }()1722 }
65 unmodified lines
1788 }1789 return exitNoMatch1790 })1791 case reqPreviewDisplay:1792 result := value.(previewResult)1754 t.previewer.text = value.(string)1793 t.previewer.text = result.content1794 t.previewer.lines = strings.Count(t.previewer.text, "\n")1756 t.previewer.offset = 01795 t.previewer.offset = util.Constrain(result.offset, 0, t.previewer.lines-1)1796 t.printPreview()1797 case reqPreviewRefresh:1798 t.printPreview()1799 case reqPrintQuery:
410 unmodified lines
2210 slot, _, query := hasPreviewFlags(a.a)2211 valid = !slot || query2212 }2213 if valid {2175 command := replacePlaceholder(a.a,2176 t.ansi, t.delimiter, t.printsep, false, string(t.input), list)2214 command := t.replacePlaceholder(a.a, false, string(t.input), list)2215 newCommand = &command2216 }2217 }2218 return true
110 unmodified lines
modified:test/test_go.rb+18 added
1785 unmodified lines
1786 tmux.until { |lines| lines.match_count == 1 }1787 tmux.until { |lines| refute_includes lines[1], '2' }1788 tmux.until { |lines| assert_includes lines[1], '[111]' }1789 end17901791 def test_preview_scroll_begin_constant1792 tmux.send_keys "echo foo 123 321 | #{FZF} --preview 'seq 1000' --preview-window left:+123", :Enter1793 tmux.until { |lines| lines.item_count == 1 }1794 tmux.until { |lines| assert_match %r{123.*123/1000}, lines[1] }1795 end17961797 def test_preview_scroll_begin_expr1798 tmux.send_keys "echo foo 123 321 | #{FZF} --preview 'seq 1000' --preview-window left:+{3}", :Enter1799 tmux.until { |lines| lines.item_count == 1 }1800 tmux.until { |lines| assert_match %r{321.*321/1000}, lines[1] }1801 end18021803 def test_preview_scroll_begin_and_offset1804 tmux.send_keys "echo foo 123 321 | #{FZF} --preview 'seq 1000' --preview-window left:+{2}-2", :Enter1805 tmux.until { |lines| lines.item_count == 1 }1806 tmux.until { |lines| assert_match %r{121.*121/1000}, lines[1] }1807 end1808end18091810module TestShell1811 def setup
475 unmodified lines
modified:CHANGELOG.md+7 added
24 unmodified lines
2526 # Preview window hidden by default, it appears when you first hit '?'27 fzf --bind '?:preview:cat {}' --preview-window hidden28 ```29- Added preview window option for setting the initial scroll offset30 ```sh31 # Initial scroll offset is set to the line number of each line of32 # git grep output *minus* 5 lines33 git grep --line-number '' |34 fzf --delimiter : --preview 'nl {1}' --preview-window +{2}-535 ```36- Added support for ANSI colors in `--prompt` string37- Vim plugin38 - `tmux` layout option for using fzf-tmux39 ```vim
870 unmodified lines