Skip to content
Myr

fzf.vim

This file

Path

plugin/fzf.vim

1,321 lines · 39.8 KiB

Last changed by

[vim] Open fzf in a tmux or Zellij floating pane by default (#4905)Junegunn Choibefore adoptiona52ac84

History of this file

Take it

1" Copyright (c) 2013-2026 Junegunn Choi2"3" MIT License4"5" Permission is hereby granted, free of charge, to any person obtaining6" a copy of this software and associated documentation files (the7" "Software"), to deal in the Software without restriction, including8" without limitation the rights to use, copy, modify, merge, publish,9" distribute, sublicense, and/or sell copies of the Software, and to10" permit persons to whom the Software is furnished to do so, subject to11" the following conditions:12"13" The above copyright notice and this permission notice shall be14" included in all copies or substantial portions of the Software.15"16" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,17" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF18" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND19" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE20" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION21" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION22" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.2324if exists('g:loaded_fzf')25  finish26endif27" Bumped when the plugin gains behavior a caller may need to detect28let g:loaded_fzf = 202608212930let s:is_win = has('win32') || has('win64')31if s:is_win && &shellslash32  set noshellslash33  let s:base_dir = expand('<sfile>:h:h')34  set shellslash35else36  let s:base_dir = expand('<sfile>:h:h')37endif38if s:is_win39  let s:term_marker = '&::FZF'4041  function! s:fzf_call(fn, ...)42    let shellslash = &shellslash43    try44      set noshellslash45      return call(a:fn, a:000)46    finally47      let &shellslash = shellslash48    endtry49  endfunction5051  " Use utf-8 for fzf.vim commands52  " Return array of shell commands for cmd.exe53  function! s:enc_to_cp(str)54    if !has('iconv')55      return a:str56    endif57    if !exists('s:codepage')58      let s:codepage = libcallnr('kernel32.dll', 'GetACP', 0)59    endif60    return iconv(a:str, &encoding, 'cp'.s:codepage)61  endfunction62  function! s:wrap_cmds(cmds)63    return map(['@echo off']64    \ + (has('gui_running') ? ['set TERM= > nul'] : [])65    \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds]),66    \ '<SID>enc_to_cp(v:val."\r")')67  endfunction68else69  let s:term_marker = ";#FZF"7071  function! s:fzf_call(fn, ...)72    return call(a:fn, a:000)73  endfunction7475  function! s:wrap_cmds(cmds)76    return a:cmds77  endfunction7879  function! s:enc_to_cp(str)80    return a:str81  endfunction82endif8384function! s:shellesc_cmd(arg)85  let e = '"'86  let slashes = 087  for c in split(a:arg, '\zs')88    if c ==# '\'89      let slashes += 190    elseif c ==# '"'91      let e .= repeat('\', slashes + 1)92      let slashes = 093    else94      let slashes = 095    endif96    let e .= c97  endfor98  let e .= repeat('\', slashes) .'"'99  return substitute(substitute(e, '[&|<>()^!"]', '^&', 'g'), '%', '%%', 'g')100endfunction101102function! fzf#shellescape(arg, ...)103  let shell = get(a:000, 0, s:is_win ? 'cmd.exe' : 'sh')104  if shell =~# 'cmd.exe$'105    return s:shellesc_cmd(a:arg)106  endif107  try108    let [shell, &shell] = [&shell, shell]109    return s:fzf_call('shellescape', a:arg)110  finally111    let [shell, &shell] = [&shell, shell]112  endtry113endfunction114115function! s:fzf_getcwd()116  return s:fzf_call('getcwd')117endfunction118119function! s:fzf_fnamemodify(fname, mods)120  return s:fzf_call('fnamemodify', a:fname, a:mods)121endfunction122123function! s:fzf_expand(fmt)124  return s:fzf_call('expand', a:fmt, 1)125endfunction126127function! s:fzf_tempname()128  return s:fzf_call('tempname')129endfunction130131let s:layout_keys = ['window', 'popup', 'tmux', 'up', 'down', 'left', 'right']132let s:fzf_go = s:base_dir.'/bin/fzf'133let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'134135let s:cpo_save = &cpo136set cpo&vim137138function! s:popup_support()139  return has('nvim') ? has('nvim-0.4') : has('popupwin') && has('patch-8.2.191')140endfunction141142function! s:default_layout()143  " A floating pane leaves the window fzf was started from visible and144  " reachable while fzf is open. A popup covers it, inside Vim or not.145  " Without a job, s:execute_tmux() blocks and freezes Vim. fzf also wants a146  " tmux window of at least 3x3, and Vim's pane is never larger than the147  " window, so asking Vim is free and survives a resize148  if (has('nvim') || has('job')) && &columns >= 3 && &lines >= 3149        \ && s:tmux_enabled() && get(s:, 'tmux_floating', 0)150    return { 'tmux': '90%,60%' }151  endif152  return s:popup_support()153        \ ? { 'window' : { 'width': 0.9, 'height': 0.6 } }154        \ : { 'down': '~40%' }155endfunction156157function! fzf#install()158  if s:is_win && !has('win32unix')159    let script = s:base_dir.'/install.ps1'160    if !filereadable(script)161      throw script.' not found'162    endif163    let script = 'powershell -ExecutionPolicy Bypass -file ' . shellescape(script)164  else165    let script = s:base_dir.'/install'166    if !executable(script)167      throw script.' not found'168    endif169    let script .= ' --bin'170  endif171172  call s:warn('Running fzf installer ...')173  call system(script)174  if v:shell_error175    throw 'Failed to download fzf: '.script176  endif177178  " A new binary invalidates the chosen executable and everything derived from179  " its version, including whether fzf opens a floating pane. fzf#install() is180  " also the vim-plug 'do' hook, so this can run long after the first fzf call181  let [s:versions, s:checked] = [{}, {}]182  unlet! s:exec s:tmux s:tmux_floating183endfunction184185let s:versions = {}186function s:get_version(bin)187  if has_key(s:versions, a:bin)188    return s:versions[a:bin]189  end190  let command = (&shell =~ 'powershell\|pwsh' ? '&' : '') . s:fzf_call('shellescape', a:bin) . ' --version --no-height'191  let output = systemlist(command)192  if v:shell_error || empty(output)193    return ''194  endif195  let ver = matchstr(output[-1], '[0-9.]\+')196  let s:versions[a:bin] = ver197  return ver198endfunction199200function! s:compare_versions(a, b)201  let a = split(a:a, '\.')202  let b = split(a:b, '\.')203  for idx in range(0, max([len(a), len(b)]) - 1)204    let v1 = str2nr(get(a, idx, 0))205    let v2 = str2nr(get(b, idx, 0))206    if     v1 < v2 | return -1207    elseif v1 > v2 | return 1208    endif209  endfor210  return 0211endfunction212213function! s:compare_binary_versions(a, b)214  return s:compare_versions(s:get_version(a:a), s:get_version(a:b))215endfunction216217let s:min_version = '0.53.0'218let s:checked = {}219function! fzf#exec(...)220  if !exists('s:exec')221    let binaries = []222    if executable('fzf')223      call add(binaries, 'fzf')224    endif225    if executable(s:fzf_go)226      call add(binaries, s:fzf_go)227    endif228229    if empty(binaries)230      if input('fzf executable not found. Download binary? (y/n) ') =~? '^y'231        redraw232        call fzf#install()233        return fzf#exec()234      else235        redraw236        throw 'fzf executable not found'237      endif238    elseif len(binaries) > 1239      call sort(binaries, 's:compare_binary_versions')240    endif241242    let s:exec = binaries[-1]243  endif244245  let min_version = s:min_version246  if a:0 && s:compare_versions(a:1, min_version) > 0247    let min_version = a:1248  endif249  if !has_key(s:checked, min_version)250    let fzf_version = s:get_version(s:exec)251    if empty(fzf_version)252      let message = printf('Failed to run "%s --version"', s:exec)253      unlet s:exec254      throw message255    end256257    if s:compare_versions(fzf_version, min_version) >= 0258      let s:checked[min_version] = 1259      return s:exec260    elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', min_version, fzf_version)) =~? '^y'261      let s:versions = {}262      unlet s:exec263      redraw264      call fzf#install()265      return fzf#exec(min_version, 1)266    else267      throw printf('You need to upgrade fzf (required: %s or above)', min_version)268    endif269  endif270271  return s:exec272endfunction273274" Path to the fzf-tmux script, or an empty string if it is not available. Only275" the legacy options still need it. --popup is handled by fzf itself.276function! s:fzf_tmux_script()277  if !executable(s:fzf_tmux)278    if !executable('fzf-tmux')279      return ''280    endif281    let s:fzf_tmux = 'fzf-tmux'282  endif283  return s:fzf_tmux284endfunction285286function! s:tmux_enabled()287  if has('gui_running')288    return 0289  endif290291  if empty($TMUX) && empty($ZELLIJ)292    return 0293  endif294295  if exists('s:tmux')296    return s:tmux297  endif298299  let [s:tmux, s:tmux_floating] = [0, 0]300301  " --popup covers Zellij as well, where the fzf-tmux script and the tmux302  " version are irrelevant. fzf learned it in 0.71.0, and the floating pane303  " options it passes need Zellij 0.44 or above. fzf checks tmux first, so304  " this branch is Zellij without tmux. Both non-empty means tmux wins.305  " empty(), not exists(), to match how fzf reads the two variables306  if empty($TMUX)307    let s:tmux =308          \ s:compare_versions(s:get_version(s:fzf_binary()), '0.71.0') >= 0309          \ && s:compare_versions(s:zellij_version(), '0.44') >= 0310    let s:tmux_floating = s:tmux311    return s:tmux312  endif313314  let output = system('tmux -V')315  if v:shell_error316    return s:tmux317  endif318  " e.g. 'tmux 3.7b', 'tmux next-3.8'319  let ver = matchstr(output, '\d\+\.\d\+')320321  " --popup requires tmux 3.3 or above, and needs no fzf-tmux script. The322  " default layout wants a floating pane, which also needs fzf 0.74.0 or323  " above. fzf opens a modal popup otherwise. The version here only skips the324  " probe for servers too old to answer it325  if s:compare_versions(ver, '3.3') >= 0326    let s:tmux = 1327    let s:tmux_floating = s:compare_versions(ver, '3.7') >= 0328          \ && s:tmux_floating_pane_support()329          \ && s:compare_versions(s:get_version(s:fzf_binary()), '0.74.0') >= 0330    return s:tmux331  endif332333  " Older versions still go through the script334  let s:tmux = !empty(s:fzf_tmux_script()) && s:compare_versions(ver, '1.7') >= 0335  return s:tmux336endfunction337338function! s:escape(path)339  let path = fnameescape(a:path)340  return s:is_win ? escape(path, '$') : path341endfunction342343function! s:error(msg)344  echohl ErrorMsg345  echom a:msg346  echohl None347endfunction348349function! s:warn(msg)350  echohl WarningMsg351  echom a:msg352  echohl None353endfunction354355function! s:has_any(dict, keys)356  for key in a:keys357    if has_key(a:dict, key)358      return 1359    endif360  endfor361  return 0362endfunction363364function! s:open(cmd, target)365  if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')366    return367  endif368  execute a:cmd s:escape(a:target)369endfunction370371function! s:common_sink(action, lines) abort372  if len(a:lines) < 2373    return374  endif375  let key = remove(a:lines, 0)376  let Cmd = get(a:action, key, 'e')377  if type(Cmd) == type(function('call'))378    return Cmd(a:lines)379  endif380  if len(a:lines) > 1381    augroup fzf_swap382      autocmd SwapExists * let v:swapchoice='o'383            \| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))384    augroup END385  endif386  try387    let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified388    " Preserve the current working directory in case it's changed during389    " the execution (e.g. `set autochdir` or `autocmd BufEnter * lcd ...`)390    let cwd = exists('w:fzf_pushd') ? w:fzf_pushd.dir : expand('%:p:h')391    for item in a:lines392      if has('win32unix') && item !~ '/'393        let item = substitute(item, '\', '/', 'g')394      end395      if item[0] != '~' && item !~ (s:is_win ? '^\([A-Z]:\)\?\' : '^/')396        let sep = s:is_win ? '\' : '/'397        let item = join([cwd, item], cwd[len(cwd)-1] == sep ? '' : sep)398      endif399      if empty400        execute 'e' s:escape(item)401        let empty = 0402      else403        call s:open(Cmd, item)404      endif405      if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')406            \ && isdirectory(item)407        doautocmd BufEnter408      endif409    endfor410  catch /^Vim:Interrupt$/411  finally412    silent! autocmd! fzf_swap413  endtry414endfunction415416function! s:get_color(attr, ...)417  " Force 24 bit colors: g:fzf_force_termguicolors (temporary workaround for https://github.com/junegunn/fzf.vim/issues/1152)418  let gui = get(g:, 'fzf_force_termguicolors', 0) || (!s:is_win && !has('win32unix') && (has('gui_running') || has('termguicolors') && &termguicolors))419  let fam = gui ? 'gui' : 'cterm'420  let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'421  for group in a:000422    let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)423    if code =~? pat424      return code425    endif426  endfor427  return ''428endfunction429430function! s:defaults()431  let rules = copy(get(g:, 'fzf_colors', {}))432  let colors = join(map(items(filter(map(rules, 'call("s:get_color", v:val)'), '!empty(v:val)')), 'join(v:val, ":")'), ',')433  return empty(colors) ? '' : fzf#shellescape('--color='.colors)434endfunction435436function! s:validate_layout(layout)437  for key in keys(a:layout)438    if index(s:layout_keys, key) < 0439      throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',440            \ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')441    endif442  endfor443  return a:layout444endfunction445446function! s:evaluate_opts(options)447  return type(a:options) == type([]) ?448        \ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options449endfunction450451" [name string,] [opts dict,] [fullscreen boolean]452function! fzf#wrap(...)453  let args = ['', {}, 0]454  let expects = map(copy(args), 'type(v:val)')455  let tidx = 0456  for arg in copy(a:000)457    let tidx = index(expects, type(arg) == 6 ? type(0) : type(arg), tidx)458    if tidx < 0459      throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'460    endif461    let args[tidx] = arg462    let tidx += 1463    unlet arg464  endfor465  let [name, opts, bang] = args466467  if len(name)468    let opts.name = name469  end470471  " Layout: g:fzf_layout (and deprecated g:fzf_height)472  if bang473    for key in s:layout_keys474      if has_key(opts, key)475        call remove(opts, key)476      endif477    endfor478  elseif !s:has_any(opts, s:layout_keys)479    if !exists('g:fzf_layout') && exists('g:fzf_height')480      let opts.down = g:fzf_height481    else482      " Not get(), which would evaluate s:default_layout() and run its version483      " checks even when g:fzf_layout makes the answer irrelevant484      let opts = extend(opts, s:validate_layout(485            \ exists('g:fzf_layout') ? g:fzf_layout : s:default_layout()))486    endif487  endif488489  " Colors: g:fzf_colors490  let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))491492  " History: g:fzf_history_dir493  if len(name) && len(get(g:, 'fzf_history_dir', ''))494    let dir = s:fzf_expand(g:fzf_history_dir)495    if !isdirectory(dir)496      call mkdir(dir, 'p')497    endif498    let history = fzf#shellescape(dir.'/'.name)499    let opts.options = join(['--history', history, opts.options])500  endif501502  " Action: g:fzf_action503  if !s:has_any(opts, ['sink', 'sinklist', 'sink*'])504    let opts._action = get(g:, 'fzf_action', s:default_action)505    let opts.options .= ' --expect='.join(keys(opts._action), ',')506    function! opts.sinklist(lines) abort507      return s:common_sink(self._action, a:lines)508    endfunction509    let opts['sink*'] = opts.sinklist " For backward compatibility510  endif511512  return opts513endfunction514515function! s:use_sh()516  let [shell, shellslash, shellcmdflag, shellxquote] = [&shell, &shellslash, &shellcmdflag, &shellxquote]517  if s:is_win518    set shell=cmd.exe519    set noshellslash520    let &shellcmdflag = has('nvim') ? '/s /c' : '/c'521    let &shellxquote = has('nvim') ? '"' : '('522  else523    set shell=sh524  endif525  return [shell, shellslash, shellcmdflag, shellxquote]526endfunction527528function! s:writefile(...)529  if call('writefile', a:000) == -1530    throw 'Failed to write temporary file. Check if you can write to the path tempname() returns.'531  endif532endfunction533534function! s:extract_option(opts, name)535  let opt = ''536  let expect = 0537  " There are a few cases where this function doesn't work as expected.538  " Let's just assume such cases are extremely unlikely in real world.539  "   e.g. --query --border540  for word in split(a:opts)541    if expect && word !~ '^"\=-'542      let opt = opt . ' ' . word543      let expect = 0544    elseif word == '--no-'.a:name545      let opt = ''546    elseif word =~ '^--'.a:name.'='547      let opt = word548    elseif word =~ '^--'.a:name.'$'549      let opt = word550      let expect = 1551    elseif expect552      let expect = 0553    endif554  endfor555  return opt556endfunction557558let s:need_cmd_window = has('win32unix') && $TERM_PROGRAM ==# 'mintty' && s:compare_versions($TERM_PROGRAM_VERSION, '3.4.5') < 0 && !executable('winpty')559560function! fzf#run(...) abort561try562  let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()563564  let dict   = exists('a:1') ? copy(a:1) : {}565  " 'popup' and 'tmux' are synonyms, as --popup and --tmux are. Normalize here566  " so that the rest of the function only has to know about one of them.567  if has_key(dict, 'popup')568    let dict.tmux = remove(dict, 'popup')569  endif570  let temps  = { 'result': s:fzf_tempname() }571  let optstr = s:evaluate_opts(get(dict, 'options', ''))572  try573    let fzf_exec = shellescape(fzf#exec())574  catch575    throw v:exception576  endtry577578  if !s:present(dict, 'dir')579    let dict.dir = s:fzf_getcwd()580  endif581  if has('win32unix') && s:present(dict, 'dir')582    let dict.dir = fnamemodify(dict.dir, ':p')583  endif584585  if has_key(dict, 'source')586    let source = dict.source587    let type = type(source)588    if type == 1589      let prefix = '('.source.')|'590    elseif type == 3591      let temps.input = s:fzf_tempname()592      call s:writefile(source, temps.input)593      let prefix = (s:is_win ? 'type ' : 'command cat ').fzf#shellescape(temps.input).'|'594    else595      throw 'Invalid source type'596    endif597  else598    let prefix = ''599  endif600601  let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')602  let use_height = has_key(dict, 'down') && !has('gui_running') &&603        \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&604        \ executable('tput') && filereadable('/dev/tty')605  let has_vim8_term = has('terminal') && has('patch-8.0.995')606  let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win607  let use_term = (has_nvim_term || has_vim8_term) && !s:need_cmd_window608  let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()609  if prefer_tmux && use_tmux610    let use_height = 0611    let use_term = 0612  endif613  if use_term614    let optstr .= ' --no-height'615    " Cancel a --popup from $FZF_DEFAULT_OPTS only when the spec asks for a Vim616    " window. Without a layout option, respect the user's preference.617    if s:present(dict, 'window', 'up', 'down', 'left', 'right')618      let optstr .= ' --no-tmux'619    endif620  elseif use_height621    let height = s:calc_size(&lines, dict.down, dict)622    let optstr .= ' --no-tmux --height='.height623  endif624625  if exists('&winborder') && &winborder !=# '' && &winborder !=# 'none'626    " Add 1-column horizontal margin627    let optstr = join(['--margin 0,1', optstr])628  else629    " Respect --border option given in $FZF_DEFAULT_OPTS and 'options'630    let optstr = join([s:border_opt(get(dict, 'window', 0)), s:extract_option($FZF_DEFAULT_OPTS, 'border'), optstr])631  endif632633  let command = prefix.(use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result634635  if use_term636    return s:execute_term(dict, command, temps)637  endif638639  " s:execute_tmux may run fzf asynchronously, so it calls s:callback itself640  if use_tmux641    return s:execute_tmux(dict, command, temps)642  endif643644  let lines = s:execute(dict, command, use_height, temps)645  call s:callback(dict, lines)646  return lines647finally648  let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]649endtry650endfunction651652function! s:present(dict, ...)653  for key in a:000654    if !empty(get(a:dict, key, ''))655      return 1656    endif657  endfor658  return 0659endfunction660661" The binary fzf#exec() would choose, without its prompting or installing.662" Layout selection runs before fzf#exec() has resolved one663function! s:fzf_binary()664  if exists('s:exec')665    return s:exec666  endif667  let bins = filter(['fzf', s:fzf_go], 'executable(v:val)')668  if empty(bins)669    return ''670  endif671  return len(bins) > 1 ? sort(bins, 's:compare_binary_versions')[-1] : bins[0]672endfunction673674function! s:zellij_version()675  if !exists('s:zellij_ver')676    let output = systemlist('zellij --version')677    let s:zellij_ver = v:shell_error || empty(output)678          \ ? '' : matchstr(output[0], '[0-9.]\+')679  endif680  return s:zellij_ver681endfunction682683" Whether the running server can put fzf in a floating pane. fzf decides on684" the server, not on the version the tmux client reports, so ask it the same685" question rather than predicting the answer. See tmuxFloatingPaneInfo in686" src/tmux.go, which also requires the tmux window to be at least 3x3; that687" one changes with a resize, so s:default_layout() reads it from Vim instead688" of caching it here689function! s:tmux_floating_pane_support()690  " fzf does not use a floating pane when it was not started from a pane691  if empty($TMUX_PANE)692    return 0693  endif694  let out = system('tmux list-commands new-pane')695  " A server that does not know the command exits normally with no output696  return !v:shell_error && out =~# 'new-pane'697endfunction698699function! s:fzf_tmux(dict)700  let size = get(a:dict, 'tmux', '')701  if empty(size)702    for o in ['up', 'down', 'left', 'right']703      if s:present(a:dict, o)704        let size = o . ',' . a:dict[o]705        break706      endif707    endfor708  endif709710  " Legacy fzf-tmux options are flags. A --tmux value never starts with a dash,711  " but may contain one, as in '90%,60%,border-native'712  if size =~ '^-'713    let script = s:fzf_tmux_script()714    if empty(script)715      throw 'fzf-tmux not found, required for the legacy option: ' . size716    endif717    return printf('LINES=%d COLUMNS=%d %s %s %s --',718          \ &lines, &columns, fzf#shellescape(script), size, (has_key(a:dict, 'source') ? '' : '-'))719  end720721  " Using native --tmux option722  let in = (has_key(a:dict, 'source') ? '' : ' --force-tty-in')723  return printf('%s --tmux %s%s', fzf#shellescape(fzf#exec()), size, in)724endfunction725726function! s:splittable(dict)727  return s:present(a:dict, 'up', 'down') && &lines > 15 ||728        \ s:present(a:dict, 'left', 'right') && &columns > 40729endfunction730731function! s:pushd(dict)732  if s:present(a:dict, 'dir')733    let cwd = s:fzf_getcwd()734    let w:fzf_pushd = {735    \   'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),736    \   'origin': cwd,737    \   'bufname': bufname('')738    \ }739    execute 'lcd' s:escape(a:dict.dir)740    let cwd = s:fzf_getcwd()741    let w:fzf_pushd.dir = cwd742    let a:dict.pushd = w:fzf_pushd743    return cwd744  endif745  return ''746endfunction747748augroup fzf_popd749  autocmd!750  autocmd WinEnter * call s:dopopd()751augroup END752753function! s:dopopd()754  if !exists('w:fzf_pushd')755    return756  endif757758  " FIXME: We temporarily change the working directory to 'dir' entry759  " of options dictionary (set to the current working directory if not given)760  " before running fzf.761  "762  " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})763  "764  " After processing the sink function, we have to restore the current working765  " directory. But doing so may not be desirable if the function changed the766  " working directory on purpose.767  "768  " So how can we tell if we should do it or not? A simple heuristic we use769  " here is that we change directory only if the current working directory770  " matches 'dir' entry. However, it is possible that the sink function did771  " change the directory to 'dir'. In that case, the user will have an772  " unexpected result.773  if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))774    execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)775  endif776  unlet! w:fzf_pushd777endfunction778779function! s:xterm_launcher()780  let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'781  if has('gui_macvim')782    let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'783  endif784  return printf(fmt,785    \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),786    \ &columns, &lines/2, getwinposx(), getwinposy())787endfunction788unlet! s:launcher789if s:is_win || has('win32unix')790  let s:launcher = '%s'791else792  let s:launcher = function('s:xterm_launcher')793endif794795function! s:exit_handler(dict, code, command, ...)796  if has_key(a:dict, 'exit')797    call a:dict.exit(a:code)798  endif799  if a:code == 2800    call s:error('Error running ' . a:command)801    if !empty(a:000)802      sleep803    endif804  endif805  return a:code806endfunction807808function! s:execute(dict, command, use_height, temps) abort809  call s:pushd(a:dict)810  if has('unix') && !a:use_height811    silent! !clear 2> /dev/null812  endif813  let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')814  if has('gui_running')815    let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))816    let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher817    if has('unix')818      let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"819    endif820    let command = printf(fmt, escaped)821  else822    let command = escaped823  endif824  if s:is_win825    let batchfile = s:fzf_tempname().'.bat'826    call s:writefile(s:wrap_cmds(command), batchfile)827    let command = batchfile828    let a:temps.batchfile = batchfile829    if has('nvim')830      let fzf = {}831      let fzf.dict = a:dict832      let fzf.temps = a:temps833      function! fzf.on_exit(job_id, exit_status, event) dict834        call s:pushd(self.dict)835        let lines = s:collect(self.temps)836        call s:callback(self.dict, lines)837      endfunction838      let cmd = 'start /wait cmd /c '.command839      call jobstart(cmd, fzf)840      return []841    endif842  elseif s:need_cmd_window843    let shellscript = s:fzf_tempname()844    call s:writefile([command], shellscript)845    let command = 'start //WAIT sh -c '.shellscript846    let a:temps.shellscript = shellscript847  endif848  if a:use_height849    let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'850    call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))851  else852    execute 'silent !'.command853  endif854  let exit_status = v:shell_error855  redraw!856  let lines = s:collect(a:temps)857  return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []858endfunction859860" Returns 0 if the job could not be started861function! s:start_popup_job(dict, command, temps) abort862  let fzf = { 'dict': a:dict, 'temps': a:temps, 'command': a:command }863  " Vim passes (job, status) and Nvim (id, status, event)864  function! fzf.on_exit(id, code, ...) abort865    redraw!866    let lines = s:collect(self.temps)867    if s:exit_handler(self.dict, a:code, self.command, 1) >= 2868      return869    endif870    call s:pushd(self.dict)871    call s:callback(self.dict, lines)872  endfunction873874  if has('nvim')875    return jobstart([&shell, &shellcmdflag, a:command], fzf) > 0876  endif877878  " The command redirects to the result file, so no stream is of interest879  let opts = { 'exit_cb': function(fzf.on_exit),880        \ 'in_io': 'null', 'out_io': 'null', 'err_io': 'null' }881882  " job_start() gives the child $TERM=dumb, and the popup inherits the883  " environment from here, so fzf would lose its colors. 'env' was added in884  " 8.0.902, so set it in the command itself on older versions.885  let command = a:command886  if has('patch-8.0.902')887    let opts.env = { 'TERM': $TERM }888  elseif !s:is_win889    let command = join(['export TERM=' . fzf#shellescape($TERM) . ';', command])890  endif891892  let job = job_start([&shell, &shellcmdflag, command], opts)893  return job_status(job) !=# 'fail'894endfunction895896function! s:execute_tmux(dict, command, temps) abort897  let command = a:command898  let cwd = s:pushd(a:dict)899  if len(cwd)900    " -c '#{pane_current_path}' is only available on tmux 1.9 or above901    let command = join(['cd', fzf#shellescape(cwd), '&&', command])902  endif903904  " fzf draws in a pane of its own, so the process we start here only waits for905  " it. Hold it with a job instead of system() so that Vim keeps processing its906  " event loop, and nothing has to be displayed for it. Fall back to the907  " blocking path when the job cannot be started, or the sink would never run908  " and the temporary files would be left behind.909  if (has('nvim') || has('job')) && s:start_popup_job(a:dict, command, a:temps)910    " Restore the working directory while fzf runs. on_exit pushes it again911    call s:dopopd()912    return []913  endif914915  call system(command)916  let exit_status = v:shell_error917  redraw!918  let lines = s:collect(a:temps)919  let lines = s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []920  call s:callback(a:dict, lines)921  return lines922endfunction923924function! s:calc_size(max, val, dict)925  let val = substitute(a:val, '^\~', '', '')926  if val =~ '%$'927    let size = a:max * str2nr(val[:-2]) / 100928  else929    let size = min([a:max, str2nr(val)])930  endif931932  let srcsz = -1933  if type(get(a:dict, 'source', 0)) == type([])934    let srcsz = len(a:dict.source)935  endif936937  let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))938  if opts =~ 'preview'939    return size940  endif941  let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2942  let margin += match(opts, '--border\([^-]\|$\)') > match(opts, '--no-border\([^-]\|$\)') ? 2 : 0943  if stridx(opts, '--header') > stridx(opts, '--no-header')944    let margin += len(split(opts, "\n"))945  endif946  return srcsz >= 0 ? min([srcsz + margin, size]) : size947endfunction948949function! s:getpos()950  return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}951endfunction952953function! s:border_opt(window)954  if type(a:window) != type({})955    return ''956  endif957958  " Border style959  let style = tolower(get(a:window, 'border', ''))960  if !has_key(a:window, 'border') && has_key(a:window, 'rounded')961    let style = a:window.rounded ? 'rounded' : 'sharp'962  endif963  if style == 'none' || style == 'no'964    return ''965  endif966967  " For --border styles, we need fzf 0.24.0 or above968  call fzf#exec('0.24.0')969  let opt = ' --border ' . style970  if has_key(a:window, 'highlight')971    let color = s:get_color('fg', a:window.highlight)972    if len(color)973      let opt .= ' --color=border:' . color974    endif975  endif976  return opt977endfunction978979function! s:split(dict)980  let directions = {981  \ 'up':    ['topleft', 'resize', &lines],982  \ 'down':  ['botright', 'resize', &lines],983  \ 'left':  ['vertical topleft', 'vertical resize', &columns],984  \ 'right': ['vertical botright', 'vertical resize', &columns] }985  let ppos = s:getpos()986  let is_popup = 0987  try988    if s:present(a:dict, 'window')989      if type(a:dict.window) == type({})990        if !s:popup_support()991          throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'992        end993        call s:popup(a:dict.window)994        let is_popup = 1995      else996        execute 'keepalt' a:dict.window997      endif998    elseif !s:splittable(a:dict)999      execute (tabpagenr()-1).'tabnew'1000    else1001      for [dir, triple] in items(directions)1002        let val = get(a:dict, dir, '')1003        if !empty(val)1004          let [cmd, resz, max] = triple1005          if (dir == 'up' || dir == 'down') && val[0] == '~'1006            let sz = s:calc_size(max, val, a:dict)1007          else1008            let sz = s:calc_size(max, val, {})1009          endif1010          execute cmd sz.'new'1011          execute resz sz1012          return [ppos, {}, is_popup]1013        endif1014      endfor1015    endif1016    return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]1017  finally1018    if !is_popup1019      setlocal winfixwidth winfixheight1020    endif1021  endtry1022endfunction10231024nnoremap <silent> <Plug>(fzf-insert) i1025nnoremap <silent> <Plug>(fzf-normal) <Nop>1026if exists(':tnoremap')1027  tnoremap <silent> <Plug>(fzf-insert) <C-\><C-n>i1028  tnoremap <silent> <Plug>(fzf-normal) <C-\><C-n>1029endif10301031let s:warned = 01032function! s:handle_ambidouble(dict)1033  if &ambiwidth == 'double'1034    let a:dict.env = { 'RUNEWIDTH_EASTASIAN': '1' }1035  elseif !s:warned && $RUNEWIDTH_EASTASIAN == '1' && &ambiwidth !=# 'double'1036    call s:warn("$RUNEWIDTH_EASTASIAN is '1' but &ambiwidth is not 'double'")1037    2sleep1038    let s:warned = 11039  endif1040endfunction10411042function! s:execute_term(dict, command, temps) abort1043  let winrest = winrestcmd()1044  let pbuf = bufnr('')1045  let [ppos, winopts, is_popup] = s:split(a:dict)1046  call s:use_sh()1047  let b:fzf = a:dict1048  let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,1049            \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,1050            \ 'columns': &columns, 'command': a:command }1051  function! fzf.switch_back(inplace)1052    if a:inplace && bufnr('') == self.buf1053      if bufexists(self.pbuf)1054        execute 'keepalt keepjumps b' self.pbuf1055      endif1056      " No other listed buffer1057      if bufnr('') == self.buf1058        enew1059      endif1060    endif1061  endfunction1062  function! fzf.on_exit(id, code, ...)1063    silent! autocmd! fzf_popup_resize1064    if s:getpos() == self.ppos " {'window': 'enew'}1065      for [opt, val] in items(self.winopts)1066        execute 'let' opt '=' val1067      endfor1068      call self.switch_back(1)1069    else1070      if bufnr('') == self.buf1071        " We use close instead of bd! since Vim does not close the split when1072        " there's no other listed buffer (nvim +'set nobuflisted')1073        close1074      endif1075      silent! execute 'tabnext' self.ppos.tab1076      silent! execute self.ppos.win.'wincmd w'1077    endif10781079    if bufexists(self.buf)1080      execute 'bd!' self.buf1081    endif10821083    if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos1084      execute self.winrest1085    endif10861087    let lines = s:collect(self.temps)1088    if s:exit_handler(self.dict, a:code, self.command, 1) >= 21089      return1090    endif10911092    call s:pushd(self.dict)1093    call s:callback(self.dict, lines)1094    call self.switch_back(s:getpos() == self.ppos)10951096    if &buftype == 'terminal'1097      call feedkeys(&filetype == 'fzf' ? "\<Plug>(fzf-insert)" : "\<Plug>(fzf-normal)")1098    endif1099  endfunction11001101  try1102    call s:pushd(a:dict)1103    if s:is_win1104      let fzf.temps.batchfile = s:fzf_tempname().'.bat'1105      call s:writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)1106      let command = fzf.temps.batchfile1107    else1108      let command = a:command1109    endif1110    let command .= s:term_marker1111    if has('nvim')1112      call s:handle_ambidouble(fzf)1113      call termopen(command, fzf)1114    else1115      let term_opts = {'exit_cb': function(fzf.on_exit)}1116      if v:version >= 8021117        let term_opts.term_kill = 'term'1118      endif1119      if is_popup1120        let term_opts.hidden = 11121      else1122        let term_opts.curwin = 11123      endif1124      call s:handle_ambidouble(term_opts)1125      keepjumps let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)1126      if is_popup && exists('#TerminalWinOpen')1127        doautocmd <nomodeline> TerminalWinOpen1128      endif1129      if !has('patch-8.0.1261') && !s:is_win1130        call term_wait(fzf.buf, 20)1131      endif1132    endif1133    tnoremap <buffer> <c-z> <nop>1134    if exists('&termwinkey') && (empty(&termwinkey) || &termwinkey =~? '<c-w>')1135      tnoremap <buffer> <c-w> <c-w>.1136    endif1137  finally1138    call s:dopopd()1139  endtry1140  setlocal nospell bufhidden=wipe nobuflisted nonumber1141  setf fzf1142  startinsert1143  return []1144endfunction11451146function! s:collect(temps) abort1147  try1148    return filereadable(a:temps.result) ? readfile(a:temps.result) : []1149  finally1150    for tf in values(a:temps)1151      silent! call delete(tf)1152    endfor1153  endtry1154endfunction11551156function! s:callback(dict, lines) abort1157  let popd = has_key(a:dict, 'pushd')1158  if popd1159    let w:fzf_pushd = a:dict.pushd1160  endif11611162  try1163    if has_key(a:dict, 'sink')1164      for line in a:lines1165        if type(a:dict.sink) == 21166          call a:dict.sink(line)1167        else1168          execute a:dict.sink s:escape(line)1169        endif1170      endfor1171    endif1172    if has_key(a:dict, 'sink*')1173      call a:dict['sink*'](a:lines)1174    elseif has_key(a:dict, 'sinklist')1175      call a:dict['sinklist'](a:lines)1176    endif1177  catch1178    if stridx(v:exception, ':E325:') < 01179      echoerr v:exception1180    endif1181  endtry11821183  " We may have opened a new window or tab1184  if popd1185    let w:fzf_pushd = a:dict.pushd1186    call s:dopopd()1187  endif1188endfunction11891190if has('nvim')1191  function! s:create_popup() abort1192    let opts = s:popup_bounds()1193    let opts = extend({'relative': 'editor', 'style': 'minimal'}, opts)11941195    let buf = nvim_create_buf(v:false, v:true)1196    let s:popup_id = nvim_open_win(buf, v:true, opts)1197    call setwinvar(s:popup_id, '&colorcolumn', '')11981199    " Colors1200    try1201      call setwinvar(s:popup_id, '&winhighlight', 'Pmenu:,Normal:Normal')1202      let rules = get(g:, 'fzf_colors', {})1203      if has_key(rules, 'bg')1204        let color = call('s:get_color', rules.bg)1205        if len(color)1206          let ns = nvim_create_namespace('fzf_popup')1207          let hl = nvim_set_hl(ns, 'Normal',1208                \ &termguicolors ? { 'bg': color } : { 'ctermbg': str2nr(color) })1209          call nvim_win_set_hl_ns(s:popup_id, ns)1210        endif1211      endif1212    catch1213    endtry1214    return buf1215  endfunction12161217  function! s:resize_popup() abort1218    if !exists('s:popup_id') || !nvim_win_is_valid(s:popup_id)1219      return1220    endif1221    let opts = s:popup_bounds()1222    let opts = extend({'relative': 'editor'}, opts)1223    call nvim_win_set_config(s:popup_id, opts)1224  endfunction1225else1226  function! s:create_popup() abort1227    function! s:popup_create(buf)1228      let s:popup_id = popup_create(a:buf, #{zindex: 1000})1229      call s:resize_popup()1230    endfunction1231    autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))1232  endfunction12331234  function! s:resize_popup() abort1235    if !exists('s:popup_id') || empty(popup_getpos(s:popup_id))1236      return1237    endif1238    let opts = s:popup_bounds()1239    call popup_move(s:popup_id, {1240      \ 'line': opts.row,1241      \ 'col': opts.col,1242      \ 'minwidth': opts.width,1243      \ 'maxwidth': opts.width,1244      \ 'minheight': opts.height,1245      \ 'maxheight': opts.height,1246    \ })1247  endfunction1248endif12491250function! s:popup_bounds() abort1251  let opts = s:popup_opts12521253  let xoffset = get(opts, 'xoffset', 0.5)1254  let yoffset = get(opts, 'yoffset', 0.5)1255  let relative = get(opts, 'relative', 0)12561257  " Use current window size for positioning relatively positioned popups1258  let columns = relative ? winwidth(0) : &columns1259  let lines = relative ? winheight(0) : (&lines - has('nvim'))12601261  " Size and position1262  let width = min([max([8, opts.width > 1 ? opts.width : float2nr(columns * opts.width)]), columns])1263  let height = min([max([4, opts.height > 1 ? opts.height : float2nr(lines * opts.height)]), lines])1264  let row = float2nr(yoffset * (lines - height)) + (relative ? win_screenpos(0)[0] - 1 : 0)1265  let col = float2nr(xoffset * (columns - width)) + (relative ? win_screenpos(0)[1] - 1 : 0)12661267  " Managing the differences1268  let row = min([max([0, row]), &lines - has('nvim') - height])1269  let col = min([max([0, col]), &columns - width])1270  let row += !has('nvim')1271  let col += !has('nvim')12721273  return { 'row': row, 'col': col, 'width': width, 'height': height }1274endfunction12751276function! s:popup(opts) abort1277  let s:popup_opts = a:opts1278  call s:create_popup()12791280  augroup fzf_popup_resize1281    autocmd!1282    autocmd VimResized * call s:resize_popup()1283  augroup END1284endfunction12851286let s:default_action = {1287  \ 'ctrl-t': 'tab split',1288  \ 'ctrl-x': 'split',1289  \ 'ctrl-v': 'vsplit' }12901291function! s:shortpath()1292  let short = fnamemodify(getcwd(), ':~:.')1293  if !has('win32unix')1294    let short = pathshorten(short)1295  endif1296  let slash = (s:is_win && !&shellslash) ? '\' : '/'1297  return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)1298endfunction12991300function! s:cmd(bang, ...) abort1301  let args = copy(a:000)1302  let opts = { 'options': ['--multi', '--scheme', 'path'] }1303  if len(args) && isdirectory(expand(args[-1]))1304    let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1305    if s:is_win && !&shellslash1306      let opts.dir = substitute(opts.dir, '/', '\\', 'g')1307    endif1308    let prompt = opts.dir1309  else1310    let prompt = s:shortpath()1311  endif1312  let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '1313  call extend(opts.options, ['--prompt', prompt])1314  call extend(opts.options, args)1315  call fzf#run(fzf#wrap('FZF', opts, a:bang))1316endfunction13171318command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)13191320let &cpo = s:cpo_save1321unlet s:cpo_save