Skip to content
Myr

fzf.vim

This file

Path

plugin/fzf.vim

949 lines · 28.1 KiB

Last changed by

[nvim] Fix floating window requirements (#2089)Jan Edmund Lazobefore adoption3e36f2b

History of this file

Take it

1" Copyright (c) 2017 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([63      \ '@echo off',64      \ 'setlocal enabledelayedexpansion']65    \ + (has('gui_running') ? ['set TERM= > nul'] : [])66    \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds])67    \ + ['endlocal'],68    \ '<SID>enc_to_cp(v:val."\r")')69  endfunction70else71  let s:term_marker = ";#FZF"7273  function! s:fzf_call(fn, ...)74    return call(a:fn, a:000)75  endfunction7677  function! s:wrap_cmds(cmds)78    return a:cmds79  endfunction8081  function! s:enc_to_cp(str)82    return a:str83  endfunction84endif8586function! s:shellesc_cmd(arg)87  let escaped = substitute(a:arg, '[&|<>()@^]', '^&', 'g')88  let escaped = substitute(escaped, '%', '%%', 'g')89  let escaped = substitute(escaped, '"', '\\^&', 'g')90  let escaped = substitute(escaped, '\(\\\+\)\(\\^\)', '\1\1\2', 'g')91  return '^"'.substitute(escaped, '\(\\\+\)$', '\1\1', '').'^"'92endfunction9394function! fzf#shellescape(arg, ...)95  let shell = get(a:000, 0, s:is_win ? 'cmd.exe' : 'sh')96  if shell =~# 'cmd.exe$'97    return s:shellesc_cmd(a:arg)98  endif99  return s:fzf_call('shellescape', a:arg)100endfunction101102function! s:fzf_getcwd()103  return s:fzf_call('getcwd')104endfunction105106function! s:fzf_fnamemodify(fname, mods)107  return s:fzf_call('fnamemodify', a:fname, a:mods)108endfunction109110function! s:fzf_expand(fmt)111  return s:fzf_call('expand', a:fmt, 1)112endfunction113114function! s:fzf_tempname()115  return s:fzf_call('tempname')116endfunction117118let s:default_layout = { 'down': '~40%' }119let s:layout_keys = ['window', 'tmux', 'up', 'down', 'left', 'right']120let s:fzf_go = s:base_dir.'/bin/fzf'121let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'122123let s:cpo_save = &cpo124set cpo&vim125126function! fzf#install()127  if s:is_win && !has('win32unix')128    let script = s:base_dir.'/install.ps1'129    if !filereadable(script)130      throw script.' not found'131    endif132    let script = 'powershell -ExecutionPolicy Bypass -file ' . script133  else134    let script = s:base_dir.'/install'135    if !executable(script)136      throw script.' not found'137    endif138    let script .= ' --bin'139  endif140141  call s:warn('Running fzf installer ...')142  call system(script)143  if v:shell_error144    throw 'Failed to download fzf: '.script145  endif146endfunction147148function! s:fzf_exec()149  if !exists('s:exec')150    if executable(s:fzf_go)151      let s:exec = s:fzf_go152    elseif executable('fzf')153      let s:exec = 'fzf'154    elseif input('fzf executable not found. Download binary? (y/n) ') =~? '^y'155      redraw156      call fzf#install()157      return s:fzf_exec()158    else159      redraw160      throw 'fzf executable not found'161    endif162  endif163  return fzf#shellescape(s:exec)164endfunction165166function! s:tmux_enabled()167  if has('gui_running') || !exists('$TMUX')168    return 0169  endif170171  if exists('s:tmux')172    return s:tmux173  endif174175  let s:tmux = 0176  if !executable(s:fzf_tmux)177    if executable('fzf-tmux')178      let s:fzf_tmux = 'fzf-tmux'179    else180      return 0181    endif182  endif183184  let output = system('tmux -V')185  let s:tmux = !v:shell_error && output >= 'tmux 1.7'186  return s:tmux187endfunction188189function! s:escape(path)190  let path = fnameescape(a:path)191  return s:is_win ? escape(path, '$') : path192endfunction193194function! s:error(msg)195  echohl ErrorMsg196  echom a:msg197  echohl None198endfunction199200function! s:warn(msg)201  echohl WarningMsg202  echom a:msg203  echohl None204endfunction205206function! s:has_any(dict, keys)207  for key in a:keys208    if has_key(a:dict, key)209      return 1210    endif211  endfor212  return 0213endfunction214215function! s:open(cmd, target)216  if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')217    return218  endif219  execute a:cmd s:escape(a:target)220endfunction221222function! s:common_sink(action, lines) abort223  if len(a:lines) < 2224    return225  endif226  let key = remove(a:lines, 0)227  let Cmd = get(a:action, key, 'e')228  if type(Cmd) == type(function('call'))229    return Cmd(a:lines)230  endif231  if len(a:lines) > 1232    augroup fzf_swap233      autocmd SwapExists * let v:swapchoice='o'234            \| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))235    augroup END236  endif237  try238    let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified239    let autochdir = &autochdir240    set noautochdir241    for item in a:lines242      if empty243        execute 'e' s:escape(item)244        let empty = 0245      else246        call s:open(Cmd, item)247      endif248      if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')249            \ && isdirectory(item)250        doautocmd BufEnter251      endif252    endfor253  catch /^Vim:Interrupt$/254  finally255    let &autochdir = autochdir256    silent! autocmd! fzf_swap257  endtry258endfunction259260function! s:get_color(attr, ...)261  let gui = !s:is_win && !has('win32unix') && has('termguicolors') && &termguicolors262  let fam = gui ? 'gui' : 'cterm'263  let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'264  for group in a:000265    let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)266    if code =~? pat267      return code268    endif269  endfor270  return ''271endfunction272273function! s:defaults()274  let rules = copy(get(g:, 'fzf_colors', {}))275  let colors = join(map(items(filter(map(rules, 'call("s:get_color", v:val)'), '!empty(v:val)')), 'join(v:val, ":")'), ',')276  return empty(colors) ? '' : fzf#shellescape('--color='.colors)277endfunction278279function! s:validate_layout(layout)280  for key in keys(a:layout)281    if index(s:layout_keys, key) < 0282      throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',283            \ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')284    endif285  endfor286  return a:layout287endfunction288289function! s:evaluate_opts(options)290  return type(a:options) == type([]) ?291        \ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options292endfunction293294" [name string,] [opts dict,] [fullscreen boolean]295function! fzf#wrap(...)296  let args = ['', {}, 0]297  let expects = map(copy(args), 'type(v:val)')298  let tidx = 0299  for arg in copy(a:000)300    let tidx = index(expects, type(arg) == 6 ? type(0) : type(arg), tidx)301    if tidx < 0302      throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'303    endif304    let args[tidx] = arg305    let tidx += 1306    unlet arg307  endfor308  let [name, opts, bang] = args309310  if len(name)311    let opts.name = name312  end313314  " Layout: g:fzf_layout (and deprecated g:fzf_height)315  if bang316    for key in s:layout_keys317      if has_key(opts, key)318        call remove(opts, key)319      endif320    endfor321  elseif !s:has_any(opts, s:layout_keys)322    if !exists('g:fzf_layout') && exists('g:fzf_height')323      let opts.down = g:fzf_height324    else325      let opts = extend(opts, s:validate_layout(get(g:, 'fzf_layout', s:default_layout)))326    endif327  endif328329  " Colors: g:fzf_colors330  let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))331332  " History: g:fzf_history_dir333  if len(name) && len(get(g:, 'fzf_history_dir', ''))334    let dir = s:fzf_expand(g:fzf_history_dir)335    if !isdirectory(dir)336      call mkdir(dir, 'p')337    endif338    let history = fzf#shellescape(dir.'/'.name)339    let opts.options = join(['--history', history, opts.options])340  endif341342  " Action: g:fzf_action343  if !s:has_any(opts, ['sink', 'sink*'])344    let opts._action = get(g:, 'fzf_action', s:default_action)345    let opts.options .= ' --expect='.join(keys(opts._action), ',')346    function! opts.sink(lines) abort347      return s:common_sink(self._action, a:lines)348    endfunction349    let opts['sink*'] = remove(opts, 'sink')350  endif351352  return opts353endfunction354355function! s:use_sh()356  let [shell, shellslash, shellcmdflag, shellxquote] = [&shell, &shellslash, &shellcmdflag, &shellxquote]357  if s:is_win358    set shell=cmd.exe359    set noshellslash360    let &shellcmdflag = has('nvim') ? '/s /c' : '/c'361    let &shellxquote = has('nvim') ? '"' : '('362  else363    set shell=sh364  endif365  return [shell, shellslash, shellcmdflag, shellxquote]366endfunction367368function! fzf#run(...) abort369try370  let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()371372  let dict   = exists('a:1') ? copy(a:1) : {}373  let temps  = { 'result': s:fzf_tempname() }374  let optstr = s:evaluate_opts(get(dict, 'options', ''))375  try376    let fzf_exec = s:fzf_exec()377  catch378    throw v:exception379  endtry380381  if !has_key(dict, 'dir')382    let dict.dir = s:fzf_getcwd()383  endif384  if has('win32unix') && has_key(dict, 'dir')385    let dict.dir = fnamemodify(dict.dir, ':p')386  endif387388  if has_key(dict, 'source')389    let source = dict.source390    let type = type(source)391    if type == 1392      let prefix = '( '.source.' )|'393    elseif type == 3394      let temps.input = s:fzf_tempname()395      call writefile(map(source, '<SID>enc_to_cp(v:val)'), temps.input)396      let prefix = (s:is_win ? 'type ' : 'cat ').fzf#shellescape(temps.input).'|'397    else398      throw 'Invalid source type'399    endif400  else401    let prefix = ''402  endif403404  let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')405  let use_height = has_key(dict, 'down') && !has('gui_running') &&406        \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&407        \ executable('tput') && filereadable('/dev/tty')408  let has_vim8_term = has('terminal') && has('patch-8.0.995')409  let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win410  let use_term = has_nvim_term ||411    \ has_vim8_term && !has('win32unix') && (has('gui_running') || s:is_win || !use_height && s:present(dict, 'down', 'up', 'left', 'right', 'window'))412  let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()413  if prefer_tmux && use_tmux414    let use_height = 0415    let use_term = 0416  endif417  if use_height418    let height = s:calc_size(&lines, dict.down, dict)419    let optstr .= ' --height='.height420  elseif use_term421    let optstr .= ' --no-height'422  endif423  let command = prefix.(use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result424425  if use_term426    return s:execute_term(dict, command, temps)427  endif428429  let lines = use_tmux ? s:execute_tmux(dict, command, temps)430                 \ : s:execute(dict, command, use_height, temps)431  call s:callback(dict, lines)432  return lines433finally434  let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]435endtry436endfunction437438function! s:present(dict, ...)439  for key in a:000440    if !empty(get(a:dict, key, ''))441      return 1442    endif443  endfor444  return 0445endfunction446447function! s:fzf_tmux(dict)448  let size = get(a:dict, 'tmux', '')449  if empty(size)450    for o in ['up', 'down', 'left', 'right']451      if s:present(a:dict, o)452        let spec = a:dict[o]453        if (o == 'up' || o == 'down') && spec[0] == '~'454          let size = '-'.o[0].s:calc_size(&lines, spec, a:dict)455        else456          " Legacy boolean option457          let size = '-'.o[0].(spec == 1 ? '' : substitute(spec, '^\~', '', ''))458        endif459        break460      endif461    endfor462  endif463  return printf('LINES=%d COLUMNS=%d %s %s %s --',464    \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))465endfunction466467function! s:splittable(dict)468  return s:present(a:dict, 'up', 'down') && &lines > 15 ||469        \ s:present(a:dict, 'left', 'right') && &columns > 40470endfunction471472function! s:pushd(dict)473  if s:present(a:dict, 'dir')474    let cwd = s:fzf_getcwd()475    let w:fzf_pushd = {476    \   'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),477    \   'origin': cwd,478    \   'bufname': bufname('')479    \ }480    execute 'lcd' s:escape(a:dict.dir)481    let cwd = s:fzf_getcwd()482    let w:fzf_pushd.dir = cwd483    let a:dict.pushd = w:fzf_pushd484    return cwd485  endif486  return ''487endfunction488489augroup fzf_popd490  autocmd!491  autocmd WinEnter * call s:dopopd()492augroup END493494function! s:dopopd()495  if !exists('w:fzf_pushd')496    return497  endif498499  " FIXME: We temporarily change the working directory to 'dir' entry500  " of options dictionary (set to the current working directory if not given)501  " before running fzf.502  "503  " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})504  "505  " After processing the sink function, we have to restore the current working506  " directory. But doing so may not be desirable if the function changed the507  " working directory on purpose.508  "509  " So how can we tell if we should do it or not? A simple heuristic we use510  " here is that we change directory only if the current working directory511  " matches 'dir' entry. However, it is possible that the sink function did512  " change the directory to 'dir'. In that case, the user will have an513  " unexpected result.514  if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))515    execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)516  endif517  unlet w:fzf_pushd518endfunction519520function! s:xterm_launcher()521  let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'522  if has('gui_macvim')523    let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'524  endif525  return printf(fmt,526    \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),527    \ &columns, &lines/2, getwinposx(), getwinposy())528endfunction529unlet! s:launcher530if s:is_win || has('win32unix')531  let s:launcher = '%s'532else533  let s:launcher = function('s:xterm_launcher')534endif535536function! s:exit_handler(code, command, ...)537  if a:code == 130538    return 0539  elseif has('nvim') && a:code == 129540    " When deleting the terminal buffer while fzf is still running,541    " Nvim sends SIGHUP.542    return 0543  elseif a:code > 1544    call s:error('Error running ' . a:command)545    if !empty(a:000)546      sleep547    endif548    return 0549  endif550  return 1551endfunction552553function! s:execute(dict, command, use_height, temps) abort554  call s:pushd(a:dict)555  if has('unix') && !a:use_height556    silent! !clear 2> /dev/null557  endif558  let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')559  if has('gui_running')560    let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))561    let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher562    if has('unix')563      let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"564    endif565    let command = printf(fmt, escaped)566  else567    let command = escaped568  endif569  if s:is_win570    let batchfile = s:fzf_tempname().'.bat'571    call writefile(s:wrap_cmds(command), batchfile)572    let command = batchfile573    let a:temps.batchfile = batchfile574    if has('nvim')575      let fzf = {}576      let fzf.dict = a:dict577      let fzf.temps = a:temps578      function! fzf.on_exit(job_id, exit_status, event) dict579        call s:pushd(self.dict)580        let lines = s:collect(self.temps)581        call s:callback(self.dict, lines)582      endfunction583      let cmd = 'start /wait cmd /c '.command584      call jobstart(cmd, fzf)585      return []586    endif587  elseif has('win32unix') && $TERM !=# 'cygwin'588    let shellscript = s:fzf_tempname()589    call writefile([command], shellscript)590    let command = 'cmd.exe /C '.fzf#shellescape('set "TERM=" & start /WAIT sh -c '.shellscript)591    let a:temps.shellscript = shellscript592  endif593  if a:use_height594    let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'595    call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))596  else597    execute 'silent !'.command598  endif599  let exit_status = v:shell_error600  redraw!601  return s:exit_handler(exit_status, command) ? s:collect(a:temps) : []602endfunction603604function! s:execute_tmux(dict, command, temps) abort605  let command = a:command606  let cwd = s:pushd(a:dict)607  if len(cwd)608    " -c '#{pane_current_path}' is only available on tmux 1.9 or above609    let command = join(['cd', fzf#shellescape(cwd), '&&', command])610  endif611612  call system(command)613  let exit_status = v:shell_error614  redraw!615  return s:exit_handler(exit_status, command) ? s:collect(a:temps) : []616endfunction617618function! s:calc_size(max, val, dict)619  let val = substitute(a:val, '^\~', '', '')620  if val =~ '%$'621    let size = a:max * str2nr(val[:-2]) / 100622  else623    let size = min([a:max, str2nr(val)])624  endif625626  let srcsz = -1627  if type(get(a:dict, 'source', 0)) == type([])628    let srcsz = len(a:dict.source)629  endif630631  let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))632  let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2633  let margin += stridx(opts, '--border') > stridx(opts, '--no-border') ? 2 : 0634  if stridx(opts, '--header') > stridx(opts, '--no-header')635    let margin += len(split(opts, "\n"))636  endif637  return srcsz >= 0 ? min([srcsz + margin, size]) : size638endfunction639640function! s:getpos()641  return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}642endfunction643644function! s:split(dict)645  let directions = {646  \ 'up':    ['topleft', 'resize', &lines],647  \ 'down':  ['botright', 'resize', &lines],648  \ 'left':  ['vertical topleft', 'vertical resize', &columns],649  \ 'right': ['vertical botright', 'vertical resize', &columns] }650  let ppos = s:getpos()651  let is_popup = 0652  try653    if s:present(a:dict, 'window')654      if type(a:dict.window) == type({})655        if !(has('nvim') ? has('nvim-0.4') : has('popupwin') && has('patch-8.2.191'))656          throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'657        end658        call s:popup(a:dict.window)659        let is_popup = 1660      else661        execute 'keepalt' a:dict.window662      endif663    elseif !s:splittable(a:dict)664      execute (tabpagenr()-1).'tabnew'665    else666      for [dir, triple] in items(directions)667        let val = get(a:dict, dir, '')668        if !empty(val)669          let [cmd, resz, max] = triple670          if (dir == 'up' || dir == 'down') && val[0] == '~'671            let sz = s:calc_size(max, val, a:dict)672          else673            let sz = s:calc_size(max, val, {})674          endif675          execute cmd sz.'new'676          execute resz sz677          return [ppos, {}, is_popup]678        endif679      endfor680    endif681    return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]682  finally683    if !is_popup684      setlocal winfixwidth winfixheight685    endif686  endtry687endfunction688689function! s:execute_term(dict, command, temps) abort690  let winrest = winrestcmd()691  let pbuf = bufnr('')692  let [ppos, winopts, is_popup] = s:split(a:dict)693  call s:use_sh()694  let b:fzf = a:dict695  let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,696            \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,697            \ 'columns': &columns, 'command': a:command }698  function! fzf.switch_back(inplace)699    if a:inplace && bufnr('') == self.buf700      if bufexists(self.pbuf)701        execute 'keepalt b' self.pbuf702      endif703      " No other listed buffer704      if bufnr('') == self.buf705        enew706      endif707    endif708  endfunction709  function! fzf.on_exit(id, code, ...)710    if s:getpos() == self.ppos " {'window': 'enew'}711      for [opt, val] in items(self.winopts)712        execute 'let' opt '=' val713      endfor714      call self.switch_back(1)715    else716      if bufnr('') == self.buf717        " We use close instead of bd! since Vim does not close the split when718        " there's no other listed buffer (nvim +'set nobuflisted')719        close720      endif721      silent! execute 'tabnext' self.ppos.tab722      silent! execute self.ppos.win.'wincmd w'723    endif724725    if bufexists(self.buf)726      execute 'bd!' self.buf727    endif728729    if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos730      execute self.winrest731    endif732733    if !s:exit_handler(a:code, self.command, 1)734      return735    endif736737    call s:pushd(self.dict)738    let lines = s:collect(self.temps)739    call s:callback(self.dict, lines)740    call self.switch_back(s:getpos() == self.ppos)741  endfunction742743  try744    call s:pushd(a:dict)745    if s:is_win746      let fzf.temps.batchfile = s:fzf_tempname().'.bat'747      call writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)748      let command = fzf.temps.batchfile749    else750      let command = a:command751    endif752    let command .= s:term_marker753    if has('nvim')754      call termopen(command, fzf)755    else756      let term_opts = {'exit_cb': function(fzf.on_exit)}757      if is_popup758        let term_opts.hidden = 1759      else760        let term_opts.curwin = 1761      endif762      let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)763      if is_popup && exists('#TerminalWinOpen')764        doautocmd <nomodeline> TerminalWinOpen765      endif766      if !has('patch-8.0.1261') && !s:is_win767        call term_wait(fzf.buf, 20)768      endif769    endif770  finally771    call s:dopopd()772  endtry773  setlocal nospell bufhidden=wipe nobuflisted nonumber774  setf fzf775  startinsert776  return []777endfunction778779function! s:collect(temps) abort780  try781    return filereadable(a:temps.result) ? readfile(a:temps.result) : []782  finally783    for tf in values(a:temps)784      silent! call delete(tf)785    endfor786  endtry787endfunction788789function! s:callback(dict, lines) abort790  let popd = has_key(a:dict, 'pushd')791  if popd792    let w:fzf_pushd = a:dict.pushd793  endif794795  try796    if has_key(a:dict, 'sink')797      for line in a:lines798        if type(a:dict.sink) == 2799          call a:dict.sink(line)800        else801          execute a:dict.sink s:escape(line)802        endif803      endfor804    endif805    if has_key(a:dict, 'sink*')806      call a:dict['sink*'](a:lines)807    endif808  catch809    if stridx(v:exception, ':E325:') < 0810      echoerr v:exception811    endif812  endtry813814  " We may have opened a new window or tab815  if popd816    let w:fzf_pushd = a:dict.pushd817    call s:dopopd()818  endif819endfunction820821if has('nvim')822  function s:create_popup(hl, opts) abort823    let buf = nvim_create_buf(v:false, v:true)824    let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)825    let border = has_key(opts, 'border') ? remove(opts, 'border') : []826    let win = nvim_open_win(buf, v:true, opts)827    call setwinvar(win, '&winhighlight', 'NormalFloat:'..a:hl)828    call setwinvar(win, '&colorcolumn', '')829    if !empty(border)830      call nvim_buf_set_lines(buf, 0, -1, v:true, border)831    endif832    return buf833  endfunction834else835  function! s:create_popup(hl, opts) abort836    let is_frame = has_key(a:opts, 'border')837    let s:popup_create = {buf -> popup_create(buf, #{838      \ line: a:opts.row,839      \ col: a:opts.col,840      \ minwidth: a:opts.width,841      \ minheight: a:opts.height,842      \ zindex: 50 - is_frame,843    \ })}844    if is_frame845      let id = s:popup_create('')846      call setwinvar(id, '&wincolor', a:hl)847      call setbufline(winbufnr(id), 1, a:opts.border)848      execute 'autocmd BufWipeout * ++once call popup_close('..id..')'849      return winbufnr(id)850    else851      autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))852    endif853  endfunction854endif855856function! s:popup(opts) abort857  " Support ambiwidth == 'double'858  let ambidouble = &ambiwidth == 'double' ? 2 : 1859860  " Size and position861  let width = min([max([0, float2nr(&columns * a:opts.width)]), &columns])862  let width += width % ambidouble863  let height = min([max([0, float2nr(&lines * a:opts.height)]), &lines - has('nvim')])864  let row = float2nr(get(a:opts, 'yoffset', 0.5) * (&lines - height))865  let col = float2nr(get(a:opts, 'xoffset', 0.5) * (&columns - width))866867  " Managing the differences868  let row = min([max([0, row]), &lines - has('nvim') - height])869  let col = min([max([0, col]), &columns - width])870  let row += !has('nvim')871  let col += !has('nvim')872873  " Border style874  let style = tolower(get(a:opts, 'border', 'rounded'))875  if !has_key(a:opts, 'border') && !get(a:opts, 'rounded', 1)876    let style = 'sharp'877  endif878879  if style =~ 'vertical\|left\|right'880    let mid = style == 'vertical' ? '│' .. repeat(' ', width - 2 * ambidouble) .. '│' :881            \ style == 'left'     ? '│' .. repeat(' ', width - 1 * ambidouble)882            \                     :        repeat(' ', width - 1 * ambidouble) .. '│'883    let border = repeat([mid], height)884    let shift = { 'row': 0, 'col': style == 'right' ? 0 : 2, 'width': style == 'vertical' ? -4 : -2, 'height': 0 }885  elseif style =~ 'horizontal\|top\|bottom'886    let hor = repeat('─', width / ambidouble)887    let mid = repeat(' ', width)888    let border = style == 'horizontal' ? [hor] + repeat([mid], height - 2) + [hor] :889               \ style == 'top'        ? [hor] + repeat([mid], height - 1)890               \                       :         repeat([mid], height - 1) + [hor]891    let shift = { 'row': style == 'bottom' ? 0 : 1, 'col': 0, 'width': 0, 'height': style == 'horizontal' ? -2 : -1 }892  else893    let edges = style == 'sharp' ? ['┌', '┐', '└', '┘'] : ['╭', '╮', '╰', '╯']894    let bar = repeat('─', width / ambidouble - 2)895    let top = edges[0] .. bar .. edges[1]896    let mid = '│' .. repeat(' ', width - 2 * ambidouble) .. '│'897    let bot = edges[2] .. bar .. edges[3]898    let border = [top] + repeat([mid], height - 2) + [bot]899    let shift = { 'row': 1, 'col': 2, 'width': -4, 'height': -2 }900  endif901902  let highlight = get(a:opts, 'highlight', 'Comment')903  let frame = s:create_popup(highlight, {904    \ 'row': row, 'col': col, 'width': width, 'height': height, 'border': border905  \ })906  call s:create_popup('Normal', {907    \ 'row': row + shift.row, 'col': col + shift.col, 'width': width + shift.width, 'height': height + shift.height908  \ })909  if has('nvim')910    execute 'autocmd BufWipeout <buffer> bwipeout '..frame911  endif912endfunction913914let s:default_action = {915  \ 'ctrl-t': 'tab split',916  \ 'ctrl-x': 'split',917  \ 'ctrl-v': 'vsplit' }918919function! s:shortpath()920  let short = fnamemodify(getcwd(), ':~:.')921  if !has('win32unix')922    let short = pathshorten(short)923  endif924  let slash = (s:is_win && !&shellslash) ? '\' : '/'925  return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)926endfunction927928function! s:cmd(bang, ...) abort929  let args = copy(a:000)930  let opts = { 'options': ['--multi'] }931  if len(args) && isdirectory(expand(args[-1]))932    let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')933    if s:is_win && !&shellslash934      let opts.dir = substitute(opts.dir, '/', '\\', 'g')935    endif936    let prompt = opts.dir937  else938    let prompt = s:shortpath()939  endif940  let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '941  call extend(opts.options, ['--prompt', prompt])942  call extend(opts.options, args)943  call fzf#run(fzf#wrap('FZF', opts, a:bang))944endfunction945946command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)947948let &cpo = s:cpo_save949unlet s:cpo_save