Skip to content
Myr

tmux.go

This file

Path

src/tmux.go

275 lines · 10.9 KiB · Go

Last changed by

Preserve tmux window zoom when opening a floating paneJunegunn Choibefore adoptiond8aeec3

History of this file

Take it

1package fzf23import (4	"fmt"5	"os"6	"os/exec"7	"path/filepath"8	"regexp"9	"strings"1011	"github.com/junegunn/fzf/src/tui"12)1314// The flag group of new-pane usage includes -A (tmux 3.8 or above)15var tmuxOverZoomFlag = regexp.MustCompile(`new-pane.*\[-[[:alpha:]]*A`)1617// Returns the size of the current window if the tmux server supports18// floating panes (tmux 3.7 or above), and whether a floating pane can stay19// above a zoomed pane20func tmuxFloatingPaneInfo() (int, int, bool, bool) {21	// TMUX_PANE is not set when fzf is not started from within a pane22	// (e.g. 'bind-key 0 run-shell "fzf --popup"'). Do not use a floating23	// pane there; a blocking run-shell suspends key processing for the24	// client until the command exits, so fzf in a floating pane would25	// never receive a key and the client would appear frozen until the26	// process is killed externally. A popup is unaffected; its input is27	// handled at the client overlay level, bypassing the suspended path.28	// The right approach for such bindings is 'run-shell -b', which does29	// not suspend key processing, as discussed in:30	//   https://github.com/tmux/tmux/issues/538431	target := os.Getenv("TMUX_PANE")32	if target == "" {33		return 0, 0, false, false34	}35	// A single invocation for both checks. Cannot rely on the exit status;36	// tmux versions before 3.7 exit normally with empty output for an37	// unknown command name, so check the output instead.38	out, err := exec.Command("tmux", "display-message", "-p", "-t", target,39		"#{window_width} #{window_height}", ";", "list-commands", "new-pane").Output()40	if err != nil || !strings.Contains(string(out), "new-pane") {41		return 0, 0, false, false42	}43	var width, height int44	if _, err := fmt.Sscanf(string(out), "%d %d", &width, &height); err != nil {45		return 0, 0, false, false46	}47	// The window is too small to fit a floating pane of the minimum size48	if width < 3 || height < 3 {49		return 0, 0, false, false50	}51	return width, height, tmuxOverZoomFlag.Match(out), true52}5354// tmux ends a command at an argument ending in ';', so a trailing one is55// escaped. Elsewhere it is not special56func escapeTmuxSeparator(str string) string {57	if strings.HasSuffix(str, ";") {58		return str[:len(str)-1] + `\;`59	}60	return str61}6263// '#[...]' is still processed when a substituted value is drawn, so '#' is64// doubled. '#{...}' is already literal65func escapeTmuxFormat(str string) string {66	return escapeTmuxSeparator(strings.ReplaceAll(str, "#", "##"))67}6869// The option pane-border-format reads back, and the pane it is set on70const (71	tmuxBorderLabelOption = "@fzf-border-label"72	tmuxBorderLabelEnv    = internalEnvPrefix + "TMUX_LABEL_PANE"73)7475// Errors are ignored. The pane may be gone76func setTmuxBorderLabel(pane string, label string) {77	// Strip ANSI sequences. tmux would draw the escape's remainder as text78	label, _, _ = extractColor(label, nil, nil)79	exec.Command("tmux", "set-option", "-p", "-t", pane,80		tmuxBorderLabelOption, escapeTmuxFormat(label)).Run()81}8283// Convert sizeSpec to the number of cells, clamped between the minimum84// footprint of 3, including the border, and the window size85func tmuxDim(spec sizeSpec, window int) int {86	dim := int(spec.size)87	if spec.percent {88		dim = window * dim / 10089	}90	return max(3, min(dim, window))91}9293func runTmuxFloatingPane(argStr string, dir string, windowWidth int, windowHeight int, overZoom bool, opts *Options) (int, error) {94	// Unlike display-popup, the size of a floating pane does not account for95	// the border around it, and the position is that of the content area. To96	// stay consistent with popups, treat the requested size as the total97	// footprint including the border.98	width := tmuxDim(opts.Tmux.width, windowWidth)99	height := tmuxDim(opts.Tmux.height, windowHeight)100	x := (windowWidth-width)/2 + 1101	y := (windowHeight-height)/2 + 1102	switch opts.Tmux.position {103	case posUp:104		y = 1105	case posDown:106		y = windowHeight - height + 1107	case posLeft:108		x = 1109	case posRight:110		x = windowWidth - width + 1111	}112113	return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {114		sh, err := sh(needBash)115		if err != nil {116			return nil, err117		}118		// Unlike display-popup, new-pane does not block until the command119		// finishes, and it does not propagate the exit status. So we block on120		// a wait-for channel that the pane signals on completion, and pass121		// the exit status through a temporary file. A watchdog process122		// signals the same channel if the pane is closed abnormally123		// (e.g. kill-pane), in which case the file is not written.124		//125		// has-session is the liveness check because it fails when the target126		// pane is gone, while display-message succeeds even for a dead pane.127		signal := escapeSingleQuote("fzf-" + filepath.Base(temp))128129		// Pre-create the exit status file so that another user on a shared130		// TMPDIR cannot plant a file or a symbolic link at the predictable131		// path while the pane is running132		codeFile := temp + ".code"133		f, err := os.OpenFile(codeFile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)134		if err != nil {135			return nil, err136		}137		f.Close()138		code := escapeSingleQuote(codeFile)139140		// Pane options are set by the pane itself before running fzf, so141		// that they are in place no matter how quickly the command exits.142		// The target must be explicit; without it, the commands would143		// resolve to the active pane of the session's current window,144		// which is not necessarily the pane running them.145		//146		// The pane should always close on exit like a popup, even when147		// remain-on-exit is on.148		setup := `tmux set-option -p -t "$TMUX_PANE" remain-on-exit off 2> /dev/null; `149150		// --border-label lives in a pane-scoped user option that151		// pane-border-format reads back, so a program in the pane cannot152		// replace it by setting the title. Set even when empty, so153		// change-border-label can fill it in and the default pane status is154		// not shown. pane-border-status is a window option until the next155		// tmux release, so it is left alone.156		//   https://github.com/tmux/tmux/commit/7a18fa281db3157		// --border-label-pos is ignored. With an explicit --border fzf draws158		// the label itself, but the native border cannot be removed.159		ownsLabel := noBorderSpecified(opts)160		label := ""161		if ownsLabel {162			// Strip ANSI sequences fzf would otherwise render itself163			label, _, _ = extractColor(opts.BorderLabel.label, nil, nil)164		}165		setup += fmt.Sprintf(`tmux set-option -p -t "$TMUX_PANE" %s %s 2> /dev/null; `,166			tmuxBorderLabelOption, escapeSingleQuote(escapeTmuxFormat(label)))167		setup += fmt.Sprintf(`tmux set-option -p -t "$TMUX_PANE" pane-border-format %s 2> /dev/null; `,168			escapeSingleQuote("#{"+tmuxBorderLabelOption+"}"))169		if ownsLabel {170			setup += fmt.Sprintf(`export %s="$TMUX_PANE"; `, tmuxBorderLabelEnv)171		}172		paneCmd := fmt.Sprintf("%s%s %s; echo $? > %s; tmux wait-for -S %s",173			setup, escapeSingleQuote(sh), escapeSingleQuote(temp), code, signal)174		target := os.Getenv("TMUX_PANE")175		newPane := "tmux new-pane -A"176		if !overZoom {177			// Unzoom the window first; creating a floating pane over a178			// zoomed window crashes the tmux server on 3.7b179			newPane = fmt.Sprintf("tmux if -F -t %s '#{window_zoomed_flag}' %s ';' new-pane",180				escapeSingleQuote(target), escapeSingleQuote("resize-pane -Z -t "+target))181		}182		newPane += fmt.Sprintf(" -P -F '#{pane_id}' -t %s -c %s -x %d -y %d -X %d -Y %d %s -c %s",183			escapeSingleQuote(target), escapeSingleQuote(dir), width-2, height-2, x, y,184			escapeSingleQuote(sh), escapeSingleQuote(paneCmd))185186		// The pane is killed when the proxy process is interrupted or hung up,187		// like a popup dying with its client. wait-for runs in the background188		// and is awaited with the interruptible wait builtin so that the trap189		// can fire while blocked. The trap is installed before creating the190		// pane; a signal received during creation is deferred until the191		// command substitution completes, and the pane is killed right after.192		// An interrupted wait does not reap the waiter, so it is killed193		// along with the watchdog.194		script := fmt.Sprintf(`trap '[ -n "$id" ] && tmux kill-pane -t "$id" 2> /dev/null' INT TERM HUP195id=$(%s) || { status=$?; rm -f %s; exit "$status"; }196{ while tmux has-session -t "$id" 2> /dev/null; do sleep 1; done; tmux wait-for -S %s; } &197watchdog=$!198tmux wait-for %s &199waiter=$!200wait "$waiter"201kill "$watchdog" "$waiter" 2> /dev/null202wait 2> /dev/null203if [ -s %s ]; then code=$(cat %s); else code=130; fi204rm -f %s205exit "$code"`, newPane, code, signal, signal, code, code, code)206		return exec.Command(sh, "-c", script), nil207	}, opts, true)208}209210// Whether no box border was asked for. 'none' and 'line' count as none.211// fzf draws no box for either212func noBorderSpecified(opts *Options) bool {213	return opts.BorderShape == tui.BorderUndefined ||214		opts.BorderShape == tui.BorderLine || opts.BorderShape == tui.BorderNone215}216217// Whether to use the multiplexer's native border for the floating pane. Its218// native border is the handle that makes the pane movable and resizable with219// the mouse, so it is the default; 'border-native' forces it. It is not used220// when a border style is explicitly specified with --border, so that the221// fzf-drawn border is the only one shown.222func nativeBorder(opts *Options) bool {223	return opts.Tmux.border || noBorderSpecified(opts)224}225226func runTmux(args []string, opts *Options) (int, error) {227	// On tmux 3.7 or above, fzf runs in a floating pane instead of a popup.228	// When the native border is not used (an explicit --border style), a229	// popup is used instead so that the fzf-drawn border is the only border230	// shown; the native border of a tmux floating pane cannot be removed.231	if nativeBorder(opts) {232		if windowWidth, windowHeight, overZoom, ok := tmuxFloatingPaneInfo(); ok {233			opts.Tmux.border = true234			argStr, dir := popupArgStr(args, opts)235			return runTmuxFloatingPane(argStr, dir, windowWidth, windowHeight, overZoom, opts)236		}237	}238239	argStr, dir := popupArgStr(args, opts)240241	// Set tmux options for popup placement242	// C        Both    The centre of the terminal243	// R        -x      The right side of the terminal244	// P        Both    The bottom left of the pane245	// M        Both    The mouse position246	// W        Both    The window position on the status line247	// S        -y      The line above or below the status line248	tmuxArgs := []string{"display-popup", "-E", "-d", dir}249	if !opts.Tmux.border {250		tmuxArgs = append(tmuxArgs, "-B")251	}252	switch opts.Tmux.position {253	case posUp:254		tmuxArgs = append(tmuxArgs, "-xC", "-y0")255	case posDown:256		tmuxArgs = append(tmuxArgs, "-xC", "-y9999")257	case posLeft:258		tmuxArgs = append(tmuxArgs, "-x0", "-yC")259	case posRight:260		tmuxArgs = append(tmuxArgs, "-xR", "-yC")261	case posCenter:262		tmuxArgs = append(tmuxArgs, "-xC", "-yC")263	}264	tmuxArgs = append(tmuxArgs, "-w"+opts.Tmux.width.String())265	tmuxArgs = append(tmuxArgs, "-h"+opts.Tmux.height.String())266267	return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {268		sh, err := sh(needBash)269		if err != nil {270			return nil, err271		}272		tmuxArgs = append(tmuxArgs, sh, temp)273		return exec.Command("tmux", tmuxArgs...), nil274	}, opts, true)275}