Skip to content
Myr

fzf.vim

This file

Path

plugin/fzf.vim

1,125 lines · 32.4 KiB

Last changed by

[neovim] Fix margin background color when &winborder is usedJunegunn Choibefore adoption821b8e7

History of this file

Take it

1" Copyright (c) 2013-2025 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  finish26endif27let g:loaded_fzf = 12829let s:is_win = has('win32') || has('win64')30if s:is_win && &shellslash31  set noshellslash32  let s:base_dir = expand('<sfile>:h:h')33  set shellslash34else35  let s:base_dir = expand('<sfile>:h:h')36endif37if s:is_win38  let s:term_marker = '&::FZF'3940  function! s:fzf_call(fn, ...)41    let shellslash = &shellslash42    try43      set noshellslash44      return call(a:fn, a:000)45    finally46      let &shellslash = shellslash47    endtry48  endfunction4950  " Use utf-8 for fzf.vim commands51  " Return array of shell commands for cmd.exe52  function! s:enc_to_cp(str)53    if !has('iconv')54      return a:str55    endif56    if !exists('s:codepage')57      let s:codepage = libcallnr('kernel32.dll', 'GetACP', 0)58    endif59    return iconv(a:str, &encoding, 'cp'.s:codepage)60  endfunction61  function! s:wrap_cmds(cmds)62    return map(['@echo off']63    \ + (has('gui_running') ? ['set TERM= > nul'] : [])64    \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds]),65    \ '<SID>enc_to_cp(v:val."\r")')66  endfunction67else68  let s:term_marker = ";#FZF"6970  function! s:fzf_call(fn, ...)71    return call(a:fn, a:000)72  endfunction7374  function! s:wrap_cmds(cmds)75    return a:cmds76  endfunction7778  function! s:enc_to_cp(str)79    return a:str80  endfunction81endif8283function! s:shellesc_cmd(arg)84  let e = '"'85  let slashes = 086  for c in split(a:arg, '\zs')87    if c ==# '\'88      let slashes += 189    elseif c ==# '"'90      let e .= repeat('\', slashes + 1)91      let slashes = 092    else93      let slashes = 094    endif95    let e .= c96  endfor97  let e .= repeat('\', slashes) .'"'98  return substitute(substitute(e, '[&|<>()^!"]', '^&', 'g'), '%', '%%', 'g')99endfunction100101function! fzf#shellescape(arg, ...)102  let shell = get(a:000, 0, s:is_win ? 'cmd.exe' : 'sh')103  if shell =~# 'cmd.exe$'104    return s:shellesc_cmd(a:arg)105  endif106  try107    let [shell, &shell] = [&shell, shell]108    return s:fzf_call('shellescape', a:arg)109  finally110    let [shell, &shell] = [&shell, shell]111  endtry112endfunction113114function! s:fzf_getcwd()115  return s:fzf_call('getcwd')116endfunction117118function! s:fzf_fnamemodify(fname, mods)119  return s:fzf_call('fnamemodify', a:fname, a:mods)120endfunction121122function! s:fzf_expand(fmt)123  return s:fzf_call('expand', a:fmt, 1)124endfunction125126function! s:fzf_tempname()127  return s:fzf_call('tempname')128endfunction129130let s:layout_keys = ['window', 'tmux', 'up', 'down', 'left', 'right']131let s:fzf_go = s:base_dir.'/bin/fzf'132let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'133134let s:cpo_save = &cpo135set cpo&vim136137function! s:popup_support()138  return has('nvim') ? has('nvim-0.4') : has('popupwin') && has('patch-8.2.191')139endfunction140141function! s:default_layout()142  return s:popup_support()143        \ ? { 'window' : { 'width': 0.9, 'height': 0.6 } }144        \ : { 'down': '~40%' }145endfunction146147function! fzf#install()148  if s:is_win && !has('win32unix')149    let script = s:base_dir.'/install.ps1'150    if !filereadable(script)151      throw script.' not found'152    endif153    let script = 'powershell -ExecutionPolicy Bypass -file ' . shellescape(script)154  else155    let script = s:base_dir.'/install'156    if !executable(script)157      throw script.' not found'158    endif159    let script .= ' --bin'160  endif161162  call s:warn('Running fzf installer ...')163  call system(script)164  if v:shell_error165    throw 'Failed to download fzf: '.script166  endif167endfunction168169let s:versions = {}170function s:get_version(bin)171  if has_key(s:versions, a:bin)172    return s:versions[a:bin]173  end174  let command = (&shell =~ 'powershell\|pwsh' ? '&' : '') . s:fzf_call('shellescape', a:bin) . ' --version --no-height'175  let output = systemlist(command)176  if v:shell_error || empty(output)177    return ''178  endif179  let ver = matchstr(output[-1], '[0-9.]\+')180  let s:versions[a:bin] = ver181  return ver182endfunction183184function! s:compare_versions(a, b)185  let a = split(a:a, '\.')186  let b = split(a:b, '\.')187  for idx in range(0, max([len(a), len(b)]) - 1)188    let v1 = str2nr(get(a, idx, 0))189    let v2 = str2nr(get(b, idx, 0))190    if     v1 < v2 | return -1191    elseif v1 > v2 | return 1192    endif193  endfor194  return 0195endfunction196197function! s:compare_binary_versions(a, b)198  return s:compare_versions(s:get_version(a:a), s:get_version(a:b))199endfunction200201let s:min_version = '0.53.0'202let s:checked = {}203function! fzf#exec(...)204  if !exists('s:exec')205    let binaries = []206    if executable('fzf')207      call add(binaries, 'fzf')208    endif209    if executable(s:fzf_go)210      call add(binaries, s:fzf_go)211    endif212213    if empty(binaries)214      if input('fzf executable not found. Download binary? (y/n) ') =~? '^y'215        redraw216        call fzf#install()217        return fzf#exec()218      else219        redraw220        throw 'fzf executable not found'221      endif222    elseif len(binaries) > 1223      call sort(binaries, 's:compare_binary_versions')224    endif225226    let s:exec = binaries[-1]227  endif228229  let min_version = s:min_version230  if a:0 && s:compare_versions(a:1, min_version) > 0231    let min_version = a:1232  endif233  if !has_key(s:checked, min_version)234    let fzf_version = s:get_version(s:exec)235    if empty(fzf_version)236      let message = printf('Failed to run "%s --version"', s:exec)237      unlet s:exec238      throw message239    end240241    if s:compare_versions(fzf_version, min_version) >= 0242      let s:checked[min_version] = 1243      return s:exec244    elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', min_version, fzf_version)) =~? '^y'245      let s:versions = {}246      unlet s:exec247      redraw248      call fzf#install()249      return fzf#exec(min_version, 1)250    else251      throw printf('You need to upgrade fzf (required: %s or above)', min_version)252    endif253  endif254255  return s:exec256endfunction257258function! s:tmux_enabled()259  if has('gui_running') || !exists('$TMUX')260    return 0261  endif262263  if exists('s:tmux')264    return s:tmux265  endif266267  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    endif274  endif275276  let output = system('tmux -V')277  let s:tmux = !v:shell_error && output >= 'tmux 1.7'278  return s:tmux279endfunction280281function! s:escape(path)282  let path = fnameescape(a:path)283  return s:is_win ? escape(path, '$') : path284endfunction285286function! s:error(msg)287  echohl ErrorMsg288  echom a:msg289  echohl None290endfunction291292function! s:warn(msg)293  echohl WarningMsg294  echom a:msg295  echohl None296endfunction297298function! s:has_any(dict, keys)299  for key in a:keys300    if has_key(a:dict, key)301      return 1302    endif303  endfor304  return 0305endfunction306307function! s:open(cmd, target)308  if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')309    return310  endif311  execute a:cmd s:escape(a:target)312endfunction313314function! s:common_sink(action, lines) abort315  if len(a:lines) < 2316    return317  endif318  let key = remove(a:lines, 0)319  let Cmd = get(a:action, key, 'e')320  if type(Cmd) == type(function('call'))321    return Cmd(a:lines)322  endif323  if len(a:lines) > 1324    augroup fzf_swap325      autocmd SwapExists * let v:swapchoice='o'326            \| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))327    augroup END328  endif329  try330    let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified331    " Preserve the current working directory in case it's changed during332    " the execution (e.g. `set autochdir` or `autocmd BufEnter * lcd ...`)333    let cwd = exists('w:fzf_pushd') ? w:fzf_pushd.dir : expand('%:p:h')334    for item in a:lines335      if has('win32unix') && item !~ '/'336        let item = substitute(item, '\', '/', 'g')337      end338      if item[0] != '~' && item !~ (s:is_win ? '^\([A-Z]:\)\?\' : '^/')339        let sep = s:is_win ? '\' : '/'340        let item = join([cwd, item], cwd[len(cwd)-1] == sep ? '' : sep)341      endif342      if empty343        execute 'e' s:escape(item)344        let empty = 0345      else346        call s:open(Cmd, item)347      endif348      if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')349            \ && isdirectory(item)350        doautocmd BufEnter351      endif352    endfor353  catch /^Vim:Interrupt$/354  finally355    silent! autocmd! fzf_swap356  endtry357endfunction358359function! s:get_color(attr, ...)360  " Force 24 bit colors: g:fzf_force_termguicolors (temporary workaround for https://github.com/junegunn/fzf.vim/issues/1152)361  let gui = get(g:, 'fzf_force_termguicolors', 0) || (!s:is_win && !has('win32unix') && (has('gui_running') || has('termguicolors') && &termguicolors))362  let fam = gui ? 'gui' : 'cterm'363  let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'364  for group in a:000365    let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)366    if code =~? pat367      return code368    endif369  endfor370  return ''371endfunction372373function! s:defaults()374  let rules = copy(get(g:, 'fzf_colors', {}))375  let colors = join(map(items(filter(map(rules, 'call("s:get_color", v:val)'), '!empty(v:val)')), 'join(v:val, ":")'), ',')376  return empty(colors) ? '' : fzf#shellescape('--color='.colors)377endfunction378379function! s:validate_layout(layout)380  for key in keys(a:layout)381    if index(s:layout_keys, key) < 0382      throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',383            \ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')384    endif385  endfor386  return a:layout387endfunction388389function! s:evaluate_opts(options)390  return type(a:options) == type([]) ?391        \ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options392endfunction393394" [name string,] [opts dict,] [fullscreen boolean]395function! fzf#wrap(...)396  let args = ['', {}, 0]397  let expects = map(copy(args), 'type(v:val)')398  let tidx = 0399  for arg in copy(a:000)400    let tidx = index(expects, type(arg) == 6 ? type(0) : type(arg), tidx)401    if tidx < 0402      throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'403    endif404    let args[tidx] = arg405    let tidx += 1406    unlet arg407  endfor408  let [name, opts, bang] = args409410  if len(name)411    let opts.name = name412  end413414  " Layout: g:fzf_layout (and deprecated g:fzf_height)415  if bang416    for key in s:layout_keys417      if has_key(opts, key)418        call remove(opts, key)419      endif420    endfor421  elseif !s:has_any(opts, s:layout_keys)422    if !exists('g:fzf_layout') && exists('g:fzf_height')423      let opts.down = g:fzf_height424    else425      let opts = extend(opts, s:validate_layout(get(g:, 'fzf_layout', s:default_layout())))426    endif427  endif428429  " Colors: g:fzf_colors430  let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))431432  " History: g:fzf_history_dir433  if len(name) && len(get(g:, 'fzf_history_dir', ''))434    let dir = s:fzf_expand(g:fzf_history_dir)435    if !isdirectory(dir)436      call mkdir(dir, 'p')437    endif438    let history = fzf#shellescape(dir.'/'.name)439    let opts.options = join(['--history', history, opts.options])440  endif441442  " Action: g:fzf_action443  if !s:has_any(opts, ['sink', 'sinklist', 'sink*'])444    let opts._action = get(g:, 'fzf_action', s:default_action)445    let opts.options .= ' --expect='.join(keys(opts._action), ',')446    function! opts.sinklist(lines) abort447      return s:common_sink(self._action, a:lines)448    endfunction449    let opts['sink*'] = opts.sinklist " For backward compatibility450  endif451452  return opts453endfunction454455function! s:use_sh()456  let [shell, shellslash, shellcmdflag, shellxquote] = [&shell, &shellslash, &shellcmdflag, &shellxquote]457  if s:is_win458    set shell=cmd.exe459    set noshellslash460    let &shellcmdflag = has('nvim') ? '/s /c' : '/c'461    let &shellxquote = has('nvim') ? '"' : '('462  else463    set shell=sh464  endif465  return [shell, shellslash, shellcmdflag, shellxquote]466endfunction467468function! s:writefile(...)469  if call('writefile', a:000) == -1470    throw 'Failed to write temporary file. Check if you can write to the path tempname() returns.'471  endif472endfunction473474function! s:extract_option(opts, name)475  let opt = ''476  let expect = 0477  " There are a few cases where this function doesn't work as expected.478  " Let's just assume such cases are extremely unlikely in real world.479  "   e.g. --query --border480  for word in split(a:opts)481    if expect && word !~ '^"\=-'482      let opt = opt . ' ' . word483      let expect = 0484    elseif word == '--no-'.a:name485      let opt = ''486    elseif word =~ '^--'.a:name.'='487      let opt = word488    elseif word =~ '^--'.a:name.'$'489      let opt = word490      let expect = 1491    elseif expect492      let expect = 0493    endif494  endfor495  return opt496endfunction497498let s:need_cmd_window = has('win32unix') && $TERM_PROGRAM ==# 'mintty' && s:compare_versions($TERM_PROGRAM_VERSION, '3.4.5') < 0 && !executable('winpty')499500function! fzf#run(...) abort501try502  let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()503504  let dict   = exists('a:1') ? copy(a:1) : {}505  let temps  = { 'result': s:fzf_tempname() }506  let optstr = s:evaluate_opts(get(dict, 'options', ''))507  try508    let fzf_exec = shellescape(fzf#exec())509  catch510    throw v:exception511  endtry512513  if !s:present(dict, 'dir')514    let dict.dir = s:fzf_getcwd()515  endif516  if has('win32unix') && s:present(dict, 'dir')517    let dict.dir = fnamemodify(dict.dir, ':p')518  endif519520  if has_key(dict, 'source')521    let source = dict.source522    let type = type(source)523    if type == 1524      let prefix = '('.source.')|'525    elseif type == 3526      let temps.input = s:fzf_tempname()527      call s:writefile(source, temps.input)528      let prefix = (s:is_win ? 'type ' : 'command cat ').fzf#shellescape(temps.input).'|'529    else530      throw 'Invalid source type'531    endif532  else533    let prefix = ''534  endif535536  let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')537  let use_height = has_key(dict, 'down') && !has('gui_running') &&538        \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&539        \ executable('tput') && filereadable('/dev/tty')540  let has_vim8_term = has('terminal') && has('patch-8.0.995')541  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'))545  let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()546  if prefer_tmux && use_tmux547    let use_height = 0548    let use_term = 0549  endif550  if use_term551    let optstr .= ' --no-height --no-tmux'552  elseif use_height553    let height = s:calc_size(&lines, dict.down, dict)554    let optstr .= ' --no-tmux --height='.height555  endif556557  if exists('&winborder') && &winborder !=# '' && &winborder !=# 'none'558    " Add 1-column horizontal margin559    let optstr = join(['--margin 0,1', optstr])560  else561    " Respect --border option given in $FZF_DEFAULT_OPTS and 'options'562    let optstr = join([s:border_opt(get(dict, 'window', 0)), s:extract_option($FZF_DEFAULT_OPTS, 'border'), optstr])563  endif564565  let command = prefix.(use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result566567  if use_term568    return s:execute_term(dict, command, temps)569  endif570571  let lines = use_tmux ? s:execute_tmux(dict, command, temps)572                 \ : s:execute(dict, command, use_height, temps)573  call s:callback(dict, lines)574  return lines575finally576  let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]577endtry578endfunction579580function! s:present(dict, ...)581  for key in a:000582    if !empty(get(a:dict, key, ''))583      return 1584    endif585  endfor586  return 0587endfunction588589function! s:fzf_tmux(dict)590  let size = get(a:dict, 'tmux', '')591  if empty(size)592    for o in ['up', 'down', 'left', 'right']593      if s:present(a:dict, o)594        let size = o . ',' . a:dict[o]595        break596      endif597    endfor598  endif599600  " Legacy fzf-tmux options601  if size =~ '-'602    return printf('LINES=%d COLUMNS=%d %s %s %s --',603          \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))604  end605606  " Using native --tmux option607  let in = (has_key(a:dict, 'source') ? '' : ' --force-tty-in')608  return printf('%s --tmux %s%s', fzf#shellescape(fzf#exec()), size, in)609endfunction610611function! s:splittable(dict)612  return s:present(a:dict, 'up', 'down') && &lines > 15 ||613        \ s:present(a:dict, 'left', 'right') && &columns > 40614endfunction615616function! s:pushd(dict)617  if s:present(a:dict, 'dir')618    let cwd = s:fzf_getcwd()619    let w:fzf_pushd = {620    \   'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),621    \   'origin': cwd,622    \   'bufname': bufname('')623    \ }624    execute 'lcd' s:escape(a:dict.dir)625    let cwd = s:fzf_getcwd()626    let w:fzf_pushd.dir = cwd627    let a:dict.pushd = w:fzf_pushd628    return cwd629  endif630  return ''631endfunction632633augroup fzf_popd634  autocmd!635  autocmd WinEnter * call s:dopopd()636augroup END637638function! s:dopopd()639  if !exists('w:fzf_pushd')640    return641  endif642643  " FIXME: We temporarily change the working directory to 'dir' entry644  " of options dictionary (set to the current working directory if not given)645  " before running fzf.646  "647  " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})648  "649  " After processing the sink function, we have to restore the current working650  " directory. But doing so may not be desirable if the function changed the651  " working directory on purpose.652  "653  " So how can we tell if we should do it or not? A simple heuristic we use654  " here is that we change directory only if the current working directory655  " matches 'dir' entry. However, it is possible that the sink function did656  " change the directory to 'dir'. In that case, the user will have an657  " unexpected result.658  if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))659    execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)660  endif661  unlet! w:fzf_pushd662endfunction663664function! s:xterm_launcher()665  let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'666  if has('gui_macvim')667    let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'668  endif669  return printf(fmt,670    \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),671    \ &columns, &lines/2, getwinposx(), getwinposy())672endfunction673unlet! s:launcher674if s:is_win || has('win32unix')675  let s:launcher = '%s'676else677  let s:launcher = function('s:xterm_launcher')678endif679680function! s:exit_handler(dict, code, command, ...)681  if has_key(a:dict, 'exit')682    call a:dict.exit(a:code)683  endif684  if a:code == 2685    call s:error('Error running ' . a:command)686    if !empty(a:000)687      sleep688    endif689  endif690  return a:code691endfunction692693function! s:execute(dict, command, use_height, temps) abort694  call s:pushd(a:dict)695  if has('unix') && !a:use_height696    silent! !clear 2> /dev/null697  endif698  let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')699  if has('gui_running')700    let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))701    let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher702    if has('unix')703      let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"704    endif705    let command = printf(fmt, escaped)706  else707    let command = escaped708  endif709  if s:is_win710    let batchfile = s:fzf_tempname().'.bat'711    call s:writefile(s:wrap_cmds(command), batchfile)712    let command = batchfile713    let a:temps.batchfile = batchfile714    if has('nvim')715      let fzf = {}716      let fzf.dict = a:dict717      let fzf.temps = a:temps718      function! fzf.on_exit(job_id, exit_status, event) dict719        call s:pushd(self.dict)720        let lines = s:collect(self.temps)721        call s:callback(self.dict, lines)722      endfunction723      let cmd = 'start /wait cmd /c '.command724      call jobstart(cmd, fzf)725      return []726    endif727  elseif s:need_cmd_window728    let shellscript = s:fzf_tempname()729    call s:writefile([command], shellscript)730    let command = 'start //WAIT sh -c '.shellscript731    let a:temps.shellscript = shellscript732  endif733  if a:use_height734    let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'735    call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))736  else737    execute 'silent !'.command738  endif739  let exit_status = v:shell_error740  redraw!741  let lines = s:collect(a:temps)742  return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []743endfunction744745function! s:execute_tmux(dict, command, temps) abort746  let command = a:command747  let cwd = s:pushd(a:dict)748  if len(cwd)749    " -c '#{pane_current_path}' is only available on tmux 1.9 or above750    let command = join(['cd', fzf#shellescape(cwd), '&&', command])751  endif752753  call system(command)754  let exit_status = v:shell_error755  redraw!756  let lines = s:collect(a:temps)757  return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []758endfunction759760function! s:calc_size(max, val, dict)761  let val = substitute(a:val, '^\~', '', '')762  if val =~ '%$'763    let size = a:max * str2nr(val[:-2]) / 100764  else765    let size = min([a:max, str2nr(val)])766  endif767768  let srcsz = -1769  if type(get(a:dict, 'source', 0)) == type([])770    let srcsz = len(a:dict.source)771  endif772773  let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))774  if opts =~ 'preview'775    return size776  endif777  let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2778  let margin += match(opts, '--border\([^-]\|$\)') > match(opts, '--no-border\([^-]\|$\)') ? 2 : 0779  if stridx(opts, '--header') > stridx(opts, '--no-header')780    let margin += len(split(opts, "\n"))781  endif782  return srcsz >= 0 ? min([srcsz + margin, size]) : size783endfunction784785function! s:getpos()786  return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}787endfunction788789function! s:border_opt(window)790  if type(a:window) != type({})791    return ''792  endif793794  " Border style795  let style = tolower(get(a:window, 'border', ''))796  if !has_key(a:window, 'border') && has_key(a:window, 'rounded')797    let style = a:window.rounded ? 'rounded' : 'sharp'798  endif799  if style == 'none' || style == 'no'800    return ''801  endif802803  " For --border styles, we need fzf 0.24.0 or above804  call fzf#exec('0.24.0')805  let opt = ' --border ' . style806  if has_key(a:window, 'highlight')807    let color = s:get_color('fg', a:window.highlight)808    if len(color)809      let opt .= ' --color=border:' . color810    endif811  endif812  return opt813endfunction814815function! s:split(dict)816  let directions = {817  \ 'up':    ['topleft', 'resize', &lines],818  \ 'down':  ['botright', 'resize', &lines],819  \ 'left':  ['vertical topleft', 'vertical resize', &columns],820  \ 'right': ['vertical botright', 'vertical resize', &columns] }821  let ppos = s:getpos()822  let is_popup = 0823  try824    if s:present(a:dict, 'window')825      if type(a:dict.window) == type({})826        if !s:popup_support()827          throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'828        end829        call s:popup(a:dict.window)830        let is_popup = 1831      else832        execute 'keepalt' a:dict.window833      endif834    elseif !s:splittable(a:dict)835      execute (tabpagenr()-1).'tabnew'836    else837      for [dir, triple] in items(directions)838        let val = get(a:dict, dir, '')839        if !empty(val)840          let [cmd, resz, max] = triple841          if (dir == 'up' || dir == 'down') && val[0] == '~'842            let sz = s:calc_size(max, val, a:dict)843          else844            let sz = s:calc_size(max, val, {})845          endif846          execute cmd sz.'new'847          execute resz sz848          return [ppos, {}, is_popup]849        endif850      endfor851    endif852    return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]853  finally854    if !is_popup855      setlocal winfixwidth winfixheight856    endif857  endtry858endfunction859860nnoremap <silent> <Plug>(fzf-insert) i861nnoremap <silent> <Plug>(fzf-normal) <Nop>862if exists(':tnoremap')863  tnoremap <silent> <Plug>(fzf-insert) <C-\><C-n>i864  tnoremap <silent> <Plug>(fzf-normal) <C-\><C-n>865endif866867let s:warned = 0868function! s:handle_ambidouble(dict)869  if &ambiwidth == 'double'870    let a:dict.env = { 'RUNEWIDTH_EASTASIAN': '1' }871  elseif !s:warned && $RUNEWIDTH_EASTASIAN == '1' && &ambiwidth !=# 'double'872    call s:warn("$RUNEWIDTH_EASTASIAN is '1' but &ambiwidth is not 'double'")873    2sleep874    let s:warned = 1875  endif876endfunction877878function! s:execute_term(dict, command, temps) abort879  let winrest = winrestcmd()880  let pbuf = bufnr('')881  let [ppos, winopts, is_popup] = s:split(a:dict)882  call s:use_sh()883  let b:fzf = a:dict884  let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,885            \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,886            \ 'columns': &columns, 'command': a:command }887  function! fzf.switch_back(inplace)888    if a:inplace && bufnr('') == self.buf889      if bufexists(self.pbuf)890        execute 'keepalt keepjumps b' self.pbuf891      endif892      " No other listed buffer893      if bufnr('') == self.buf894        enew895      endif896    endif897  endfunction898  function! fzf.on_exit(id, code, ...)899    if s:getpos() == self.ppos " {'window': 'enew'}900      for [opt, val] in items(self.winopts)901        execute 'let' opt '=' val902      endfor903      call self.switch_back(1)904    else905      if bufnr('') == self.buf906        " We use close instead of bd! since Vim does not close the split when907        " there's no other listed buffer (nvim +'set nobuflisted')908        close909      endif910      silent! execute 'tabnext' self.ppos.tab911      silent! execute self.ppos.win.'wincmd w'912    endif913914    if bufexists(self.buf)915      execute 'bd!' self.buf916    endif917918    if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos919      execute self.winrest920    endif921922    let lines = s:collect(self.temps)923    if s:exit_handler(self.dict, a:code, self.command, 1) >= 2924      return925    endif926927    call s:pushd(self.dict)928    call s:callback(self.dict, lines)929    call self.switch_back(s:getpos() == self.ppos)930931    if &buftype == 'terminal'932      call feedkeys(&filetype == 'fzf' ? "\<Plug>(fzf-insert)" : "\<Plug>(fzf-normal)")933    endif934  endfunction935936  try937    call s:pushd(a:dict)938    if s:is_win939      let fzf.temps.batchfile = s:fzf_tempname().'.bat'940      call s:writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)941      let command = fzf.temps.batchfile942    else943      let command = a:command944    endif945    let command .= s:term_marker946    if has('nvim')947      call s:handle_ambidouble(fzf)948      call termopen(command, fzf)949    else950      let term_opts = {'exit_cb': function(fzf.on_exit)}951      if v:version >= 802952        let term_opts.term_kill = 'term'953      endif954      if is_popup955        let term_opts.hidden = 1956      else957        let term_opts.curwin = 1958      endif959      call s:handle_ambidouble(term_opts)960      keepjumps let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)961      if is_popup && exists('#TerminalWinOpen')962        doautocmd <nomodeline> TerminalWinOpen963      endif964      if !has('patch-8.0.1261') && !s:is_win965        call term_wait(fzf.buf, 20)966      endif967    endif968    tnoremap <buffer> <c-z> <nop>969    if exists('&termwinkey') && (empty(&termwinkey) || &termwinkey =~? '<c-w>')970      tnoremap <buffer> <c-w> <c-w>.971    endif972  finally973    call s:dopopd()974  endtry975  setlocal nospell bufhidden=wipe nobuflisted nonumber976  setf fzf977  startinsert978  return []979endfunction980981function! s:collect(temps) abort982  try983    return filereadable(a:temps.result) ? readfile(a:temps.result) : []984  finally985    for tf in values(a:temps)986      silent! call delete(tf)987    endfor988  endtry989endfunction990991function! s:callback(dict, lines) abort992  let popd = has_key(a:dict, 'pushd')993  if popd994    let w:fzf_pushd = a:dict.pushd995  endif996997  try998    if has_key(a:dict, 'sink')999      for line in a:lines1000        if type(a:dict.sink) == 21001          call a:dict.sink(line)1002        else1003          execute a:dict.sink s:escape(line)1004        endif1005      endfor1006    endif1007    if has_key(a:dict, 'sink*')1008      call a:dict['sink*'](a:lines)1009    elseif has_key(a:dict, 'sinklist')1010      call a:dict['sinklist'](a:lines)1011    endif1012  catch1013    if stridx(v:exception, ':E325:') < 01014      echoerr v:exception1015    endif1016  endtry10171018  " We may have opened a new window or tab1019  if popd1020    let w:fzf_pushd = a:dict.pushd1021    call s:dopopd()1022  endif1023endfunction10241025if has('nvim')1026  function s:create_popup(opts) abort1027    let buf = nvim_create_buf(v:false, v:true)1028    let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)1029    let win = nvim_open_win(buf, v:true, opts)1030    call setwinvar(win, '&colorcolumn', '')10311032    " Colors1033    try1034      call setwinvar(win, '&winhighlight', 'Pmenu:,Normal:Normal')1035      let rules = get(g:, 'fzf_colors', {})1036      if has_key(rules, 'bg')1037        let color = call('s:get_color', rules.bg)1038        if len(color)1039          let ns = nvim_create_namespace('fzf_popup')1040          let hl = nvim_set_hl(ns, 'Normal',1041                \ &termguicolors ? { 'bg': color } : { 'ctermbg': str2nr(color) })1042          call nvim_win_set_hl_ns(win, ns)1043        endif1044      endif1045    catch1046    endtry1047    return buf1048  endfunction1049else1050  function! s:create_popup(opts) abort1051    let s:popup_create = {buf -> popup_create(buf, #{1052      \ line: a:opts.row,1053      \ col: a:opts.col,1054      \ minwidth: a:opts.width,1055      \ maxwidth: a:opts.width,1056      \ minheight: a:opts.height,1057      \ maxheight: a:opts.height,1058      \ zindex: 1000,1059    \ })}1060    autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))1061  endfunction1062endif10631064function! s:popup(opts) abort1065  let xoffset = get(a:opts, 'xoffset', 0.5)1066  let yoffset = get(a:opts, 'yoffset', 0.5)1067  let relative = get(a:opts, 'relative', 0)10681069  " Use current window size for positioning relatively positioned popups1070  let columns = relative ? winwidth(0) : &columns1071  let lines = relative ? winheight(0) : (&lines - has('nvim'))10721073  " Size and position1074  let width = min([max([8, a:opts.width > 1 ? a:opts.width : float2nr(columns * a:opts.width)]), columns])1075  let height = min([max([4, a:opts.height > 1 ? a:opts.height : float2nr(lines * a:opts.height)]), lines])1076  let row = float2nr(yoffset * (lines - height)) + (relative ? win_screenpos(0)[0] - 1 : 0)1077  let col = float2nr(xoffset * (columns - width)) + (relative ? win_screenpos(0)[1] - 1 : 0)10781079  " Managing the differences1080  let row = min([max([0, row]), &lines - has('nvim') - height])1081  let col = min([max([0, col]), &columns - width])1082  let row += !has('nvim')1083  let col += !has('nvim')10841085  call s:create_popup({1086    \ 'row': row, 'col': col, 'width': width, 'height': height1087  \ })1088endfunction10891090let s:default_action = {1091  \ 'ctrl-t': 'tab split',1092  \ 'ctrl-x': 'split',1093  \ 'ctrl-v': 'vsplit' }10941095function! s:shortpath()1096  let short = fnamemodify(getcwd(), ':~:.')1097  if !has('win32unix')1098    let short = pathshorten(short)1099  endif1100  let slash = (s:is_win && !&shellslash) ? '\' : '/'1101  return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)1102endfunction11031104function! s:cmd(bang, ...) abort1105  let args = copy(a:000)1106  let opts = { 'options': ['--multi', '--scheme', 'path'] }1107  if len(args) && isdirectory(expand(args[-1]))1108    let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1109    if s:is_win && !&shellslash1110      let opts.dir = substitute(opts.dir, '/', '\\', 'g')1111    endif1112    let prompt = opts.dir1113  else1114    let prompt = s:shortpath()1115  endif1116  let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '1117  call extend(opts.options, ['--prompt', prompt])1118  call extend(opts.options, args)1119  call fzf#run(fzf#wrap('FZF', opts, a:bang))1120endfunction11211122command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)11231124let &cpo = s:cpo_save1125unlet s:cpo_save