Add --tmux option to replace fzf-tmux script
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Junegunn Choi · committed by Junegunn Choi · parent 01e7668 · Browse files · 12 files·+313 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+313 added−9 removed
- other:+313 added−9 removed
Provenance
- Commit
83b6033- Tree
103394f- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
01e7668
12 files changed+313 added−9 removed
modified:bin/fzf-tmux+4 added-2 removed
130 unmodified lines131 "$fzf" "${args[@]}"132 exit $?133 fi134 135-# --height option is not allowed. CTRL-Z is also disabled.136-args=("${args[@]}" "--no-height" "--bind=ctrl-z:ignore")135+# * --height option is not allowed136+# * CTRL-Z is also disabled137+# * fzf-tmux script is not compatible with --tmux option in fzf 0.53.0 or later138+args=("${args[@]}" "--no-height" "--bind=ctrl-z:ignore" "--no-tmux")139 140 # Handle zoomed tmux pane without popup options by moving it to a temp window141 if [[ ! "$opt" =~ "-E" ]] && tmux list-panes -F '#F' | grep -q Z; then142 zoomed_without_popup=1102 unmodified linesmodified:man/man1/fzf-tmux.1+1 added-1 removed
19 unmodified lines20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22 THE SOFTWARE.23 ..24-.TH fzf-tmux 1 "May 2024" "fzf 0.52.1" "fzf-tmux - open fzf in tmux split pane"24+.TH fzf-tmux 1 "May 2024" "fzf 0.53.0" "fzf-tmux - open fzf in tmux split pane"25 26 .SH NAME27 fzf-tmux - open fzf in tmux split pane28 40 unmodified linesmodified:man/man1/fzf.1+19 added-1 removed
19 unmodified lines20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22 THE SOFTWARE.23 ..24-.TH fzf 1 "May 2024" "fzf 0.52.1" "fzf - a command-line fuzzy finder"24+.TH fzf 1 "May 2024" "fzf 0.53.0" "fzf - a command-line fuzzy finder"25 26 .SH NAME27 fzf - a command-line fuzzy finder28 186 unmodified lines215 .BI "--min-height=" "HEIGHT"216 Minimum height when \fB--height\fR is given in percent (default: 10).217 Ignored when \fB--height\fR is not specified.218 .TP219+.BI "--tmux=" "[center|top|bottom|left|right][,SIZE[%]][,SIZE[%]]"220+Start fzf in a tmux popup. Requires tmux 3.3 or later. This option is ignored221+if you are not running fzf inside tmux.222+223+e.g.224+ \fB# Popup in the center with 80% width height225+ fzf --tmux 80%226+227+ # Popup on the left with 40% width and 100% height228+ fzf --tmux right,40%229+230+ # Popup on the bottom with 100% width and 30% height231+ fzf --tmux bottom,30%232+233+ # Popup on the top with 80% width and 40% height234+ fzf --tmux top,80%,40%\fR235+236+.TP237 .BI "--layout=" "LAYOUT"238 Choose the layout (default: default)239 240 .br1353 unmodified linesmodified:plugin/fzf.vim+2 added-2 removed
535 unmodified lines536 let use_height = 0537 let use_term = 0538 endif539 if use_term540- let optstr .= ' --no-height'540+ let optstr .= ' --no-height --no-tmux'541 elseif use_height542 let height = s:calc_size(&lines, dict.down, dict)543- let optstr .= ' --height='.height543+ let optstr .= ' --no-tmux --height='.height544 endif545 " Respect --border option given in $FZF_DEFAULT_OPTS and 'options'546 let optstr = join([s:border_opt(get(dict, 'window', 0)), s:extract_option($FZF_DEFAULT_OPTS, 'border'), optstr])547 let command = prefix.(use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result547 unmodified linesmodified:src/tui/tui.go+2 added-1 removed
354 unmodified lines355 356 type BorderShape int357 358 const (359- BorderNone BorderShape = iota359+ BorderUndefined BorderShape = iota360+ BorderNone361 BorderRounded362 BorderSharp363 BorderBold364 BorderBlock522 unmodified linesmodified:src/core.go+5 added
1 // Package fzf implements fzf, a command-line fuzzy finder.2 package fzf3 4 import (5+ "os"6 "sync"7 "time"8 9 "github.com/junegunn/fzf/src/util"9 unmodified lines19 */20 21 // Run starts fzf22 func Run(opts *Options) (int, error) {23+ if opts.Tmux != nil && len(os.Getenv("TMUX")) > 0 {24+ return runTmux(os.Args[1:], opts)25+ }26+27 if err := postProcessOptions(opts); err != nil {28 return ExitError, err29 }30 387 unmodified linesmodified:src/functions.go+1 added-1 removed
5 unmodified lines6 "unsafe"7 )8 9 func writeTemporaryFile(data []string, printSep string) string {10- f, err := os.CreateTemp("", "fzf-preview-*")10+ f, err := os.CreateTemp("", "fzf-temp-*")11 if err != nil {12 // Unable to create temporary file13 // FIXME: Should we terminate the program?14 return ""21 unmodified linesmodified:src/options.go+103 added
61 unmodified lines62 If prefixed with '~', fzf will determine the height63 according to the input size.64 --min-height=HEIGHT Minimum height when --height is given in percent65 (default: 10)66+ --tmux=OPTS Start fzf in a tmux popup (requires tmux 3.3+)67+ [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]]68 --layout=LAYOUT Choose layout: [default|reverse|reverse-list]69 --border[=STYLE] Draw border around the finder70 [rounded|sharp|bold|block|thinblock|double|horizontal|vertical|71 top|bottom|left|right|none] (default: rounded)109 unmodified lines181 size float64182 percent bool183 }184 185+func (s sizeSpec) String() string {186+ if s.percent {187+ return fmt.Sprintf("%d%%", int(s.size))188+ }189+ return fmt.Sprintf("%d", int(s.size))190+}191+192 func defaultMargin() [4]sizeSpec {193 return [4]sizeSpec{}194 }195 11 unmodified lines207 posUp windowPosition = iota208 posDown209 posLeft210 posRight211+ posCenter212 )213 214+type tmuxOptions struct {215+ width sizeSpec216+ height sizeSpec217+ position windowPosition218+}219+220 type layoutType int221 222 const (223 layoutDefault layoutType = iota39 unmodified lines263 func (o *previewOpts) Toggle() {264 o.hidden = !o.hidden265 }266 267+func parseTmuxOptions(arg string) (*tmuxOptions, error) {268+ var err error269+ opts := tmuxOptions{}270+ tokens := splitRegexp.Split(arg, -1)271+ if len(tokens) == 0 || len(tokens) > 3 {272+ return nil, errors.New("invalid tmux option: " + arg + " (expected: [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]])")273+ }274+275+ // Defaults to 'center'276+ switch tokens[0] {277+ case "top", "up":278+ opts.position = posUp279+ opts.width = sizeSpec{100, true}280+ case "bottom", "down":281+ opts.position = posDown282+ opts.width = sizeSpec{100, true}283+ case "left":284+ opts.position = posLeft285+ opts.height = sizeSpec{100, true}286+ case "right":287+ opts.position = posRight288+ opts.height = sizeSpec{100, true}289+ case "center":290+ opts.position = posCenter291+ opts.width = sizeSpec{50, true}292+ opts.height = sizeSpec{50, true}293+ default:294+ opts.position = posCenter295+ opts.width = sizeSpec{50, true}296+ opts.height = sizeSpec{50, true}297+ tokens = append([]string{"center"}, tokens...)298+ }299+300+ // One size given301+ var size1 sizeSpec302+ if len(tokens) > 1 {303+ if size1, err = parseSize(tokens[1], 100, "size"); err != nil {304+ return nil, err305+ }306+ }307+308+ // Two sizes given309+ var size2 sizeSpec310+ if len(tokens) == 3 {311+ if size2, err = parseSize(tokens[2], 100, "size"); err != nil {312+ return nil, err313+ }314+ opts.width = size1315+ opts.height = size2316+ } else if len(tokens) == 2 {317+ switch tokens[0] {318+ case "top", "up":319+ opts.height = size1320+ case "bottom", "down":321+ opts.height = size1322+ case "left":323+ opts.width = size1324+ case "right":325+ opts.width = size1326+ case "center":327+ opts.width = size1328+ opts.height = size1329+ }330+ }331+332+ return &opts, nil333+}334+335 func parseLabelPosition(opts *labelOpts, arg string) error {336 opts.column = 0337 opts.bottom = false338 var err error40 unmodified lines379 // Options stores the values of command-line options380 type Options struct {381 Input chan string382 Output chan string383+ Tmux *tmuxOptions384 Bash bool385 Zsh bool386 Fish bool387 Fuzzy bool1483 unmodified lines1871 opts.Help = true1872 case "--version":1873 clearExitingOpts()1874 opts.Version = true1875+ case "--tmux":1876+ str, err := nextString(allArgs, &i, "tmux options required")1877+ if err != nil {1878+ return err1879+ }1880+ if opts.Tmux, err = parseTmuxOptions(str); err != nil {1881+ return err1882+ }1883+ case "--no-tmux":1884+ opts.Tmux = nil1885 case "-x", "--extended":1886 opts.Extended = true1887 case "-e", "--exact":1888 opts.Fuzzy = false469 unmodified lines2358 if match, value := optString(arg, "--algo="); match {2359 if opts.FuzzyAlgo, err = parseAlgo(value); err != nil {2360 return err2361 }2362+ } else if match, value := optString(arg, "--tmux="); match {2363+ if opts.Tmux, err = parseTmuxOptions(value); err != nil {2364+ return err2365+ }2366 } else if match, value := optString(arg, "--scheme="); match {2367 opts.Scheme = strings.ToLower(value)2368 } else if match, value := optString(arg, "-q", "--query="); match {2369 opts.Query = value206 unmodified lines2576 if opts.Ambidouble {2577 uniseg.EastAsianAmbiguousWidth = 22578 }2579 2580+ if opts.BorderShape == tui.BorderUndefined {2581+ opts.BorderShape = tui.BorderNone2582+ }2583+2584 if err := validateSign(opts.Pointer, "pointer"); err != nil {2585 return err2586 }2587 156 unmodified linesadded:src/tmux_unix.go+9 added
1+//go:build !windows2+3+package fzf4+5+import "golang.org/x/sys/unix"6+7+func mkfifo(path string, mode uint32) error {8+ return unix.Mkfifo(path, mode)9+}added:src/tmux_windows.go+17 added
1+//go:build windows2+3+package fzf4+5+import (6+ "os/exec"7+ "strconv"8+)9+10+func mkfifo(path string, mode uint32) error {11+ m := strconv.FormatUint(uint64(mode), 8)12+ cmd := exec.Command("mkfifo", "-m", m, path)13+ if err := cmd.Run(); err != nil {14+ return err15+ }16+ return nil17+}added:src/tmux.go+149 added
1+package fzf2+3+import (4+ "bufio"5+ "fmt"6+ "io"7+ "os"8+ "os/exec"9+ "path/filepath"10+ "strings"11+ "time"12+13+ "github.com/junegunn/fzf/src/tui"14+ "github.com/junegunn/fzf/src/util"15+)16+17+func escapeSingleQuote(str string) string {18+ return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"19+}20+21+func runTmux(args []string, opts *Options) (int, error) {22+ ns := time.Now().UnixNano()23+24+ output := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-tmux-output-%d", ns))25+ if err := mkfifo(output, 0666); err != nil {26+ return ExitError, err27+ }28+ defer os.Remove(output)29+30+ // Find fzf executable31+ fzf := "fzf"32+ if found, err := os.Executable(); err == nil {33+ fzf = found34+ }35+36+ // Prepare arguments37+ args = append([]string{"--bind=ctrl-z:ignore"}, args...)38+ if opts.BorderShape == tui.BorderUndefined {39+ args = append(args, "--border")40+ }41+ args = append(args, "--no-height")42+ args = append(args, "--no-tmux")43+ argStr := ""44+ for _, arg := range args {45+ // %q formatting escapes $'foo\nbar' to "foo\nbar"46+ argStr += " " + escapeSingleQuote(arg)47+ }48+49+ // Build command50+ var command string51+ if opts.Input == nil && util.IsTty() {52+ command = fmt.Sprintf(`%q%s > %q`, fzf, argStr, output)53+ } else {54+ input := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-tmux-input-%d", ns))55+ if err := mkfifo(input, 0644); err != nil {56+ return ExitError, err57+ }58+ defer os.Remove(input)59+60+ go func() {61+ inputFile, err := os.OpenFile(input, os.O_WRONLY, 0)62+ if err != nil {63+ return64+ }65+ if opts.Input == nil {66+ io.Copy(inputFile, os.Stdin)67+ } else {68+ for item := range opts.Input {69+ fmt.Fprint(inputFile, item+opts.PrintSep)70+ }71+ }72+ inputFile.Close()73+ }()74+75+ command = fmt.Sprintf(`%q%s < %q > %q`, fzf, argStr, input, output)76+ }77+78+ // Get current directory79+ dir, err := os.Getwd()80+ if err != nil {81+ dir = "."82+ }83+84+ // Set tmux options for popup placement85+ // C Both The centre of the terminal86+ // R -x The right side of the terminal87+ // P Both The bottom left of the pane88+ // M Both The mouse position89+ // W Both The window position on the status line90+ // S -y The line above or below the status line91+ tmuxArgs := []string{"display-popup", "-E", "-B", "-d", dir}92+ switch opts.Tmux.position {93+ case posUp:94+ tmuxArgs = append(tmuxArgs, "-xC", "-y0")95+ case posDown:96+ tmuxArgs = append(tmuxArgs, "-xC", "-yS")97+ case posLeft:98+ tmuxArgs = append(tmuxArgs, "-x0", "-yC")99+ case posRight:100+ tmuxArgs = append(tmuxArgs, "-xR", "-yC")101+ case posCenter:102+ tmuxArgs = append(tmuxArgs, "-xC", "-yC")103+ }104+ tmuxArgs = append(tmuxArgs, "-w"+opts.Tmux.width.String())105+ tmuxArgs = append(tmuxArgs, "-h"+opts.Tmux.height.String())106+107+ // To ensure that the options are processed by a POSIX-compliant shell,108+ // we need to write the command to a temporary file and execute it with sh.109+ exports := os.Environ()110+ for idx, pairStr := range exports {111+ pair := strings.SplitN(pairStr, "=", 2)112+ exports[idx] = fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1]))113+ }114+ temp := writeTemporaryFile(append(exports, command), "\n")115+ defer os.Remove(temp)116+ tmuxArgs = append(tmuxArgs, "sh", temp)117+118+ // Take the output119+ go func() {120+ outputFile, err := os.OpenFile(output, os.O_RDONLY, 0)121+ if err != nil {122+ return123+ }124+ if opts.Output == nil {125+ io.Copy(os.Stdout, outputFile)126+ } else {127+ reader := bufio.NewReader(outputFile)128+ sep := opts.PrintSep[0]129+ for {130+ item, err := reader.ReadString(sep)131+ if err != nil {132+ break133+ }134+ opts.Output <- item135+ }136+ }137+138+ outputFile.Close()139+ }()140+141+ cmd := exec.Command("tmux", tmuxArgs...)142+ if err := cmd.Run(); err != nil {143+ if exitError, ok := err.(*exec.ExitError); ok {144+ return exitError.ExitCode(), err145+ }146+ }147+148+ return ExitOk, nil149+}modified:main.go+1 added-1 removed
33 unmodified lines34 fmt.Println("### end: " + label + " ###")35 }36 37 func exit(code int, err error) {38- if err != nil {38+ if code == fzf.ExitError {39 fmt.Fprintln(os.Stderr, err.Error())40 }41 os.Exit(code)42 }40 unmodified lines