Separate floating pane border label from pane title
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--border-label of a tmux floating pane was stored in the pane title and read back by pane-border-format as '#{pane_title}', so any program in the pane could replace the border text by setting the title. On Zellij the name was only set when the pane was created. Either way the built-in label actions could not touch it, as fzf draws no border of its own there. - tmux: hold the label in pane-scoped @fzf-border-label. Set the option even without a label, so a later change-border-label has somewhere to write. Drop select-pane -T; the pane title is left to the user - Zellij: run 'zellij action rename-pane' on label change. 'zellij run' has no option to set the environment of the new pane, so the command exports the target itself - change-border-label and transform-border-label now update the native border, through the setter nativeLabelSetter picks by multiplexer - The pane is named in a __FZF_INTERNAL_ variable that runProxy withholds from the environment replay, so the same name in the outer environment cannot redirect the update to another pane
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+279 added−57 removed
- tests:+45 added−6 removed
- other:+234 added−51 removed
Provenance
- Commit
50e6c02- Tree
ca18f76- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
b5f2ba4
9 files changed+279 added−57 removed
modified:man/man1/fzf.1+7 added-3 removed
424 unmodified lines425 On tmux 3.7 or above and on Zellij, the floating pane is not modal; you can426 switch to other panes and windows while fzf is running, and move and resize427 the pane with the mouse. The native border of the pane is the handle for428 moving and resizing it, so it is used by default and \fBborder\-native\fR is429-implied. On tmux, \fB\-\-border\-label\fR is set as the title of the pane,430-and is displayed on the border if \fBpane\-border\-status\fR is enabled in431-tmux (\fB\-\-border\-label\-pos\fR is ignored).429+implied. \fB\-\-border\-label\fR is displayed on the native border, and430+\fBchange\-border\-label\fR and \fBtransform\-border\-label\fR update it431+(\fB\-\-border\-label\-pos\fR is ignored). On tmux, fzf holds the label in432+the \fB@fzf\-border\-label\fR option of the pane and sets its433+\fBpane\-border\-format\fR to read it back, so the label is displayed if434+\fBpane\-border\-status\fR is enabled in tmux. The title of the pane is left435+alone. On Zellij, the label is the name of the pane.436 437 fzf draws its own border instead when a border style is explicitly specified438 with \fB\-\-border\fR, so that it is the only border shown. \fBnone\fR and439 \fBline\fR are treated as no border. Give \fBborder\-native\fR to keep the1980 unmodified linesadded:src/proxy_test.go+65 added
1+package fzf2+3+import (4+ "strconv"5+ "sync"6+ "testing"7+ "time"8+)9+10+func TestLabelUpdater(t *testing.T) {11+ var mu sync.Mutex12+ applied := []int{}13+ // The goroutine can still be running after the test function returns, so14+ // it records the label instead of reporting it, and -1 stands in for one15+ // that could not be parsed16+ updater := &labelUpdater{set: func(label string) {17+ n, err := strconv.Atoi(label)18+ if err != nil {19+ n = -120+ }21+ mu.Lock()22+ applied = append(applied, n)23+ mu.Unlock()24+ // Long enough for the burst to pile up behind the first update25+ time.Sleep(time.Millisecond)26+ }}27+28+ const last = 9929+ for i := 0; i <= last; i++ {30+ updater.update(strconv.Itoa(i))31+ }32+33+ // However many updates are dropped, the final one is always applied34+ deadline := time.Now().Add(5 * time.Second)35+ for {36+ mu.Lock()37+ done := len(applied) > 0 && applied[len(applied)-1] == last38+ mu.Unlock()39+ if done {40+ break41+ }42+ if time.Now().After(deadline) {43+ t.Fatalf("last update was not applied: %v", applied)44+ }45+ time.Sleep(time.Millisecond)46+ }47+48+ mu.Lock()49+ defer mu.Unlock()50+ // Updates are never applied out of order, so the border cannot be left51+ // showing a label older than the last one requested52+ for i, n := range applied {53+ if i > 0 && n <= applied[i-1] {54+ t.Errorf("applied out of order: %v", applied)55+ break56+ }57+ }58+ // A burst collapses instead of running one command per update. The59+ // updates are queued in a tight loop while each one takes a millisecond60+ // to apply, so all of them landing would mean no coalescing at all61+ if len(applied) >= last+1 {62+ t.Errorf("expected updates to be coalesced, applied all %d", len(applied))63+ }64+ t.Logf("applied %d of %d updates", len(applied), last+1)65+}modified:src/proxy.go+69 added
9 unmodified lines10 "os/signal"11 "path/filepath"12 "regexp"13 "strings"14+ "sync"15 "time"16 17 "github.com/junegunn/fzf/src/tui"18 "github.com/junegunn/fzf/src/util"19 )20 21 const becomeSuffix = ".become"22 23+// Withheld from the environment replay below, so an outer value cannot24+// override what the floating pane set25+const internalEnvPrefix = "__FZF_INTERNAL_"26+27 func escapeSingleQuote(str string) string {28 return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"29 }30 31+// Read and remove, so preview and execute commands do not inherit it32+func takeEnv(name string) string {33+ value := os.Getenv(name)34+ os.Unsetenv(name)35+ return value36+}37+38+// Applies label updates off the event loop, which would block on the fork39+type labelUpdater struct {40+ set func(string)41+ mu sync.Mutex42+ pending *string43+ running bool44+}45+46+// A queue of one: a burst collapses to the newest label. A goroutine per47+// update could apply them out of order48+func (u *labelUpdater) update(label string) {49+ u.mu.Lock()50+ defer u.mu.Unlock()51+ u.pending = &label52+ if u.running {53+ return54+ }55+ u.running = true56+ go u.run()57+}58+59+// Ends once caught up, so nothing needs cancelling when Run returns60+func (u *labelUpdater) run() {61+ for {62+ u.mu.Lock()63+ label := u.pending64+ if label == nil {65+ u.running = false66+ u.mu.Unlock()67+ return68+ }69+ u.pending = nil70+ u.mu.Unlock()71+ u.set(*label)72+ }73+}74+75+// Updates the label on the native border, or nil when it is not fzf's to update76+func nativeLabelSetter() func(string) {77+ // Read both, so neither is left behind78+ tmuxPane, zellijPane := takeEnv(tmuxBorderLabelEnv), takeEnv(zellijBorderLabelEnv)79+ var set func(string)80+ switch {81+ case tmuxPane != "":82+ set = func(label string) { setTmuxBorderLabel(tmuxPane, label) }83+ case zellijPane != "":84+ set = func(label string) { setZellijBorderLabel(zellijPane, label) }85+ default:86+ return nil87+ }88+ updater := &labelUpdater{set: set}89+ return updater.update90+}91+92 func popupArgStr(args []string, opts *Options) (string, string) {93 fzf, rest := args[0], args[1:]94 args = []string{"--bind=ctrl-z:ignore"}95 if !opts.Tmux.border && (opts.BorderShape == tui.BorderUndefined || opts.BorderShape == tui.BorderLine) {94 unmodified lines190 exports = []string{"FZF_DEFAULT_COMMAND=", "FZF_DEFAULT_OPTS=", "FZF_DEFAULT_OPTS_FILE="}191 validIdentifier := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)192 for _, pairStr := range os.Environ() {193 pair := strings.SplitN(pairStr, "=", 2)194+ if strings.HasPrefix(pair[0], internalEnvPrefix) {195+ continue196+ }197 if validIdentifier.MatchString(pair[0]) {198 exports = append(exports, fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1])))199 } else if strings.HasPrefix(pair[0], "BASH_FUNC_") && strings.HasSuffix(pair[0], "%%") {200 name := pair[0][10 : len(pair[0])-2]67 unmodified linesmodified:src/terminal.go+6 added
468 unmodified lines469 clickHeaderColumn int470 clickFooterLine int471 clickFooterColumn int472 proxyScript string473+ setNativeLabel func(string)474 numLinesCache map[int32]numLinesCacheValue475 raw bool476 lastActivity time.Time477 }664 unmodified lines1142 jumpLabels: opts.JumpLabels,1143 printer: opts.Printer,1144 printsep: opts.PrintSep,1145 proxyScript: opts.ProxyScript,1146+ setNativeLabel: nativeLabelSetter(),1147 merger: em,1148 passMerger: em,1149 resultMerger: em,1150 matchMap: make(map[int32]Result),6122 unmodified lines7273 t.borderLabelOpts.label = label7274 if t.border != nil {7275 t.borderLabel, t.borderLabelLen = t.ansiLabelPrinter(label, &tui.ColBorderLabel, false)7276 req(reqRedrawBorderLabel)7277+ } else if t.setNativeLabel != nil {7278+ // fzf draws no border of its own; the label is on the7279+ // native border of the floating pane7280+ t.setNativeLabel(label)7281 }7282 })7283 case actChangePreviewLabel, actTransformPreviewLabel, actBgTransformPreviewLabel:7284 capture(true, func(label string) {1451 unmodified linesmodified:src/tmux_test.go+18 added-10 removed
1 package fzf2 3 import "testing"4 5-func TestEscapeTmuxTitle(t *testing.T) {5+func TestEscapeTmuxFormat(t *testing.T) {6 for _, tc := range []struct {7 given string8 expected string9 }{10 {"", ""},11 {" fzf ", " fzf "},12- {"#", "##"},13- {"##", "####"},14- {" C# notes #S ", " C## notes ##S "},12 {"100%", "100%"},13+ // '#[' would be taken as a style directive when the label is drawn14+ {"#[fg=red]x", "##[fg=red]x"},15+ // '#{' is already literal in a substituted value, but doubling it16+ // keeps a label that fzf renders itself looking the same17+ {"#{pane_id}", "##{pane_id}"},18+ {" C# notes #S ", " C## notes ##S "},19 {";", `\;`},20 {"; rm", "; rm"},18- {" ; ", " ; "},21 } {20- if actual := escapeTmuxTitle(tc.given); actual != tc.expected {22+ if actual := escapeTmuxFormat(tc.given); actual != tc.expected {23 t.Errorf("expected %q, got %q", tc.expected, actual)24 }25 }26 }27 26-func TestEscapeTmuxTitleSeparator(t *testing.T) {28+func TestEscapeTmuxSeparator(t *testing.T) {29 for _, tc := range []struct {30 given string31 expected string32 }{31- {"#;", "##;"},32- {";#", ";##"},33+ {"", ""},34+ {" fzf ", " fzf "},35+ {"#", "#"},36+ {"#{pane_id}", "#{pane_id}"},37+ {"100%", "100%"},38+ {";", `\;`},39+ {"; rm", "; rm"},40+ {" ; ", " ; "},41 {";;", ";;"},42 } {35- if actual := escapeTmuxTitle(tc.given); actual != tc.expected {43+ if actual := escapeTmuxSeparator(tc.given); actual != tc.expected {44 t.Errorf("expected %q, got %q", tc.expected, actual)45 }46 }47 }modified:src/tmux.go+44 added-33 removed
53 unmodified lines54 }55 return str56 }57 58-// Escape a string for use as the pane title; select-pane -T expands format59-// expressions denoted by '#', but not time conversion specifiers60-func escapeTmuxTitle(str string) string {58+// '#[...]' is still processed when a substituted value is drawn, so '#' is59+// doubled. '#{...}' is already literal60+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 on65+const (66+ tmuxBorderLabelOption = "@fzf-border-label"67+ tmuxBorderLabelEnv = internalEnvPrefix + "TMUX_LABEL_PANE"68+)69+70+// Errors are ignored. The pane may be gone71+func setTmuxBorderLabel(pane string, label string) {72+ // Strip ANSI sequences. tmux would draw the escape's remainder as text73+ 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 minimum79 // footprint of 3, including the border, and the window size80 func tmuxDim(spec sizeSpec, window int) int {81 dim := int(spec.size)59 unmodified lines141 // The pane should always close on exit like a popup, even when142 // remain-on-exit is on.143 setup := `tmux set-option -p -t "$TMUX_PANE" remain-on-exit off 2> /dev/null; `144 131- // Set --border-label as the title of the floating pane, and as its132- // pane-border-format so that it is displayed on the border when133- // pane-border-status is enabled. Without a label, the border text134- // is cleared so that the default pane status content (e.g. the135- // pane title) is not shown. pane-border-format is pane-scoped,136- // but pane-border-status is a window option that only becomes137- // pane-scoped in the next release of tmux, so it is left alone.145+ // --border-label lives in a pane-scoped user option that146+ // pane-border-format reads back, so a program in the pane cannot147+ // replace it by setting the title. Set even when empty, so148+ // change-border-label can fill it in and the default pane status is149+ // not shown. pane-border-status is a window option until the next150+ // tmux release, so it is left alone.151 // https://github.com/tmux/tmux/commit/7a18fa281db3139- // --border-label-pos is ignored.140- // The label is left to fzf when it draws its own border with the141- // label on it. '--border=none' is not the case; fzf would not142- // display the label, but the native border of a floating pane143- // cannot be removed, so display the label on it nonetheless.144- format := ""145- if opts.BorderLabel.label != "" &&146- (opts.BorderShape == tui.BorderUndefined || opts.BorderShape == tui.BorderLine ||147- opts.BorderShape == tui.BorderNone) {152+ // --border-label-pos is ignored. With an explicit --border fzf draws153+ // 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 itself149- label, _, _ := extractColor(opts.BorderLabel.label, nil, nil)150- if label != "" {151- setup += fmt.Sprintf(`tmux select-pane -t "$TMUX_PANE" -T %s 2> /dev/null; `,152- escapeSingleQuote(escapeTmuxTitle(label)))153- // The title is displayed verbatim; substituted values are154- // not expanded again155- format = "#{pane_title}"156- }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; `,159- escapeSingleQuote(format))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 zoomed170 // window crashes the tmux server on 3.7b, and newer versions of28 unmodified lines199 return exec.Command(sh, "-c", script), nil200 }, opts, true)201 }202 203+// Whether no box border was asked for. 'none' and 'line' count as none.204+// fzf draws no box for either205+func noBorderSpecified(opts *Options) bool {206+ return opts.BorderShape == tui.BorderUndefined ||207+ opts.BorderShape == tui.BorderLine || opts.BorderShape == tui.BorderNone208+}209+210 // Whether to use the multiplexer's native border for the floating pane. Its211 // native border is the handle that makes the pane movable and resizable with212 // the mouse, so it is the default; 'border-native' forces it. It is not used213 // when a border style is explicitly specified with --border, so that the200-// fzf-drawn border is the only one shown. 'none' and 'line' are treated as no201-// border; fzf draws no box for either, and 'line' only makes sense with202-// --height.214+// fzf-drawn border is the only one shown.215 func nativeBorder(opts *Options) bool {204- return opts.Tmux.border || opts.BorderShape == tui.BorderUndefined ||205- opts.BorderShape == tui.BorderLine || opts.BorderShape == tui.BorderNone216+ 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.48 unmodified linesmodified:src/zellij.go+22 added-5 removed
1 package fzf2 3 import (4+ "fmt"5 "os/exec"5-6- "github.com/junegunn/fzf/src/tui"6 )7 8+const zellijBorderLabelEnv = internalEnvPrefix + "ZELLIJ_LABEL_PANE"9+10+// Errors are ignored. The pane may be gone11+func setZellijBorderLabel(pane string, label string) {12+ // Strip ANSI sequences fzf would otherwise render itself13+ label, _, _ = extractColor(label, nil, nil)14+ // '--' so that a label starting with a hyphen is not parsed as a flag15+ exec.Command("zellij", "action", "rename-pane", "-p", pane, "--", label).Run()16+}17+18 func runZellij(args []string, opts *Options) (int, error) {19 // Use the native Zellij border by default, consistent with tmux, so that20 // the pane can be moved and resized with the mouse. Set before21 // popupArgStr so that it does not inject an fzf border. fzf draws its own6 unmodified lines28 zellijArgs := []string{29 "run", "--floating", "--close-on-exit", "--block-until-exit",30 "--cwd", dir,31 }32+ ownsLabel := false33 if !opts.Tmux.border {34 zellijArgs = append(zellijArgs, "--borderless", "true")35 } else {36 // Set --border-label as the name of the pane, displayed on the5 unmodified lines42 // label starts with a hyphen. No escaping is needed beyond43 // stripping ANSI sequences fzf would otherwise render itself.44 // --border-label-pos is ignored.45 label := ""36- if opts.BorderShape == tui.BorderUndefined || opts.BorderShape == tui.BorderLine ||37- opts.BorderShape == tui.BorderNone {46+ ownsLabel = noBorderSpecified(opts)47+ if ownsLabel {48 label, _, _ = extractColor(opts.BorderLabel.label, nil, nil)49 }50 zellijArgs = append(zellijArgs, "--name="+label)51 }17 unmodified lines69 sh, err := sh(needBash)70 if err != nil {71 return nil, err72 }73+ if ownsLabel {74+ // 'zellij run' cannot set the new pane's environment, so the75+ // command exports it itself. exec avoids a lingering shell76+ zellijArgs = append(zellijArgs, sh, "-c", fmt.Sprintf(`export %s="$ZELLIJ_PANE_ID"; exec %s %s`,77+ zellijBorderLabelEnv, escapeSingleQuote(sh), escapeSingleQuote(temp)))78+ } else {63- zellijArgs = append(zellijArgs, sh, temp)79+ zellijArgs = append(zellijArgs, sh, temp)80+ }81 return exec.Command("zellij", zellijArgs...), nil82 }, opts, true)83 }modified:test/test_tmux.rb+45 added-6 removed
15 unmodified lines16 17 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- # Border text is cleared when no label is given21- format = IO.popen(['tmux', 'show-options', '-p', '-t', floating_pane, 'pane-border-format'], &:read)22- assert_includes format, "''"20+ # Border text is empty when no label is given21+ pane = floating_pane22+ refute_nil pane23+ assert_equal "\#{@fzf-border-label}", pane_option(pane, 'pane-border-format')24+ assert_equal '', pane_option(pane, '@fzf-border-label')25 tmux.send_keys '99'26 tmux.until { |lines| assert_equal 1, lines.match_count }27 tmux.send_keys :Enter28 assert_equal '99', fzf_output12 unmodified lines41 tmux.send_keys "seq 100 | #{fzf(%(--popup center,80% --margin 0 --border-label ' #fzf-label 100% '))}", :Enter42 tmux.until { |lines| assert_equal 100, lines.item_count }43 pane = floating_pane44 refute_nil pane45+ # The label is held in a user option, not in the pane title, which is46+ # left to the user. '#' is doubled so that the label is drawn as it is47+ # written, instead of '#[...]' being taken as a style directive48+ assert_equal ' ##fzf-label 100% ', pane_option(pane, '@fzf-border-label')49+ assert_equal "\#{@fzf-border-label}", pane_option(pane, 'pane-border-format')50 title = IO.popen(['tmux', 'display-message', '-p', '-t', pane, "\#{pane_title}"], &:read)44- assert_equal ' #fzf-label 100% ', title.chomp45- format = IO.popen(['tmux', 'show-options', '-p', '-t', pane, 'pane-border-format'], &:read)46- assert_includes format, "\#{pane_title}"51+ refute_equal ' #fzf-label 100% ', title.chomp52 tmux.send_keys :Enter53 assert_equal '1', fzf_output54 end55 56+ def test_floating_pane_change_border_label57+ tmux.send_keys "seq 100 | #{fzf(%(--popup center,80% --margin 0 --bind 'space:change-border-label( #[fg=red] 100% )'))}", :Enter58+ tmux.until { |lines| assert_equal 100, lines.item_count }59+ pane = floating_pane60+ refute_nil pane61+ assert_equal '', pane_option(pane, '@fzf-border-label')62+ tmux.send_keys :Space63+ wait { assert_equal ' ##[fg=red] 100% ', pane_option(pane, '@fzf-border-label') }64+ tmux.send_keys :Enter65+ assert_equal '1', fzf_output66+ end67+68+ # A program running in the pane owns the pane title, but not the label69+ def test_floating_pane_border_label_not_affected_by_title70+ tmux.send_keys "seq 100 | #{fzf(%(--popup center,80% --margin 0 --border-label ' label ' --bind 'space:execute-silent(printf "\\033]2;hijacked\\033\\\\" > /dev/tty)'))}", :Enter71+ tmux.until { |lines| assert_equal 100, lines.item_count }72+ pane = floating_pane73+ refute_nil pane74+ tmux.send_keys :Space75+ wait do76+ title = IO.popen(['tmux', 'display-message', '-p', '-t', pane, "\#{pane_title}"], &:read)77+ assert_equal 'hijacked', title.chomp78+ end79+ assert_equal ' label ', pane_option(pane, '@fzf-border-label')80+ tmux.send_keys :Enter81+ assert_equal '1', fzf_output82+ end83+84 def test_floating_pane_become85 tmux.send_keys "seq 100 | #{fzf(%(--popup center,80% --margin 0 --bind 'enter:become(echo became-{})'))}", :Enter86 tmux.until { |lines| assert_equal 100, lines.item_count }87 tmux.send_keys :Enter23 unmodified lines111 end112 113 private114 115+ # stderr is merged in so that an unset option, which prints 'invalid116+ # option' to stderr and nothing to stdout, is not read as an empty value117+ def pane_option(pane, name)118+ IO.popen(['tmux', 'show-options', '-p', '-t', pane, '-v', name], err: %i[child out], &:read).chomp119+ end120+121 def floating_pane122 format = "\#{pane_id} \#{pane_floating_flag}"123 lines = IO.popen(['tmux', 'list-panes', '-t', tmux.win, '-F', format]) { |io| io.readlines(chomp: true) }124 lines.filter_map { |line| line.split.first if line.end_with?(' 1') }.first2 unmodified linesmodified:CHANGELOG.md+3 added
1 unmodified line2 =========3 4 0.74.25 ------6+- `change-border-label` and `transform-border-label` now update the label on the native border of a tmux or Zellij floating pane7+ - On tmux, the label no longer goes through the pane title, so a program running in the pane cannot replace it by setting the title8+- Fixed a Kitty graphics sequence from a preview command being taken by tmux as a request to set the pane title; it is now passed through to the terminal9 - Performance optimizations for short queries10 - The most critical case: fzf narrows results as you type, so short queries scan the largest candidate sets and the first keystroke scans the whole input.11 - Single-character queries are up to 2.4x faster12 - Two-character queries are up to 1.4x faster3400 unmodified lines