Run fzf asynchronously in the Vim plugin (#4897)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Run fzf asynchronously in the Vim plugin Popup mode held the fzf process with system(), which froze Vim until fzf exited. fzf in a popup draws in a pane of its own, so that process only waits for it and does not need a window. Hold it with a job instead and Vim keeps processing its event loop, which is what a live preview needs. Nothing is displayed for the job. Falls back to the blocking path when the job cannot start, so the sink still runs and temp files are removed. - job_start() sets $TERM=dumb and the popup inherits the environment, so fzf dropped to its 16-color scheme. Restore it via 'env', or in the command itself before 8.0.902, when 'env' was added - Fullscreen now uses a terminal buffer in a new tab on Vim too. use_term lacked parentheses, so && bound tighter than || and the layout test was dead on Neovim, which already behaved this way - fzf#run returns an empty list in these modes. Callers use sink, sinklist or exit, and the vader specs now wait for completion - Append --no-tmux only when the spec asks for a Vim window, so --popup in $FZF_DEFAULT_OPTS survives a spec with no layout option Accept popup as a synonym of the tmux layout key, matching --popup being the name of --tmux. popup wins when both are given. s:tmux_enabled(): - Accept $ZELLIJ, which --popup covers as well - Parse tmux -V with matchstr and compare with s:compare_versions. The old string comparison against 'tmux 1.7' misreads 10.0 - Drop the fzf-tmux requirement on tmux 3.3 or above, where --tmux needs no script. Removing the script silently disabled popups entirely - Resolve the script where it is used, and anchor the legacy test to ^- so a --tmux value containing a dash, as in 90%,60%,border-native, is not mistaken for a legacy flag * Turn g:loaded_fzf into a version marker Callers cannot detect plugin-side behavior. fzf#exec() reports the version of the binary, not of this plugin, and everything else here is script-local. fzf.vim needs to know whether fzf#run is asynchronous in popup mode before offering a key binding that depends on it. The value was only ever read through the exists() guard, so raising it from 1 breaks nothing.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+207 added−45 removed
- tests:+65 added−12 removed
- other:+142 added−33 removed
Provenance
- Commit
5cb7bab- Tree
34eb5fd- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
956562d
5 files changed+207 added−45 removed
modified:doc/fzf.txt+7 added-6 removed
308 unmodified lines309 `exit` | funcref | Function to be called with the exit status of fzf (e.g. 0, 1, 2, 130)310 `options` | string/list | Options to fzf311 `dir` | string | Working directory312 `up` / `down` / `left` / `right` | number/string | (Layout) Window position and size (e.g. `20` , `50%` )313- `tmux` | string | (Layout) `--tmux` options (e.g. `90%,70%` )313+ `popup` / `tmux` | string | (Layout) `--popup` options (e.g. `90%,70%` )314 `window` (Vim 8 / Neovim) | string | (Layout) Command to open fzf window (e.g. `vertical aboveleft 30new` )315 `window` (Vim 8 / Neovim) | dict | (Layout) Popup window settings (e.g. `{'width': 0.9, 'height': 0.6}` )316 ---------------------------+---------------+----------------------------------------------------------------------317 148 unmodified lines466 " - border [string default 'rounded']: Border style467 " - 'rounded' / 'sharp' / 'horizontal' / 'vertical' / 'top' / 'bottom' / 'left' / 'right'468 let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6 } }469 <470-Alternatively, you can make fzf open in a tmux popup window (requires tmux 3.2471-or above) by putting `--tmux` options in `tmux` key.470+Alternatively, you can make fzf open in a popup window (requires tmux 3.3 or471+above, or Zellij 0.44 or above) by putting `--popup` options in `popup` key.472+`tmux` is accepted as a synonym, just as `--tmux` is an alias of `--popup`.473 >473- " See `--tmux` option in `man fzf` for available options474+ " See `--popup` option in `man fzf` for available options475 " [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]]475- if exists('$TMUX')476- let g:fzf_layout = { 'tmux': '90%,70%' }476+ if exists('$TMUX') || exists('$ZELLIJ')477+ let g:fzf_layout = { 'popup': '90%,70%' }478 else479 let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6 } }480 endif481 <27 unmodified linesmodified:plugin/fzf.vim+116 added-21 removed
22 unmodified lines23 24 if exists('g:loaded_fzf')25 finish26 endif27+" Bumped when the plugin gains behavior a caller may need to detect27-let g:loaded_fzf = 128+let g:loaded_fzf = 2026082129 30 let s:is_win = has('win32') || has('win64')31 if s:is_win && &shellslash32 set noshellslash94 unmodified lines127 function! s:fzf_tempname()128 return s:fzf_call('tempname')129 endfunction130 130-let s:layout_keys = ['window', 'tmux', 'up', 'down', 'left', 'right']131+let s:layout_keys = ['window', 'popup', 'tmux', 'up', 'down', 'left', 'right']132 let s:fzf_go = s:base_dir.'/bin/fzf'133 let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'134 135 let s:cpo_save = &cpo119 unmodified lines255 256 return s:exec257 endfunction258 259+" Path to the fzf-tmux script, or an empty string if it is not available. Only260+" the legacy options still need it. --tmux is handled by fzf itself.261+function! s:fzf_tmux_script()262+ if !executable(s:fzf_tmux)263+ if !executable('fzf-tmux')264+ return ''265+ endif266+ let s:fzf_tmux = 'fzf-tmux'267+ endif268+ return s:fzf_tmux269+endfunction270+271 function! s:tmux_enabled()259- if has('gui_running') || !exists('$TMUX')272+ if has('gui_running')273 return 0274 endif275 276+ " --tmux covers Zellij as well, where the fzf-tmux script and the tmux277+ " version are irrelevant, but the binary only learned it in 0.71.0278+ if exists('$ZELLIJ')279+ return exists('s:exec')280+ \ && s:compare_versions(s:get_version(s:exec), '0.71.0') >= 0281+ endif282+283+ if !exists('$TMUX')284+ return 0285+ endif286+287 if exists('s:tmux')288 return s:tmux289 endif290 291 let s:tmux = 0268- if !executable(s:fzf_tmux)269- if executable('fzf-tmux')270- let s:fzf_tmux = 'fzf-tmux'271- else272- return 0273- endif292+ let output = system('tmux -V')293+ if v:shell_error294+ return s:tmux295 endif296+ " e.g. 'tmux 3.7b', 'tmux next-3.8'297+ let ver = matchstr(output, '\d\+\.\d\+')298 276- let output = system('tmux -V')277- let s:tmux = !v:shell_error && output >= 'tmux 1.7'299+ " --tmux requires tmux 3.3 or above, and needs no fzf-tmux script300+ if s:compare_versions(ver, '3.3') >= 0301+ let s:tmux = 1302+ return s:tmux303+ endif304+305+ " Older versions still go through the script306+ let s:tmux = !empty(s:fzf_tmux_script()) && s:compare_versions(ver, '1.7') >= 0307 return s:tmux308 endfunction309 310 function! s:escape(path)219 unmodified lines530 try531 let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()532 533 let dict = exists('a:1') ? copy(a:1) : {}534+ " 'popup' and 'tmux' are synonyms, as --popup and --tmux are. Normalize here535+ " so that the rest of the function only has to know about one of them.536+ if has_key(dict, 'popup')537+ let dict.tmux = remove(dict, 'popup')538+ endif539 let temps = { 'result': s:fzf_tempname() }540 let optstr = s:evaluate_opts(get(dict, 'options', ''))541 try542 let fzf_exec = shellescape(fzf#exec())29 unmodified lines572 \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&573 \ executable('tput') && filereadable('/dev/tty')574 let has_vim8_term = has('terminal') && has('patch-8.0.995')575 let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win542- let use_term = has_nvim_term || has_vim8_term543- \ && !s:need_cmd_window544- \ && (has('gui_running') || s:is_win || s:present(dict, 'down', 'up', 'left', 'right', 'window'))576+ let use_term = (has_nvim_term || has_vim8_term) && !s:need_cmd_window577 let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()578 if prefer_tmux && use_tmux579 let use_height = 0580 let use_term = 0581 endif582 if use_term551- let optstr .= ' --no-height --no-tmux'583+ let optstr .= ' --no-height'584+ " Cancel a --popup from $FZF_DEFAULT_OPTS only when the spec asks for a Vim585+ " window. Without a layout option, respect the user's preference.586+ if s:present(dict, 'window', 'up', 'down', 'left', 'right')587+ let optstr .= ' --no-tmux'588+ endif589 elseif use_height590 let height = s:calc_size(&lines, dict.down, dict)591 let optstr .= ' --no-tmux --height='.height592 endif11 unmodified lines604 if use_term605 return s:execute_term(dict, command, temps)606 endif607 571- let lines = use_tmux ? s:execute_tmux(dict, command, temps)572- \ : s:execute(dict, command, use_height, temps)608+ " s:execute_tmux may run fzf asynchronously, so it calls s:callback itself609+ if use_tmux610+ return s:execute_tmux(dict, command, temps)611+ endif612+613+ let lines = s:execute(dict, command, use_height, temps)614 call s:callback(dict, lines)615 return lines616 finally617 let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]19 unmodified lines637 endif638 endfor639 endif640 600- " Legacy fzf-tmux options601- if size =~ '-'641+ " Legacy fzf-tmux options are flags. A --tmux value never starts with a dash,642+ " but may contain one, as in '90%,60%,border-native'643+ if size =~ '^-'644+ let script = s:fzf_tmux_script()645+ if empty(script)646+ throw 'fzf-tmux not found, required for the legacy option: ' . size647+ endif648 return printf('LINES=%d COLUMNS=%d %s %s %s --',603- \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))649+ \ &lines, &columns, fzf#shellescape(script), size, (has_key(a:dict, 'source') ? '' : '-'))650 end651 652 " Using native --tmux option653 let in = (has_key(a:dict, 'source') ? '' : ' --force-tty-in')133 unmodified lines787 let lines = s:collect(a:temps)788 return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []789 endfunction790 791+" Returns 0 if the job could not be started792+function! s:start_popup_job(dict, command, temps) abort793+ let fzf = { 'dict': a:dict, 'temps': a:temps, 'command': a:command }794+ " Vim passes (job, status) and Nvim (id, status, event)795+ function! fzf.on_exit(id, code, ...) abort796+ redraw!797+ let lines = s:collect(self.temps)798+ if s:exit_handler(self.dict, a:code, self.command, 1) >= 2799+ return800+ endif801+ call s:pushd(self.dict)802+ call s:callback(self.dict, lines)803+ endfunction804+805+ if has('nvim')806+ return jobstart([&shell, &shellcmdflag, a:command], fzf) > 0807+ endif808+809+ " The command redirects to the result file, so no stream is of interest810+ let opts = { 'exit_cb': function(fzf.on_exit),811+ \ 'in_io': 'null', 'out_io': 'null', 'err_io': 'null' }812+813+ " job_start() gives the child $TERM=dumb, and the popup inherits the814+ " environment from here, so fzf would lose its colors. 'env' was added in815+ " 8.0.902, so set it in the command itself on older versions.816+ let command = a:command817+ if has('patch-8.0.902')818+ let opts.env = { 'TERM': $TERM }819+ elseif !s:is_win820+ let command = join(['export TERM=' . fzf#shellescape($TERM) . ';', command])821+ endif822+823+ let job = job_start([&shell, &shellcmdflag, command], opts)824+ return job_status(job) !=# 'fail'825+endfunction826+827 function! s:execute_tmux(dict, command, temps) abort828 let command = a:command829 let cwd = s:pushd(a:dict)830 if len(cwd)831 " -c '#{pane_current_path}' is only available on tmux 1.9 or above832 let command = join(['cd', fzf#shellescape(cwd), '&&', command])833 endif834 835+ " fzf draws in a pane of its own, so the process we start here only waits for836+ " it. Hold it with a job instead of system() so that Vim keeps processing its837+ " event loop, and nothing has to be displayed for it. Fall back to the838+ " blocking path when the job cannot be started, or the sink would never run839+ " and the temporary files would be left behind.840+ if (has('nvim') || has('job')) && s:start_popup_job(a:dict, command, a:temps)841+ " Restore the working directory while fzf runs. on_exit pushes it again842+ call s:dopopd()843+ return []844+ endif845+846 call system(command)847 let exit_status = v:shell_error848 redraw!849 let lines = s:collect(a:temps)757- return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []850+ let lines = s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []851+ call s:callback(a:dict, lines)852+ return lines853 endfunction854 855 function! s:calc_size(max, val, dict)856 let val = substitute(a:val, '^\~', '', '')396 unmodified linesmodified:test/vim/fzf.vader+65 added-12 removed
2 unmodified lines3 unlet! g:fzf_layout g:fzf_action g:fzf_history_dir4 Log 'Test directory: ' . g:dir5 Save &acd6 7+ " fzf#run runs fzf in a terminal buffer and returns immediately, so the8+ " assertions have to wait for the run to finish. 'exit' is called from the9+ " same handler that runs the sink, just before it, so once it has fired the10+ " sink has run too. It also fires when nothing is selected, unlike the sink.11+ function! g:FzfExit(code)12+ let g:fzf_done = 113+ endfunction14+15+ " Collects the output without displacing a 'sink' the spec already has.16+ " s:callback runs both17+ function! g:FzfCollect(lines)18+ call extend(g:fzf_lines, a:lines)19+ endfunction20+21+ function! g:FzfRun(spec) abort22+ let g:fzf_done = 023+ let g:fzf_lines = []24+ call fzf#run(extend(copy(a:spec),25+ \ { 'exit': function('g:FzfExit'), 'sinklist': function('g:FzfCollect') }))26+ let started = reltime()27+ while !g:fzf_done && reltimefloat(reltime(started)) < 1028+ sleep 10m29+ endwhile30+ if !g:fzf_done31+ throw 'Timed out waiting for fzf#run'32+ endif33+ return g:fzf_lines34+ endfunction35+36 Execute (fzf#run with dir option):37 let cwd = getcwd()9- let result = fzf#run({ 'source': 'git ls-files', 'options': '--filter=vdr', 'dir': g:dir })38+ let result = g:FzfRun({ 'source': 'git ls-files', 'options': '--filter=vdr', 'dir': g:dir })39 AssertEqual ['fzf.vader'], result40 AssertEqual 0, haslocaldir()41 AssertEqual getcwd(), cwd42 43 execute 'lcd' fnameescape(cwd)15- let result = sort(fzf#run({ 'source': 'git ls-files', 'options': '--filter e', 'dir': g:dir }))44+ let result = sort(g:FzfRun({ 'source': 'git ls-files', 'options': '--filter e', 'dir': g:dir }))45 AssertEqual ['fzf.vader'], result46 AssertEqual 1, haslocaldir()47 AssertEqual getcwd(), cwd48 1 unmodified line50 let g:ret = []51 function! g:FzfTest(e)52 call add(g:ret, a:e)53 endfunction25- let result = sort(fzf#run({ 'source': 'git ls-files', 'sink': function('g:FzfTest'), 'options': '--filter e', 'dir': g:dir }))54+ let result = sort(g:FzfRun({ 'source': 'git ls-files', 'sink': function('g:FzfTest'), 'options': '--filter e', 'dir': g:dir }))55 AssertEqual ['fzf.vader'], result56 AssertEqual ['fzf.vader'], sort(g:ret)57 58 Execute (fzf#run with string source):30- let result = sort(fzf#run({ 'source': 'echo hi', 'options': '-f i' }))59+ let result = sort(g:FzfRun({ 'source': 'echo hi', 'options': '-f i' }))60 AssertEqual ['hi'], result61 62 Execute (fzf#run with list source):34- let result = sort(fzf#run({ 'source': ['hello', 'world'], 'options': '-f e' }))63+ let result = sort(g:FzfRun({ 'source': ['hello', 'world'], 'options': '-f e' }))64 AssertEqual ['hello'], result36- let result = sort(fzf#run({ 'source': ['hello', 'world'], 'options': '-f o' }))65+ let result = sort(g:FzfRun({ 'source': ['hello', 'world'], 'options': '-f o' }))66 AssertEqual ['hello', 'world'], result67 68 Execute (fzf#run with string source):40- let result = sort(fzf#run({ 'source': 'echo hi', 'options': '-f i' }))69+ let result = sort(g:FzfRun({ 'source': 'echo hi', 'options': '-f i' }))70 AssertEqual ['hi'], result71 72 Execute (fzf#run with dir option and noautochdir):73 set noacd74 let cwd = getcwd()46- call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})75+ call g:FzfRun({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})76 " No change in working directory77 AssertEqual cwd, getcwd()78 50- call fzf#run({'source': ['/foobar'], 'sink': 'tabe', 'dir': '/tmp', 'options': '-1'})79+ call g:FzfRun({'source': ['/foobar'], 'sink': 'tabe', 'dir': '/tmp', 'options': '-1'})80 AssertEqual cwd, getcwd()81 tabclose82 AssertEqual cwd, getcwd()83 84 Execute (Incomplete fzf#run with dir option and autochdir):85 set acd86 let cwd = getcwd()58- call fzf#run({'source': [], 'sink': 'e', 'dir': '/tmp', 'options': '-0'})87+ call g:FzfRun({'source': [], 'sink': 'e', 'dir': '/tmp', 'options': '-0'})88 " No change in working directory even if &acd is set89 AssertEqual cwd, getcwd()90 91 Execute (FIXME: fzf#run with dir option and autochdir):92 set acd64- call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})93+ call g:FzfRun({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})94 " Working directory changed due to &acd95 AssertEqual '/foobar', expand('%')96 AssertEqual '/', getcwd()97 98 Execute (fzf#run with dir option and autochdir when final cwd is same as dir):99 set acd100 cd /tmp72- call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/', 'options': '-1'})101+ call g:FzfRun({'source': ['/foobar'], 'sink': 'e', 'dir': '/', 'options': '-1'})102 " Working directory changed due to &acd103 AssertEqual '/', getcwd()104 105 Execute (fzf#wrap):72 unmodified lines178 let g:fzf_colors = { 'fg': ['fg', 'Error'] }179 let opts = fzf#wrap({})180 Assert opts.options =~ '--color=fg:'181 182+Execute (popup is a synonym of tmux):183+ unlet! g:fzf_layout184+185+ " Treated as a layout option, so g:fzf_layout is not applied on top186+ let opts = fzf#wrap('foobar', {'popup': '90%,70%'})187+ AssertEqual '90%,70%', opts.popup188+ Assert !has_key(opts, 'window')189+190+ " And stripped in fullscreen, like the others191+ let opts = fzf#wrap('foobar', {'popup': '90%,70%'}, 1)192+ Assert !has_key(opts, 'popup')193+194+ " Accepted in g:fzf_layout195+ let g:fzf_layout = {'popup': '90%,70%'}196+ let opts = fzf#wrap('foobar')197+ AssertEqual '90%,70%', opts.popup198+ unlet g:fzf_layout199+200+ " Listed as a valid key201+ let g:fzf_layout = {'bogus': 1}202+ AssertThrows call fzf#wrap('foobar')203+ Assert g:vader_exception =~ 'popup'204+ unlet g:fzf_layout205+206 Execute (fzf#shellescape with sh):207 AssertEqual '''''', fzf#shellescape('', 'sh')208 AssertEqual '''\''', fzf#shellescape('\', 'sh')209 AssertEqual '''""''', fzf#shellescape('""', 'sh')19 unmodified linesmodified:CHANGELOG.md+11 added
1 CHANGELOG2 =========3 4+0.74.45+------6+- Vim plugin7+ - fzf no longer blocks the editor, so live previews keep working while fzf is open8+ - `fzf#run` returns an empty list when it runs fzf asynchronously. Use `sink`, `sinklist`, or `exit` to get the result9+ - The popup layout now works under Zellij10+ - Added `popup` as a synonym of the `tmux` layout key11+ ```vim12+ let g:fzf_layout = { 'popup': '90%,70%' }13+ ```14+15 0.74.316 ------17 - Performance optimizations for non-ASCII input18 - ASCII queries are up to 16x faster3420 unmodified linesmodified:README-VIM.md+8 added-6 removed
294 unmodified lines295 | `exit` | funcref | Function to be called with the exit status of fzf (e.g. 0, 1, 2, 130) |296 | `options` | string/list | Options to fzf |297 | `dir` | string | Working directory |298 | `up`/`down`/`left`/`right` | number/string | (Layout) Window position and size (e.g. `20`, `50%`) |299-| `tmux` | string | (Layout) `--tmux` options (e.g. `90%,70%`) |299+| `popup`/`tmux` | string | (Layout) `--popup` options (e.g. `90%,70%`) |300 | `window` (Vim 8 / Neovim) | string | (Layout) Command to open fzf window (e.g. `vertical aboveleft 30new`) |301 | `window` (Vim 8 / Neovim) | dict | (Layout) Popup window settings (e.g. `{'width': 0.9, 'height': 0.6}`) |302 303 `options` entry can be either a string or a list. For simple cases, string153 unmodified lines457 " - 'rounded' / 'sharp' / 'horizontal' / 'vertical' / 'top' / 'bottom' / 'left' / 'right'458 let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6 } }459 ```460 461-Alternatively, you can make fzf open in a tmux popup window (requires tmux 3.2462-or above) by putting `--tmux` option value in `tmux` key.461+Alternatively, you can make fzf open in a popup window (requires tmux 3.3 or462+above, or Zellij 0.44 or above) by putting `--popup` option value in `popup`463+key. `tmux` is accepted as a synonym, just as `--tmux` is an alias of464+`--popup`.465 466 ```vim465-" See `--tmux` option in `man fzf` for available options467+" See `--popup` option in `man fzf` for available options468 " [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]]467-if exists('$TMUX')468- let g:fzf_layout = { 'tmux': '90%,70%' }469+if exists('$TMUX') || exists('$ZELLIJ')470+ let g:fzf_layout = { 'popup': '90%,70%' }471 else472 let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6 } }473 endif474 ```24 unmodified lines