Skip to content
Myr

Use floating pane instead of popup on tmux 3.7 or above (#4850) (#4852)

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

Unlike a popup, a floating pane is not modal; you can switch to other panes and windows while fzf is running, move and resize the pane with the mouse, zoom it to fullscreen, and use copy-mode in it. - Floating pane always has a native border, so 'border-native' is implied; give new 'border-fzf' option to fall back to a popup where fzf draws its own border - Popup is also used on tmux versions below 3.7, or when the window is too small to fit a floating pane - new-pane does not block until the command finishes and does not propagate the exit status; block on a wait-for channel signaled by the pane and pass the exit status through a temporary file - Watchdog process signals the channel when the pane is closed abnormally (e.g. kill-pane) - Kill the pane when the proxy process is interrupted, like a popup dying with its client - Unzoom the window before creating the floating pane; doing so over a zoomed window crashes the tmux server on 3.7b, and newer versions of tmux unzoom the window anyway - Floating pane size excludes the border and the position is that of the content area; treat the requested size as the total footprint including the border for consistency with popups - Close the pane on exit even when remain-on-exit is on - Pre-create the exit status file with O_EXCL to prevent tampering on a shared TMPDIR

authored by Junegunn Choi · committed by GitHub · parent a1fb014 · Browse files · 7 files+240 added−14 removed
This commit

State

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

Diff stats

7 files+240 added−14 removed

  • tests:+64 added−0 removed
  • other:+176 added−14 removed

7 files+240 added−14 removed

modified:man/man1/fzf.1+11 added-3 removed
415 unmodified lines
416layout options so that the specified number of items are visible in the list417section (default: \fB10+\fR).418Ignored when \fB\-\-height\fR is not specified or set as an absolute value.419.TP420.BI "\-\-popup" "[=[center|top|bottom|left|right][,SIZE[%]][,SIZE[%]][,border-native]]"421Start fzf in a tmux popup or in a Zellij floating pane (default422\fBcenter,50%\fR). Requires tmux 3.3+ or Zellij 0.44+. This option is ignored if you420.BI "\-\-popup" "[=[center|top|bottom|left|right][,SIZE[%]][,SIZE[%]][,border-native|border-fzf]]"421Start fzf in a tmux or Zellij floating pane (default \fBcenter,50%\fR).422Requires tmux 3.3+ or Zellij 0.44+. This option is ignored if you423are not running fzf inside tmux or Zellij. \fB\-\-tmux\fR is an alias for this option.424425On tmux 3.7 or above, the floating pane is not modal; you can switch to426other panes and windows while fzf is running, move and resize the pane with427the mouse, zoom it to fullscreen, and use copy\-mode in it. The pane always428has a native border, which is what makes it movable and resizable, so429\fBborder\-native\fR is implied. On tmux versions below 3.7, or when430\fBborder\-fzf\fR is given, a modal tmux popup is used instead and fzf draws431its own border.432433e.g.434 \fB# Popup in the center with 70% width and height435 fzf \-\-popup 70%436
1968 unmodified lines
modified:src/options.go+19 added-7 removed
73 unmodified lines
74 according to the input size.75 --min-height=HEIGHT[+] Minimum height when --height is given as a percentage.76 Add '+' to automatically increase the value77 according to the other layout options (default: 10+).78 --popup[=OPTS] Start fzf in a popup window (requires tmux 3.3+ or Zellij 0.44+)78 --popup[=OPTS] Start fzf in a floating pane (requires tmux 3.3+ or Zellij 0.44+)79 [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]]80 [,border-native] (default: center,50%)80 [,border-native|border-fzf] (default: center,50%)81 --tmux[=OPTS] Alias for --popup8283 LAYOUT84 --layout=LAYOUT Choose layout: [default|reverse|reverse-list]
249 unmodified lines
334 posCenter335 posNext // adjacent to the input section, on the list side336)337338type tmuxBorder int339340const (341 tmuxBorderAuto tmuxBorder = iota342 tmuxBorderNative343 tmuxBorderFzf344)345346type tmuxOptions struct {347 width sizeSpec348 height sizeSpec349 position windowPosition350 index int343 border bool351 border tmuxBorder352}353354type layoutType int355
78 unmodified lines
434func parseTmuxOptions(arg string, index int) (*tmuxOptions, error) {435 var err error436 opts := defaultTmuxOptions(index)437 tokens := splitRegexp.Split(arg, -1)430 errorToReturn := errors.New("invalid popup option: " + arg + " (expected: [center|top|bottom|left|right][,SIZE[%]][,SIZE[%][,border-native]])")438 errorToReturn := errors.New("invalid popup option: " + arg + " (expected: [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]][,border-native|border-fzf])")439 if len(tokens) == 0 || len(tokens) > 4 {440 return nil, errorToReturn441 }442443 for i, token := range tokens {436 if token == "border-native" {437 tokens = append(tokens[:i], tokens[i+1:]...) // cut the 'border-native' option438 opts.border = true444 if token == "border-native" || token == "border-fzf" {445 tokens = append(tokens[:i], tokens[i+1:]...) // cut the border option446 if token == "border-native" {447 opts.border = tmuxBorderNative448 } else {449 opts.border = tmuxBorderFzf450 }451 break452 }453 }454
3552 unmodified lines
modified:src/proxy.go+2 added-2 removed
24 unmodified lines
2526func popupArgStr(args []string, opts *Options) (string, string) {27 fzf, rest := args[0], args[1:]28 args = []string{"--bind=ctrl-z:ignore"}29 if !opts.Tmux.border && (opts.BorderShape == tui.BorderUndefined || opts.BorderShape == tui.BorderLine) {29 if opts.Tmux.border != tmuxBorderNative && (opts.BorderShape == tui.BorderUndefined || opts.BorderShape == tui.BorderLine) {30 if tui.DefaultBorderShape == tui.BorderRounded {31 rest = append(rest, "--border=rounded")32 } else {33 rest = append(rest, "--border=sharp")34 }35 }36 if opts.Tmux.border && opts.Margin == defaultMargin() {36 if opts.Tmux.border == tmuxBorderNative && opts.Margin == defaultMargin() {37 args = append(args, "--margin=0,1")38 }39 argStr := escapeSingleQuote(fzf)40 for _, arg := range append(args, rest...) {
148 unmodified lines
modified:src/tmux.go+136 added-1 removed
1package fzf23import (4 "fmt"5 "os"6 "os/exec"7 "path/filepath"8 "strings"9)1011// Returns the size of the current window if the tmux server supports12// floating panes (tmux 3.7 or above)13func tmuxFloatingPaneInfo() (int, int, bool) {14 target := os.Getenv("TMUX_PANE")15 if target == "" {16 return 0, 0, false17 }18 // A single invocation for both checks. Cannot rely on the exit status;19 // tmux versions before 3.7 exit normally with empty output for an20 // unknown command name, so check the output instead.21 out, err := exec.Command("tmux", "display-message", "-p", "-t", target,22 "#{window_width} #{window_height}", ";", "list-commands", "new-pane").Output()23 if err != nil || !strings.Contains(string(out), "new-pane") {24 return 0, 0, false25 }26 var width, height int27 if _, err := fmt.Sscanf(string(out), "%d %d", &width, &height); err != nil {28 return 0, 0, false29 }30 // The window is too small to fit a floating pane of the minimum size31 if width < 3 || height < 3 {32 return 0, 0, false33 }34 return width, height, true35}3637// Convert sizeSpec to the number of cells, clamped between the minimum38// footprint of 3, including the border, and the window size39func tmuxDim(spec sizeSpec, window int) int {40 dim := int(spec.size)41 if spec.percent {42 dim = window * dim / 10043 }44 return max(3, min(dim, window))45}4647func runTmuxFloatingPane(argStr string, dir string, windowWidth int, windowHeight int, opts *Options) (int, error) {48 // Unlike display-popup, the size of a floating pane does not account for49 // the border around it, and the position is that of the content area. To50 // stay consistent with popups, treat the requested size as the total51 // footprint including the border.52 width := tmuxDim(opts.Tmux.width, windowWidth)53 height := tmuxDim(opts.Tmux.height, windowHeight)54 x := (windowWidth-width)/2 + 155 y := (windowHeight-height)/2 + 156 switch opts.Tmux.position {57 case posUp:58 y = 159 case posDown:60 y = windowHeight - height + 161 case posLeft:62 x = 163 case posRight:64 x = windowWidth - width + 165 }6667 return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {68 sh, err := sh(needBash)69 if err != nil {70 return nil, err71 }72 // Unlike display-popup, new-pane does not block until the command73 // finishes, and it does not propagate the exit status. So we block on74 // a wait-for channel that the pane signals on completion, and pass75 // the exit status through a temporary file. A watchdog process76 // signals the same channel if the pane is closed abnormally77 // (e.g. kill-pane), in which case the file is not written.78 //79 // has-session is the liveness check because it fails when the target80 // pane is gone, while display-message succeeds even for a dead pane.81 signal := escapeSingleQuote("fzf-" + filepath.Base(temp))8283 // Pre-create the exit status file so that another user on a shared84 // TMPDIR cannot plant a file or a symbolic link at the predictable85 // path while the pane is running86 codeFile := temp + ".code"87 f, err := os.OpenFile(codeFile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)88 if err != nil {89 return nil, err90 }91 f.Close()92 code := escapeSingleQuote(codeFile)93 paneCmd := fmt.Sprintf("%s %s; echo $? > %s; tmux wait-for -S %s",94 escapeSingleQuote(sh), escapeSingleQuote(temp), code, signal)95 // Unzoom the window first; creating a floating pane over a zoomed96 // window crashes the tmux server on 3.7b, and newer versions of97 // tmux unzoom the window anyway. The pane should always close on98 // exit like a popup, even when remain-on-exit is on. set-option99 // targets the new pane as new-pane makes it the current pane.100 target := os.Getenv("TMUX_PANE")101 newPane := fmt.Sprintf(102 "tmux if -F -t %s '#{window_zoomed_flag}' %s ';' new-pane -P -F '#{pane_id}' -t %s -c %s -x %d -y %d -X %d -Y %d %s -c %s ';' set-option -p remain-on-exit off",103 escapeSingleQuote(target), escapeSingleQuote("resize-pane -Z -t "+target),104 escapeSingleQuote(target), escapeSingleQuote(dir), width-2, height-2, x, y,105 escapeSingleQuote(sh), escapeSingleQuote(paneCmd))106 // The pane is killed when the proxy process is interrupted or hung up,107 // like a popup dying with its client. wait-for runs in the background108 // and is awaited with the interruptible wait builtin so that the trap109 // can fire while blocked. The trap is installed before creating the110 // pane; a signal received during creation is deferred until the111 // command substitution completes, and the pane is killed right after.112 // An interrupted wait does not reap the waiter, so it is killed113 // along with the watchdog.114 script := fmt.Sprintf(`trap '[ -n "$id" ] && tmux kill-pane -t "$id" 2> /dev/null' INT TERM HUP115id=$(%s) || { status=$?; rm -f %s; exit "$status"; }116{ while tmux has-session -t "$id" 2> /dev/null; do sleep 1; done; tmux wait-for -S %s; } &117watchdog=$!118tmux wait-for %s &119waiter=$!120wait "$waiter"121kill "$watchdog" "$waiter" 2> /dev/null122wait 2> /dev/null123if [ -s %s ]; then code=$(cat %s); else code=130; fi124rm -f %s125exit "$code"`, newPane, code, signal, signal, code, code, code)126 return exec.Command(sh, "-c", script), nil127 }, opts, true)128}129130func runTmux(args []string, opts *Options) (int, error) {131 // On tmux 3.7 or above, fzf runs in a floating pane instead of a popup.132 // A floating pane always has a native border, so 'border-native' is133 // implied. Give 'border-fzf' to fall back to a popup where fzf draws134 // its own border.135 if opts.Tmux.border != tmuxBorderFzf {136 if windowWidth, windowHeight, ok := tmuxFloatingPaneInfo(); ok {137 opts.Tmux.border = tmuxBorderNative138 argStr, dir := popupArgStr(args, opts)139 return runTmuxFloatingPane(argStr, dir, windowWidth, windowHeight, opts)140 }141 }142143 argStr, dir := popupArgStr(args, opts)144145 // Set tmux options for popup placement146 // C Both The centre of the terminal
2 unmodified lines
149 // M Both The mouse position150 // W Both The window position on the status line151 // S -y The line above or below the status line152 tmuxArgs := []string{"display-popup", "-E", "-d", dir}18 if !opts.Tmux.border {153 if opts.Tmux.border != tmuxBorderNative {154 tmuxArgs = append(tmuxArgs, "-B")155 }156 switch opts.Tmux.position {157 case posUp:
22 unmodified lines
modified:src/zellij.go+1 added-1 removed
9 unmodified lines
10 zellijArgs := []string{11 "run", "--floating", "--close-on-exit", "--block-until-exit",12 "--cwd", dir,13 }14 if !opts.Tmux.border {14 if opts.Tmux.border != tmuxBorderNative {15 zellijArgs = append(zellijArgs, "--borderless", "true")16 }17 switch opts.Tmux.position {18 case posUp:
23 unmodified lines
added:test/test_tmux.rb+64 added
1# frozen_string_literal: true23require 'shellwords'4require 'tmpdir'5require_relative 'lib/common'67# Tests for running fzf in a tmux floating pane (--popup on tmux 3.7 or above)8class TestTmux < TestInteractive9 def setup10 super11 # Cannot rely on the exit status; tmux versions before 3.7 exit12 # normally with empty output for an unknown command name13 supported = IO.popen(%w[tmux list-commands new-pane], err: File::NULL, &:read).include?('new-pane')14 skip('floating panes not supported') unless supported15 end1617 def test_floating_pane18 tmux.send_keys "seq 100 | #{fzf('--popup center,80% --margin 0')}", :Enter19 tmux.until { |lines| assert_equal 100, lines.item_count }20 tmux.send_keys '99'21 tmux.until { |lines| assert_equal 1, lines.match_count }22 tmux.send_keys :Enter23 assert_equal '99', fzf_output24 end2526 def test_floating_pane_killed27 tmux.send_keys "seq 100 | #{FZF} --popup bottom,50% --margin 0; echo code:$?", :Enter28 tmux.until { |lines| assert_equal 100, lines.item_count }29 pane = floating_pane30 refute_nil pane31 assert system('tmux', 'kill-pane', '-t', pane)32 tmux.until { |lines| assert lines.any_include?('code:130') }33 end3435 def test_border_fzf_falls_back_to_popup36 # display-popup requires an attached client, which the test environment37 # may not have; intercept it with a tmux shim on PATH38 dir = Dir.mktmpdir39 real = `command -v tmux`.chomp40 shim = File.join(dir, 'tmux')41 File.write(shim, <<~SH)42 #!/bin/sh43 if [ "$1" = display-popup ]; then44 echo popup-used >&245 exit 046 fi47 exec #{real.shellescape} "$@"48 SH49 FileUtils.chmod(0o755, shim)50 tmux.send_keys "seq 100 | PATH=#{dir.shellescape}:$PATH #{FZF} --popup center,border-fzf", :Enter51 tmux.until { |lines| assert lines.any_include?('popup-used') }52 refute floating_pane53 ensure54 FileUtils.remove_entry(dir) if dir55 end5657 private5859 def floating_pane60 format = "\#{pane_id} \#{pane_floating_flag}"61 lines = IO.popen(['tmux', 'list-panes', '-t', tmux.win, '-F', format]) { |io| io.readlines(chomp: true) }62 lines.filter_map { |line| line.split.first if line.end_with?(' 1') }.first63 end64end
modified:CHANGELOG.md+7 added
1 unmodified line
2=========340.74.0 (WIP)5------------6- On tmux 3.7 or above, `--popup` starts fzf in a floating pane instead of a popup (#4850)7 - Unlike a popup, a floating pane is not modal; you can switch to other panes and windows while fzf is running, move and resize the pane with the mouse, zoom it to fullscreen, and use copy-mode in it8 - A floating pane always has a native border, which is what makes the pane movable and resizable, so `border-native` is implied9 - Give `border-fzf` to fall back to a popup where fzf draws its own border10 ```sh11 fzf --popup center,80%,border-fzf12 ```13- Added `result-final` event, a variant of `result` that is not triggered while the input stream is still open (#4835)14 - Use it for one-shot, per-query actions that would otherwise re-fire on every intermediate snapshot during loading15 ```sh16 # 'result' fires per intermediate snapshot (header keeps updating during load);
3336 unmodified lines