Skip to content
Myr

fzf.vim

This file

Path

plugin/fzf.vim

1,096 lines · 31.5 KiB

Last changed by

[vim] Use native --tmux option instead of fzf-tmux when possibleJunegunn Choibefore adoption685fb71

History of this file

Take it

1" Copyright (c) 2013-2024 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:checked = {}202function! fzf#exec(...)203  if !exists('s:exec')204    let binaries = []205    if executable('fzf')206      call add(binaries, 'fzf')207    endif208    if executable(s:fzf_go)209      call add(binaries, s:fzf_go)210    endif211212    if empty(binaries)213      if input('fzf executable not found. Download binary? (y/n) ') =~? '^y'214        redraw215        call fzf#install()216        return fzf#exec()217      else218        redraw219        throw 'fzf executable not found'220      endif221    elseif len(binaries) > 1222      call sort(binaries, 's:compare_binary_versions')223    endif224225    let s:exec = binaries[-1]226  endif227228  if a:0 && !has_key(s:checked, a:1)229    let fzf_version = s:get_version(s:exec)230    if empty(fzf_version)231      let message = printf('Failed to run "%s --version"', s:exec)232      unlet s:exec233      throw message234    end235236    if s:compare_versions(fzf_version, a:1) >= 0237      let s:checked[a:1] = 1238      return s:exec239    elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', a:1, fzf_version)) =~? '^y'240      let s:versions = {}241      unlet s:exec242      redraw243      call fzf#install()244      return fzf#exec(a:1, 1)245    else246      throw printf('You need to upgrade fzf (required: %s or above)', a:1)247    endif248  endif249250  return s:exec251endfunction252253function! s:tmux_enabled()254  if has('gui_running') || !exists('$TMUX')255    return 0256  endif257258  if exists('s:tmux')259    return s:tmux260  endif261262  let s:tmux = 0263  if !executable(s:fzf_tmux)264    if executable('fzf-tmux')265      let s:fzf_tmux = 'fzf-tmux'266    else267      return 0268    endif269  endif270271  let output = system('tmux -V')272  let s:tmux = !v:shell_error && output >= 'tmux 1.7'273  return s:tmux274endfunction275276function! s:escape(path)277  let path = fnameescape(a:path)278  return s:is_win ? escape(path, '$') : path279endfunction280281function! s:error(msg)282  echohl ErrorMsg283  echom a:msg284  echohl None285endfunction286287function! s:warn(msg)288  echohl WarningMsg289  echom a:msg290  echohl None291endfunction292293function! s:has_any(dict, keys)294  for key in a:keys295    if has_key(a:dict, key)296      return 1297    endif298  endfor299  return 0300endfunction301302function! s:open(cmd, target)303  if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')304    return305  endif306  execute a:cmd s:escape(a:target)307endfunction308309function! s:common_sink(action, lines) abort310  if len(a:lines) < 2311    return312  endif313  let key = remove(a:lines, 0)314  let Cmd = get(a:action, key, 'e')315  if type(Cmd) == type(function('call'))316    return Cmd(a:lines)317  endif318  if len(a:lines) > 1319    augroup fzf_swap320      autocmd SwapExists * let v:swapchoice='o'321            \| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))322    augroup END323  endif324  try325    let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified326    " Preserve the current working directory in case it's changed during327    " the execution (e.g. `set autochdir` or `autocmd BufEnter * lcd ...`)328    let cwd = exists('w:fzf_pushd') ? w:fzf_pushd.dir : expand('%:p:h')329    for item in a:lines330      if item[0] != '~' && item !~ (s:is_win ? '^[A-Z]:\' : '^/')331        let sep = s:is_win ? '\' : '/'332        let item = join([cwd, item], cwd[len(cwd)-1] == sep ? '' : sep)333      endif334      if empty335        execute 'e' s:escape(item)336        let empty = 0337      else338        call s:open(Cmd, item)339      endif340      if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')341            \ && isdirectory(item)342        doautocmd BufEnter343      endif344    endfor345  catch /^Vim:Interrupt$/346  finally347    silent! autocmd! fzf_swap348  endtry349endfunction350351function! s:get_color(attr, ...)352  " Force 24 bit colors: g:fzf_force_termguicolors (temporary workaround for https://github.com/junegunn/fzf.vim/issues/1152)353  let gui = get(g:, 'fzf_force_termguicolors', 0) || (!s:is_win && !has('win32unix') && has('termguicolors') && &termguicolors)354  let fam = gui ? 'gui' : 'cterm'355  let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'356  for group in a:000357    let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)358    if code =~? pat359      return code360    endif361  endfor362  return ''363endfunction364365function! s:defaults()366  let rules = copy(get(g:, 'fzf_colors', {}))367  let colors = join(map(items(filter(map(rules, 'call("s:get_color", v:val)'), '!empty(v:val)')), 'join(v:val, ":")'), ',')368  return empty(colors) ? '' : fzf#shellescape('--color='.colors)369endfunction370371function! s:validate_layout(layout)372  for key in keys(a:layout)373    if index(s:layout_keys, key) < 0374      throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',375            \ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')376    endif377  endfor378  return a:layout379endfunction380381function! s:evaluate_opts(options)382  return type(a:options) == type([]) ?383        \ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options384endfunction385386" [name string,] [opts dict,] [fullscreen boolean]387function! fzf#wrap(...)388  let args = ['', {}, 0]389  let expects = map(copy(args), 'type(v:val)')390  let tidx = 0391  for arg in copy(a:000)392    let tidx = index(expects, type(arg) == 6 ? type(0) : type(arg), tidx)393    if tidx < 0394      throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'395    endif396    let args[tidx] = arg397    let tidx += 1398    unlet arg399  endfor400  let [name, opts, bang] = args401402  if len(name)403    let opts.name = name404  end405406  " Layout: g:fzf_layout (and deprecated g:fzf_height)407  if bang408    for key in s:layout_keys409      if has_key(opts, key)410        call remove(opts, key)411      endif412    endfor413  elseif !s:has_any(opts, s:layout_keys)414    if !exists('g:fzf_layout') && exists('g:fzf_height')415      let opts.down = g:fzf_height416    else417      let opts = extend(opts, s:validate_layout(get(g:, 'fzf_layout', s:default_layout())))418    endif419  endif420421  " Colors: g:fzf_colors422  let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))423424  " History: g:fzf_history_dir425  if len(name) && len(get(g:, 'fzf_history_dir', ''))426    let dir = s:fzf_expand(g:fzf_history_dir)427    if !isdirectory(dir)428      call mkdir(dir, 'p')429    endif430    let history = fzf#shellescape(dir.'/'.name)431    let opts.options = join(['--history', history, opts.options])432  endif433434  " Action: g:fzf_action435  if !s:has_any(opts, ['sink', 'sinklist', 'sink*'])436    let opts._action = get(g:, 'fzf_action', s:default_action)437    let opts.options .= ' --expect='.join(keys(opts._action), ',')438    function! opts.sinklist(lines) abort439      return s:common_sink(self._action, a:lines)440    endfunction441    let opts['sink*'] = opts.sinklist " For backward compatibility442  endif443444  return opts445endfunction446447function! s:use_sh()448  let [shell, shellslash, shellcmdflag, shellxquote] = [&shell, &shellslash, &shellcmdflag, &shellxquote]449  if s:is_win450    set shell=cmd.exe451    set noshellslash452    let &shellcmdflag = has('nvim') ? '/s /c' : '/c'453    let &shellxquote = has('nvim') ? '"' : '('454  else455    set shell=sh456  endif457  return [shell, shellslash, shellcmdflag, shellxquote]458endfunction459460function! s:writefile(...)461  if call('writefile', a:000) == -1462    throw 'Failed to write temporary file. Check if you can write to the path tempname() returns.'463  endif464endfunction465466function! s:extract_option(opts, name)467  let opt = ''468  let expect = 0469  " There are a few cases where this function doesn't work as expected.470  " Let's just assume such cases are extremely unlikely in real world.471  "   e.g. --query --border472  for word in split(a:opts)473    if expect && word !~ '^"\=-'474      let opt = opt . ' ' . word475      let expect = 0476    elseif word == '--no-'.a:name477      let opt = ''478    elseif word =~ '^--'.a:name.'='479      let opt = word480    elseif word =~ '^--'.a:name.'$'481      let opt = word482      let expect = 1483    elseif expect484      let expect = 0485    endif486  endfor487  return opt488endfunction489490function! fzf#run(...) abort491try492  let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()493494  let dict   = exists('a:1') ? copy(a:1) : {}495  let temps  = { 'result': s:fzf_tempname() }496  let optstr = s:evaluate_opts(get(dict, 'options', ''))497  try498    let fzf_exec = shellescape(fzf#exec())499  catch500    throw v:exception501  endtry502503  if !s:present(dict, 'dir')504    let dict.dir = s:fzf_getcwd()505  endif506  if has('win32unix') && s:present(dict, 'dir')507    let dict.dir = fnamemodify(dict.dir, ':p')508  endif509510  if has_key(dict, 'source')511    let source = dict.source512    let type = type(source)513    if type == 1514      let prefix = '('.source.')|'515    elseif type == 3516      let temps.input = s:fzf_tempname()517      call s:writefile(source, temps.input)518      let prefix = (s:is_win ? 'type ' : 'command cat ').fzf#shellescape(temps.input).'|'519    else520      throw 'Invalid source type'521    endif522  else523    let prefix = ''524  endif525526  let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')527  let use_height = has_key(dict, 'down') && !has('gui_running') &&528        \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&529        \ executable('tput') && filereadable('/dev/tty')530  let has_vim8_term = has('terminal') && has('patch-8.0.995')531  let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win532  let use_term = has_nvim_term ||533    \ has_vim8_term && !has('win32unix') && (has('gui_running') || s:is_win || s:present(dict, 'down', 'up', 'left', 'right', 'window'))534  let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()535  if prefer_tmux && use_tmux536    let use_height = 0537    let use_term = 0538  endif539  if use_term540    let optstr .= ' --no-height --no-tmux'541  elseif use_height542    let height = s:calc_size(&lines, dict.down, dict)543    let optstr .= ' --no-tmux --height='.height544  endif545  " Respect --border option given in $FZF_DEFAULT_OPTS and 'options'546  let optstr = join([s:border_opt(get(dict, 'window', 0)), s:extract_option($FZF_DEFAULT_OPTS, 'border'), optstr])547  let command = prefix.(use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result548549  if use_term550    return s:execute_term(dict, command, temps)551  endif552553  let lines = use_tmux ? s:execute_tmux(dict, command, temps)554                 \ : s:execute(dict, command, use_height, temps)555  call s:callback(dict, lines)556  return lines557finally558  let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]559endtry560endfunction561562function! s:present(dict, ...)563  for key in a:000564    if !empty(get(a:dict, key, ''))565      return 1566    endif567  endfor568  return 0569endfunction570571function! s:fzf_tmux(dict)572  let size = get(a:dict, 'tmux', '')573  if empty(size)574    for o in ['up', 'down', 'left', 'right']575      if s:present(a:dict, o)576        let size = o . ',' . a:dict[o]577        break578      endif579    endfor580  endif581582  " Legacy fzf-tmux options583  if size =~ '-'584    return printf('LINES=%d COLUMNS=%d %s %s %s --',585          \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))586  end587588  " Using native --tmux option589  let in = (has_key(a:dict, 'source') ? '' : ' < /dev/tty')590  return printf('%s --tmux %s%s', fzf#shellescape(fzf#exec()), size, in)591endfunction592593function! s:splittable(dict)594  return s:present(a:dict, 'up', 'down') && &lines > 15 ||595        \ s:present(a:dict, 'left', 'right') && &columns > 40596endfunction597598function! s:pushd(dict)599  if s:present(a:dict, 'dir')600    let cwd = s:fzf_getcwd()601    let w:fzf_pushd = {602    \   'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),603    \   'origin': cwd,604    \   'bufname': bufname('')605    \ }606    execute 'lcd' s:escape(a:dict.dir)607    let cwd = s:fzf_getcwd()608    let w:fzf_pushd.dir = cwd609    let a:dict.pushd = w:fzf_pushd610    return cwd611  endif612  return ''613endfunction614615augroup fzf_popd616  autocmd!617  autocmd WinEnter * call s:dopopd()618augroup END619620function! s:dopopd()621  if !exists('w:fzf_pushd')622    return623  endif624625  " FIXME: We temporarily change the working directory to 'dir' entry626  " of options dictionary (set to the current working directory if not given)627  " before running fzf.628  "629  " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})630  "631  " After processing the sink function, we have to restore the current working632  " directory. But doing so may not be desirable if the function changed the633  " working directory on purpose.634  "635  " So how can we tell if we should do it or not? A simple heuristic we use636  " here is that we change directory only if the current working directory637  " matches 'dir' entry. However, it is possible that the sink function did638  " change the directory to 'dir'. In that case, the user will have an639  " unexpected result.640  if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))641    execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)642  endif643  unlet! w:fzf_pushd644endfunction645646function! s:xterm_launcher()647  let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'648  if has('gui_macvim')649    let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'650  endif651  return printf(fmt,652    \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),653    \ &columns, &lines/2, getwinposx(), getwinposy())654endfunction655unlet! s:launcher656if s:is_win || has('win32unix')657  let s:launcher = '%s'658else659  let s:launcher = function('s:xterm_launcher')660endif661662function! s:exit_handler(code, command, ...)663  if a:code == 130664    return 0665  elseif has('nvim') && a:code == 129666    " When deleting the terminal buffer while fzf is still running,667    " Nvim sends SIGHUP.668    return 0669  elseif a:code > 1670    call s:error('Error running ' . a:command)671    if !empty(a:000)672      sleep673    endif674    return 0675  endif676  return 1677endfunction678679function! s:execute(dict, command, use_height, temps) abort680  call s:pushd(a:dict)681  if has('unix') && !a:use_height682    silent! !clear 2> /dev/null683  endif684  let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')685  if has('gui_running')686    let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))687    let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher688    if has('unix')689      let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"690    endif691    let command = printf(fmt, escaped)692  else693    let command = escaped694  endif695  if s:is_win696    let batchfile = s:fzf_tempname().'.bat'697    call s:writefile(s:wrap_cmds(command), batchfile)698    let command = batchfile699    let a:temps.batchfile = batchfile700    if has('nvim')701      let fzf = {}702      let fzf.dict = a:dict703      let fzf.temps = a:temps704      function! fzf.on_exit(job_id, exit_status, event) dict705        call s:pushd(self.dict)706        let lines = s:collect(self.temps)707        call s:callback(self.dict, lines)708      endfunction709      let cmd = 'start /wait cmd /c '.command710      call jobstart(cmd, fzf)711      return []712    endif713  elseif has('win32unix') && $TERM !=# 'cygwin'714    let shellscript = s:fzf_tempname()715    call s:writefile([command], shellscript)716    let command = 'cmd.exe //C '.fzf#shellescape('set "TERM=" & start /WAIT sh -c '.shellscript)717    let a:temps.shellscript = shellscript718  endif719  if a:use_height720    let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'721    call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))722  else723    execute 'silent !'.command724  endif725  let exit_status = v:shell_error726  redraw!727  let lines = s:collect(a:temps)728  return s:exit_handler(exit_status, command) ? lines : []729endfunction730731function! s:execute_tmux(dict, command, temps) abort732  let command = a:command733  let cwd = s:pushd(a:dict)734  if len(cwd)735    " -c '#{pane_current_path}' is only available on tmux 1.9 or above736    let command = join(['cd', fzf#shellescape(cwd), '&&', command])737  endif738739  call system(command)740  let exit_status = v:shell_error741  redraw!742  let lines = s:collect(a:temps)743  return s:exit_handler(exit_status, command) ? lines : []744endfunction745746function! s:calc_size(max, val, dict)747  let val = substitute(a:val, '^\~', '', '')748  if val =~ '%$'749    let size = a:max * str2nr(val[:-2]) / 100750  else751    let size = min([a:max, str2nr(val)])752  endif753754  let srcsz = -1755  if type(get(a:dict, 'source', 0)) == type([])756    let srcsz = len(a:dict.source)757  endif758759  let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))760  if opts =~ 'preview'761    return size762  endif763  let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2764  let margin += match(opts, '--border\([^-]\|$\)') > match(opts, '--no-border\([^-]\|$\)') ? 2 : 0765  if stridx(opts, '--header') > stridx(opts, '--no-header')766    let margin += len(split(opts, "\n"))767  endif768  return srcsz >= 0 ? min([srcsz + margin, size]) : size769endfunction770771function! s:getpos()772  return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}773endfunction774775function! s:border_opt(window)776  if type(a:window) != type({})777    return ''778  endif779780  " Border style781  let style = tolower(get(a:window, 'border', ''))782  if !has_key(a:window, 'border') && has_key(a:window, 'rounded')783    let style = a:window.rounded ? 'rounded' : 'sharp'784  endif785  if style == 'none' || style == 'no'786    return ''787  endif788789  " For --border styles, we need fzf 0.24.0 or above790  call fzf#exec('0.24.0')791  let opt = ' --border ' . style792  if has_key(a:window, 'highlight')793    let color = s:get_color('fg', a:window.highlight)794    if len(color)795      let opt .= ' --color=border:' . color796    endif797  endif798  return opt799endfunction800801function! s:split(dict)802  let directions = {803  \ 'up':    ['topleft', 'resize', &lines],804  \ 'down':  ['botright', 'resize', &lines],805  \ 'left':  ['vertical topleft', 'vertical resize', &columns],806  \ 'right': ['vertical botright', 'vertical resize', &columns] }807  let ppos = s:getpos()808  let is_popup = 0809  try810    if s:present(a:dict, 'window')811      if type(a:dict.window) == type({})812        if !s:popup_support()813          throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'814        end815        call s:popup(a:dict.window)816        let is_popup = 1817      else818        execute 'keepalt' a:dict.window819      endif820    elseif !s:splittable(a:dict)821      execute (tabpagenr()-1).'tabnew'822    else823      for [dir, triple] in items(directions)824        let val = get(a:dict, dir, '')825        if !empty(val)826          let [cmd, resz, max] = triple827          if (dir == 'up' || dir == 'down') && val[0] == '~'828            let sz = s:calc_size(max, val, a:dict)829          else830            let sz = s:calc_size(max, val, {})831          endif832          execute cmd sz.'new'833          execute resz sz834          return [ppos, {}, is_popup]835        endif836      endfor837    endif838    return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]839  finally840    if !is_popup841      setlocal winfixwidth winfixheight842    endif843  endtry844endfunction845846nnoremap <silent> <Plug>(fzf-insert) i847nnoremap <silent> <Plug>(fzf-normal) <Nop>848if exists(':tnoremap')849  tnoremap <silent> <Plug>(fzf-insert) <C-\><C-n>i850  tnoremap <silent> <Plug>(fzf-normal) <C-\><C-n>851endif852853let s:warned = 0854function! s:handle_ambidouble(dict)855  if &ambiwidth == 'double'856    let a:dict.env = { 'RUNEWIDTH_EASTASIAN': '1' }857  elseif !s:warned && $RUNEWIDTH_EASTASIAN == '1' && &ambiwidth !=# 'double'858    call s:warn("$RUNEWIDTH_EASTASIAN is '1' but &ambiwidth is not 'double'")859    2sleep860    let s:warned = 1861  endif862endfunction863864function! s:execute_term(dict, command, temps) abort865  let winrest = winrestcmd()866  let pbuf = bufnr('')867  let [ppos, winopts, is_popup] = s:split(a:dict)868  call s:use_sh()869  let b:fzf = a:dict870  let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,871            \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,872            \ 'columns': &columns, 'command': a:command }873  function! fzf.switch_back(inplace)874    if a:inplace && bufnr('') == self.buf875      if bufexists(self.pbuf)876        execute 'keepalt keepjumps b' self.pbuf877      endif878      " No other listed buffer879      if bufnr('') == self.buf880        enew881      endif882    endif883  endfunction884  function! fzf.on_exit(id, code, ...)885    if s:getpos() == self.ppos " {'window': 'enew'}886      for [opt, val] in items(self.winopts)887        execute 'let' opt '=' val888      endfor889      call self.switch_back(1)890    else891      if bufnr('') == self.buf892        " We use close instead of bd! since Vim does not close the split when893        " there's no other listed buffer (nvim +'set nobuflisted')894        close895      endif896      silent! execute 'tabnext' self.ppos.tab897      silent! execute self.ppos.win.'wincmd w'898    endif899900    if bufexists(self.buf)901      execute 'bd!' self.buf902    endif903904    if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos905      execute self.winrest906    endif907908    let lines = s:collect(self.temps)909    if !s:exit_handler(a:code, self.command, 1)910      return911    endif912913    call s:pushd(self.dict)914    call s:callback(self.dict, lines)915    call self.switch_back(s:getpos() == self.ppos)916917    if &buftype == 'terminal'918      call feedkeys(&filetype == 'fzf' ? "\<Plug>(fzf-insert)" : "\<Plug>(fzf-normal)")919    endif920  endfunction921922  try923    call s:pushd(a:dict)924    if s:is_win925      let fzf.temps.batchfile = s:fzf_tempname().'.bat'926      call s:writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)927      let command = fzf.temps.batchfile928    else929      let command = a:command930    endif931    let command .= s:term_marker932    if has('nvim')933      call s:handle_ambidouble(fzf)934      call termopen(command, fzf)935    else936      let term_opts = {'exit_cb': function(fzf.on_exit)}937      if v:version >= 802938        let term_opts.term_kill = 'term'939      endif940      if is_popup941        let term_opts.hidden = 1942      else943        let term_opts.curwin = 1944      endif945      call s:handle_ambidouble(term_opts)946      keepjumps let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)947      if is_popup && exists('#TerminalWinOpen')948        doautocmd <nomodeline> TerminalWinOpen949      endif950      if !has('patch-8.0.1261') && !s:is_win951        call term_wait(fzf.buf, 20)952      endif953    endif954    tnoremap <buffer> <c-z> <nop>955    if exists('&termwinkey') && (empty(&termwinkey) || &termwinkey =~? '<c-w>')956      tnoremap <buffer> <c-w> <c-w>.957    endif958  finally959    call s:dopopd()960  endtry961  setlocal nospell bufhidden=wipe nobuflisted nonumber962  setf fzf963  startinsert964  return []965endfunction966967function! s:collect(temps) abort968  try969    return filereadable(a:temps.result) ? readfile(a:temps.result) : []970  finally971    for tf in values(a:temps)972      silent! call delete(tf)973    endfor974  endtry975endfunction976977function! s:callback(dict, lines) abort978  let popd = has_key(a:dict, 'pushd')979  if popd980    let w:fzf_pushd = a:dict.pushd981  endif982983  try984    if has_key(a:dict, 'sink')985      for line in a:lines986        if type(a:dict.sink) == 2987          call a:dict.sink(line)988        else989          execute a:dict.sink s:escape(line)990        endif991      endfor992    endif993    if has_key(a:dict, 'sink*')994      call a:dict['sink*'](a:lines)995    elseif has_key(a:dict, 'sinklist')996      call a:dict['sinklist'](a:lines)997    endif998  catch999    if stridx(v:exception, ':E325:') < 01000      echoerr v:exception1001    endif1002  endtry10031004  " We may have opened a new window or tab1005  if popd1006    let w:fzf_pushd = a:dict.pushd1007    call s:dopopd()1008  endif1009endfunction10101011if has('nvim')1012  function s:create_popup(opts) abort1013    let buf = nvim_create_buf(v:false, v:true)1014    let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)1015    let win = nvim_open_win(buf, v:true, opts)1016    silent! call setwinvar(win, '&winhighlight', 'Pmenu:,Normal:Normal')1017    call setwinvar(win, '&colorcolumn', '')1018    return buf1019  endfunction1020else1021  function! s:create_popup(opts) abort1022    let s:popup_create = {buf -> popup_create(buf, #{1023      \ line: a:opts.row,1024      \ col: a:opts.col,1025      \ minwidth: a:opts.width,1026      \ maxwidth: a:opts.width,1027      \ minheight: a:opts.height,1028      \ maxheight: a:opts.height,1029      \ zindex: 1000,1030    \ })}1031    autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))1032  endfunction1033endif10341035function! s:popup(opts) abort1036  let xoffset = get(a:opts, 'xoffset', 0.5)1037  let yoffset = get(a:opts, 'yoffset', 0.5)1038  let relative = get(a:opts, 'relative', 0)10391040  " Use current window size for positioning relatively positioned popups1041  let columns = relative ? winwidth(0) : &columns1042  let lines = relative ? winheight(0) : (&lines - has('nvim'))10431044  " Size and position1045  let width = min([max([8, a:opts.width > 1 ? a:opts.width : float2nr(columns * a:opts.width)]), columns])1046  let height = min([max([4, a:opts.height > 1 ? a:opts.height : float2nr(lines * a:opts.height)]), lines])1047  let row = float2nr(yoffset * (lines - height)) + (relative ? win_screenpos(0)[0] - 1 : 0)1048  let col = float2nr(xoffset * (columns - width)) + (relative ? win_screenpos(0)[1] - 1 : 0)10491050  " Managing the differences1051  let row = min([max([0, row]), &lines - has('nvim') - height])1052  let col = min([max([0, col]), &columns - width])1053  let row += !has('nvim')1054  let col += !has('nvim')10551056  call s:create_popup({1057    \ 'row': row, 'col': col, 'width': width, 'height': height1058  \ })1059endfunction10601061let s:default_action = {1062  \ 'ctrl-t': 'tab split',1063  \ 'ctrl-x': 'split',1064  \ 'ctrl-v': 'vsplit' }10651066function! s:shortpath()1067  let short = fnamemodify(getcwd(), ':~:.')1068  if !has('win32unix')1069    let short = pathshorten(short)1070  endif1071  let slash = (s:is_win && !&shellslash) ? '\' : '/'1072  return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)1073endfunction10741075function! s:cmd(bang, ...) abort1076  let args = copy(a:000)1077  let opts = { 'options': ['--multi'] }1078  if len(args) && isdirectory(expand(args[-1]))1079    let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1080    if s:is_win && !&shellslash1081      let opts.dir = substitute(opts.dir, '/', '\\', 'g')1082    endif1083    let prompt = opts.dir1084  else1085    let prompt = s:shortpath()1086  endif1087  let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '1088  call extend(opts.options, ['--prompt', prompt])1089  call extend(opts.options, args)1090  call fzf#run(fzf#wrap('FZF', opts, a:bang))1091endfunction10921093command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)10941095let &cpo = s:cpo_save1096unlet s:cpo_save