| 1 |
package fzf |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"os" |
| 6 |
"os/exec" |
| 7 |
"path/filepath" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"github.com/junegunn/fzf/src/tui" |
| 11 |
) |
| 12 |
|
| 13 |
// Returns the size of the current window if the tmux server supports |
| 14 |
// floating panes (tmux 3.7 or above) |
| 15 |
func tmuxFloatingPaneInfo() (int, int, bool) { |
| 16 |
// TMUX_PANE is not set when fzf is not started from within a pane |
| 17 |
// (e.g. 'bind-key 0 run-shell "fzf --popup"'). Do not use a floating |
| 18 |
// pane there; a blocking run-shell suspends key processing for the |
| 19 |
// client until the command exits, so fzf in a floating pane would |
| 20 |
// never receive a key and the client would appear frozen until the |
| 21 |
// process is killed externally. A popup is unaffected; its input is |
| 22 |
// handled at the client overlay level, bypassing the suspended path. |
| 23 |
// The right approach for such bindings is 'run-shell -b', which does |
| 24 |
// not suspend key processing, as discussed in: |
| 25 |
// https://github.com/tmux/tmux/issues/5384 |
| 26 |
target := os.Getenv("TMUX_PANE") |
| 27 |
if target == "" { |
| 28 |
return 0, 0, false |
| 29 |
} |
| 30 |
// A single invocation for both checks. Cannot rely on the exit status; |
| 31 |
// tmux versions before 3.7 exit normally with empty output for an |
| 32 |
// unknown command name, so check the output instead. |
| 33 |
out, err := exec.Command("tmux", "display-message", "-p", "-t", target, |
| 34 |
"#{window_width} #{window_height}", ";", "list-commands", "new-pane").Output() |
| 35 |
if err != nil || !strings.Contains(string(out), "new-pane") { |
| 36 |
return 0, 0, false |
| 37 |
} |
| 38 |
var width, height int |
| 39 |
if _, err := fmt.Sscanf(string(out), "%d %d", &width, &height); err != nil { |
| 40 |
return 0, 0, false |
| 41 |
} |
| 42 |
// The window is too small to fit a floating pane of the minimum size |
| 43 |
if width < 3 || height < 3 { |
| 44 |
return 0, 0, false |
| 45 |
} |
| 46 |
return width, height, true |
| 47 |
} |
| 48 |
|
| 49 |
// tmux ends a command at an argument ending in ';', so a trailing one is |
| 50 |
// escaped. Elsewhere it is not special |
| 51 |
func escapeTmuxSeparator(str string) string { |
| 52 |
if strings.HasSuffix(str, ";") { |
| 53 |
return str[:len(str)-1] + `\;` |
| 54 |
} |
| 55 |
return str |
| 56 |
} |
| 57 |
|
| 58 |
// '#[...]' is still processed when a substituted value is drawn, so '#' is |
| 59 |
// doubled. '#{...}' is already literal |
| 60 |
func escapeTmuxFormat(str string) string { |
| 61 |
return escapeTmuxSeparator(strings.ReplaceAll(str, "#", "##")) |
| 62 |
} |
| 63 |
|
| 64 |
// The option pane-border-format reads back, and the pane it is set on |
| 65 |
const ( |
| 66 |
tmuxBorderLabelOption = "@fzf-border-label" |
| 67 |
tmuxBorderLabelEnv = internalEnvPrefix + "TMUX_LABEL_PANE" |
| 68 |
) |
| 69 |
|
| 70 |
// Errors are ignored. The pane may be gone |
| 71 |
func setTmuxBorderLabel(pane string, label string) { |
| 72 |
// Strip ANSI sequences. tmux would draw the escape's remainder as text |
| 73 |
label, _, _ = extractColor(label, nil, nil) |
| 74 |
exec.Command("tmux", "set-option", "-p", "-t", pane, |
| 75 |
tmuxBorderLabelOption, escapeTmuxFormat(label)).Run() |
| 76 |
} |
| 77 |
|
| 78 |
// Convert sizeSpec to the number of cells, clamped between the minimum |
| 79 |
// footprint of 3, including the border, and the window size |
| 80 |
func tmuxDim(spec sizeSpec, window int) int { |
| 81 |
dim := int(spec.size) |
| 82 |
if spec.percent { |
| 83 |
dim = window * dim / 100 |
| 84 |
} |
| 85 |
return max(3, min(dim, window)) |
| 86 |
} |
| 87 |
|
| 88 |
func runTmuxFloatingPane(argStr string, dir string, windowWidth int, windowHeight int, opts *Options) (int, error) { |
| 89 |
// Unlike display-popup, the size of a floating pane does not account for |
| 90 |
// the border around it, and the position is that of the content area. To |
| 91 |
// stay consistent with popups, treat the requested size as the total |
| 92 |
// footprint including the border. |
| 93 |
width := tmuxDim(opts.Tmux.width, windowWidth) |
| 94 |
height := tmuxDim(opts.Tmux.height, windowHeight) |
| 95 |
x := (windowWidth-width)/2 + 1 |
| 96 |
y := (windowHeight-height)/2 + 1 |
| 97 |
switch opts.Tmux.position { |
| 98 |
case posUp: |
| 99 |
y = 1 |
| 100 |
case posDown: |
| 101 |
y = windowHeight - height + 1 |
| 102 |
case posLeft: |
| 103 |
x = 1 |
| 104 |
case posRight: |
| 105 |
x = windowWidth - width + 1 |
| 106 |
} |
| 107 |
|
| 108 |
return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) { |
| 109 |
sh, err := sh(needBash) |
| 110 |
if err != nil { |
| 111 |
return nil, err |
| 112 |
} |
| 113 |
// Unlike display-popup, new-pane does not block until the command |
| 114 |
// finishes, and it does not propagate the exit status. So we block on |
| 115 |
// a wait-for channel that the pane signals on completion, and pass |
| 116 |
// the exit status through a temporary file. A watchdog process |
| 117 |
// signals the same channel if the pane is closed abnormally |
| 118 |
// (e.g. kill-pane), in which case the file is not written. |
| 119 |
// |
| 120 |
// has-session is the liveness check because it fails when the target |
| 121 |
// pane is gone, while display-message succeeds even for a dead pane. |
| 122 |
signal := escapeSingleQuote("fzf-" + filepath.Base(temp)) |
| 123 |
|
| 124 |
// Pre-create the exit status file so that another user on a shared |
| 125 |
// TMPDIR cannot plant a file or a symbolic link at the predictable |
| 126 |
// path while the pane is running |
| 127 |
codeFile := temp + ".code" |
| 128 |
f, err := os.OpenFile(codeFile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) |
| 129 |
if err != nil { |
| 130 |
return nil, err |
| 131 |
} |
| 132 |
f.Close() |
| 133 |
code := escapeSingleQuote(codeFile) |
| 134 |
|
| 135 |
// Pane options are set by the pane itself before running fzf, so |
| 136 |
// that they are in place no matter how quickly the command exits. |
| 137 |
// The target must be explicit; without it, the commands would |
| 138 |
// resolve to the active pane of the session's current window, |
| 139 |
// which is not necessarily the pane running them. |
| 140 |
// |
| 141 |
// The pane should always close on exit like a popup, even when |
| 142 |
// remain-on-exit is on. |
| 143 |
setup := `tmux set-option -p -t "$TMUX_PANE" remain-on-exit off 2> /dev/null; ` |
| 144 |
|
| 145 |
// --border-label lives in a pane-scoped user option that |
| 146 |
// pane-border-format reads back, so a program in the pane cannot |
| 147 |
// replace it by setting the title. Set even when empty, so |
| 148 |
// change-border-label can fill it in and the default pane status is |
| 149 |
// not shown. pane-border-status is a window option until the next |
| 150 |
// tmux release, so it is left alone. |
| 151 |
// https://github.com/tmux/tmux/commit/7a18fa281db3 |
| 152 |
// --border-label-pos is ignored. With an explicit --border fzf draws |
| 153 |
// the label itself, but the native border cannot be removed. |
| 154 |
ownsLabel := noBorderSpecified(opts) |
| 155 |
label := "" |
| 156 |
if ownsLabel { |
| 157 |
// Strip ANSI sequences fzf would otherwise render itself |
| 158 |
label, _, _ = extractColor(opts.BorderLabel.label, nil, nil) |
| 159 |
} |
| 160 |
setup += fmt.Sprintf(`tmux set-option -p -t "$TMUX_PANE" %s %s 2> /dev/null; `, |
| 161 |
tmuxBorderLabelOption, escapeSingleQuote(escapeTmuxFormat(label))) |
| 162 |
setup += fmt.Sprintf(`tmux set-option -p -t "$TMUX_PANE" pane-border-format %s 2> /dev/null; `, |
| 163 |
escapeSingleQuote("#{"+tmuxBorderLabelOption+"}")) |
| 164 |
if ownsLabel { |
| 165 |
setup += fmt.Sprintf(`export %s="$TMUX_PANE"; `, tmuxBorderLabelEnv) |
| 166 |
} |
| 167 |
paneCmd := fmt.Sprintf("%s%s %s; echo $? > %s; tmux wait-for -S %s", |
| 168 |
setup, escapeSingleQuote(sh), escapeSingleQuote(temp), code, signal) |
| 169 |
// Unzoom the window first; creating a floating pane over a zoomed |
| 170 |
// window crashes the tmux server on 3.7b, and newer versions of |
| 171 |
// tmux unzoom the window anyway. |
| 172 |
target := os.Getenv("TMUX_PANE") |
| 173 |
newPane := fmt.Sprintf( |
| 174 |
"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", |
| 175 |
escapeSingleQuote(target), escapeSingleQuote("resize-pane -Z -t "+target), |
| 176 |
escapeSingleQuote(target), escapeSingleQuote(dir), width-2, height-2, x, y, |
| 177 |
escapeSingleQuote(sh), escapeSingleQuote(paneCmd)) |
| 178 |
|
| 179 |
// The pane is killed when the proxy process is interrupted or hung up, |
| 180 |
// like a popup dying with its client. wait-for runs in the background |
| 181 |
// and is awaited with the interruptible wait builtin so that the trap |
| 182 |
// can fire while blocked. The trap is installed before creating the |
| 183 |
// pane; a signal received during creation is deferred until the |
| 184 |
// command substitution completes, and the pane is killed right after. |
| 185 |
// An interrupted wait does not reap the waiter, so it is killed |
| 186 |
// along with the watchdog. |
| 187 |
script := fmt.Sprintf(`trap '[ -n "$id" ] && tmux kill-pane -t "$id" 2> /dev/null' INT TERM HUP |
| 188 |
id=$(%s) || { status=$?; rm -f %s; exit "$status"; } |
| 189 |
{ while tmux has-session -t "$id" 2> /dev/null; do sleep 1; done; tmux wait-for -S %s; } & |
| 190 |
watchdog=$! |
| 191 |
tmux wait-for %s & |
| 192 |
waiter=$! |
| 193 |
wait "$waiter" |
| 194 |
kill "$watchdog" "$waiter" 2> /dev/null |
| 195 |
wait 2> /dev/null |
| 196 |
if [ -s %s ]; then code=$(cat %s); else code=130; fi |
| 197 |
rm -f %s |
| 198 |
exit "$code"`, newPane, code, signal, signal, code, code, code) |
| 199 |
return exec.Command(sh, "-c", script), nil |
| 200 |
}, opts, true) |
| 201 |
} |
| 202 |
|
| 203 |
// Whether no box border was asked for. 'none' and 'line' count as none. |
| 204 |
// fzf draws no box for either |
| 205 |
func noBorderSpecified(opts *Options) bool { |
| 206 |
return opts.BorderShape == tui.BorderUndefined || |
| 207 |
opts.BorderShape == tui.BorderLine || opts.BorderShape == tui.BorderNone |
| 208 |
} |
| 209 |
|
| 210 |
// Whether to use the multiplexer's native border for the floating pane. Its |
| 211 |
// native border is the handle that makes the pane movable and resizable with |
| 212 |
// the mouse, so it is the default; 'border-native' forces it. It is not used |
| 213 |
// when a border style is explicitly specified with --border, so that the |
| 214 |
// fzf-drawn border is the only one shown. |
| 215 |
func nativeBorder(opts *Options) bool { |
| 216 |
return opts.Tmux.border || noBorderSpecified(opts) |
| 217 |
} |
| 218 |
|
| 219 |
func runTmux(args []string, opts *Options) (int, error) { |
| 220 |
// On tmux 3.7 or above, fzf runs in a floating pane instead of a popup. |
| 221 |
// When the native border is not used (an explicit --border style), a |
| 222 |
// popup is used instead so that the fzf-drawn border is the only border |
| 223 |
// shown; the native border of a tmux floating pane cannot be removed. |
| 224 |
if nativeBorder(opts) { |
| 225 |
if windowWidth, windowHeight, ok := tmuxFloatingPaneInfo(); ok { |
| 226 |
opts.Tmux.border = true |
| 227 |
argStr, dir := popupArgStr(args, opts) |
| 228 |
return runTmuxFloatingPane(argStr, dir, windowWidth, windowHeight, opts) |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
argStr, dir := popupArgStr(args, opts) |
| 233 |
|
| 234 |
// Set tmux options for popup placement |
| 235 |
// C Both The centre of the terminal |
| 236 |
// R -x The right side of the terminal |
| 237 |
// P Both The bottom left of the pane |
| 238 |
// M Both The mouse position |
| 239 |
// W Both The window position on the status line |
| 240 |
// S -y The line above or below the status line |
| 241 |
tmuxArgs := []string{"display-popup", "-E", "-d", dir} |
| 242 |
if !opts.Tmux.border { |
| 243 |
tmuxArgs = append(tmuxArgs, "-B") |
| 244 |
} |
| 245 |
switch opts.Tmux.position { |
| 246 |
case posUp: |
| 247 |
tmuxArgs = append(tmuxArgs, "-xC", "-y0") |
| 248 |
case posDown: |
| 249 |
tmuxArgs = append(tmuxArgs, "-xC", "-y9999") |
| 250 |
case posLeft: |
| 251 |
tmuxArgs = append(tmuxArgs, "-x0", "-yC") |
| 252 |
case posRight: |
| 253 |
tmuxArgs = append(tmuxArgs, "-xR", "-yC") |
| 254 |
case posCenter: |
| 255 |
tmuxArgs = append(tmuxArgs, "-xC", "-yC") |
| 256 |
} |
| 257 |
tmuxArgs = append(tmuxArgs, "-w"+opts.Tmux.width.String()) |
| 258 |
tmuxArgs = append(tmuxArgs, "-h"+opts.Tmux.height.String()) |
| 259 |
|
| 260 |
return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) { |
| 261 |
sh, err := sh(needBash) |
| 262 |
if err != nil { |
| 263 |
return nil, err |
| 264 |
} |
| 265 |
tmuxArgs = append(tmuxArgs, sh, temp) |
| 266 |
return exec.Command("tmux", tmuxArgs...), nil |
| 267 |
}, opts, true) |
| 268 |
} |