Skip to content
Myr

fzf.vim

This file

Path

plugin/fzf.vim

1,098 lines 路 31.8 KiB

Last changed by

[vim] Keep jump list unaffected when calling term_startJunegunn Choibefore adoption3a96585

History of this file

Take it

1" Copyright (c) 2013-2023 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  try100    let [shell, &shell] = [&shell, shell]101    return s:fzf_call('shellescape', a:arg)102  finally103    let [shell, &shell] = [&shell, shell]104  endtry105endfunction106107function! s:fzf_getcwd()108  return s:fzf_call('getcwd')109endfunction110111function! s:fzf_fnamemodify(fname, mods)112  return s:fzf_call('fnamemodify', a:fname, a:mods)113endfunction114115function! s:fzf_expand(fmt)116  return s:fzf_call('expand', a:fmt, 1)117endfunction118119function! s:fzf_tempname()120  return s:fzf_call('tempname')121endfunction122123let s:layout_keys = ['window', 'tmux', 'up', 'down', 'left', 'right']124let s:fzf_go = s:base_dir.'/bin/fzf'125let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'126127let s:cpo_save = &cpo128set cpo&vim129130function! s:popup_support()131  return has('nvim') ? has('nvim-0.4') : has('popupwin') && has('patch-8.2.191')132endfunction133134function! s:default_layout()135  return s:popup_support()136        \ ? { 'window' : { 'width': 0.9, 'height': 0.6 } }137        \ : { 'down': '~40%' }138endfunction139140function! fzf#install()141  if s:is_win && !has('win32unix')142    let script = s:base_dir.'/install.ps1'143    if !filereadable(script)144      throw script.' not found'145    endif146    let script = 'powershell -ExecutionPolicy Bypass -file ' . shellescape(script)147  else148    let script = s:base_dir.'/install'149    if !executable(script)150      throw script.' not found'151    endif152    let script .= ' --bin'153  endif154155  call s:warn('Running fzf installer ...')156  call system(script)157  if v:shell_error158    throw 'Failed to download fzf: '.script159  endif160endfunction161162let s:versions = {}163function s:get_version(bin)164  if has_key(s:versions, a:bin)165    return s:versions[a:bin]166  end167  let command = (&shell =~ 'powershell\|pwsh' ? '&' : '') . s:fzf_call('shellescape', a:bin) . ' --version --no-height'168  let output = systemlist(command)169  if v:shell_error || empty(output)170    return ''171  endif172  let ver = matchstr(output[-1], '[0-9.]\+')173  let s:versions[a:bin] = ver174  return ver175endfunction176177function! s:compare_versions(a, b)178  let a = split(a:a, '\.')179  let b = split(a:b, '\.')180  for idx in range(0, max([len(a), len(b)]) - 1)181    let v1 = str2nr(get(a, idx, 0))182    let v2 = str2nr(get(b, idx, 0))183    if     v1 < v2 | return -1184    elseif v1 > v2 | return 1185    endif186  endfor187  return 0188endfunction189190function! s:compare_binary_versions(a, b)191  return s:compare_versions(s:get_version(a:a), s:get_version(a:b))192endfunction193194let s:checked = {}195function! fzf#exec(...)196  if !exists('s:exec')197    let binaries = []198    if executable('fzf')199      call add(binaries, 'fzf')200    endif201    if executable(s:fzf_go)202      call add(binaries, s:fzf_go)203    endif204205    if empty(binaries)206      if input('fzf executable not found. Download binary? (y/n) ') =~? '^y'207        redraw208        call fzf#install()209        return fzf#exec()210      else211        redraw212        throw 'fzf executable not found'213      endif214    elseif len(binaries) > 1215      call sort(binaries, 's:compare_binary_versions')216    endif217218    let s:exec = binaries[-1]219  endif220221  if a:0 && !has_key(s:checked, a:1)222    let fzf_version = s:get_version(s:exec)223    if empty(fzf_version)224      let message = printf('Failed to run "%s --version"', s:exec)225      unlet s:exec226      throw message227    end228229    if s:compare_versions(fzf_version, a:1) >= 0230      let s:checked[a:1] = 1231      return s:exec232    elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', a:1, fzf_version)) =~? '^y'233      let s:versions = {}234      unlet s:exec235      redraw236      call fzf#install()237      return fzf#exec(a:1, 1)238    else239      throw printf('You need to upgrade fzf (required: %s or above)', a:1)240    endif241  endif242243  return s:exec244endfunction245246function! s:tmux_enabled()247  if has('gui_running') || !exists('$TMUX')248    return 0249  endif250251  if exists('s:tmux')252    return s:tmux253  endif254255  let s:tmux = 0256  if !executable(s:fzf_tmux)257    if executable('fzf-tmux')258      let s:fzf_tmux = 'fzf-tmux'259    else260      return 0261    endif262  endif263264  let output = system('tmux -V')265  let s:tmux = !v:shell_error && output >= 'tmux 1.7'266  return s:tmux267endfunction268269function! s:escape(path)270  let path = fnameescape(a:path)271  return s:is_win ? escape(path, '$') : path272endfunction273274function! s:error(msg)275  echohl ErrorMsg276  echom a:msg277  echohl None278endfunction279280function! s:warn(msg)281  echohl WarningMsg282  echom a:msg283  echohl None284endfunction285286function! s:has_any(dict, keys)287  for key in a:keys288    if has_key(a:dict, key)289      return 1290    endif291  endfor292  return 0293endfunction294295function! s:open(cmd, target)296  if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')297    return298  endif299  execute a:cmd s:escape(a:target)300endfunction301302function! s:common_sink(action, lines) abort303  if len(a:lines) < 2304    return305  endif306  let key = remove(a:lines, 0)307  let Cmd = get(a:action, key, 'e')308  if type(Cmd) == type(function('call'))309    return Cmd(a:lines)310  endif311  if len(a:lines) > 1312    augroup fzf_swap313      autocmd SwapExists * let v:swapchoice='o'314            \| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))315    augroup END316  endif317  try318    let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified319    " Preserve the current working directory in case it's changed during320    " the execution (e.g. `set autochdir` or `autocmd BufEnter * lcd ...`)321    let cwd = exists('w:fzf_pushd') ? w:fzf_pushd.dir : expand('%:p:h')322    for item in a:lines323      if item[0] != '~' && item !~ (s:is_win ? '^[A-Z]:\' : '^/')324        let sep = s:is_win ? '\' : '/'325        let item = join([cwd, item], cwd[len(cwd)-1] == sep ? '' : sep)326      endif327      if empty328        execute 'e' s:escape(item)329        let empty = 0330      else331        call s:open(Cmd, item)332      endif333      if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')334            \ && isdirectory(item)335        doautocmd BufEnter336      endif337    endfor338  catch /^Vim:Interrupt$/339  finally340    silent! autocmd! fzf_swap341  endtry342endfunction343344function! s:get_color(attr, ...)345  " Force 24 bit colors: g:fzf_force_termguicolors (temporary workaround for https://github.com/junegunn/fzf.vim/issues/1152)346  let gui = get(g:, 'fzf_force_termguicolors', 0) || (!s:is_win && !has('win32unix') && has('termguicolors') && &termguicolors)347  let fam = gui ? 'gui' : 'cterm'348  let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'349  for group in a:000350    let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)351    if code =~? pat352      return code353    endif354  endfor355  return ''356endfunction357358function! s:defaults()359  let rules = copy(get(g:, 'fzf_colors', {}))360  let colors = join(map(items(filter(map(rules, 'call("s:get_color", v:val)'), '!empty(v:val)')), 'join(v:val, ":")'), ',')361  return empty(colors) ? '' : fzf#shellescape('--color='.colors)362endfunction363364function! s:validate_layout(layout)365  for key in keys(a:layout)366    if index(s:layout_keys, key) < 0367      throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',368            \ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')369    endif370  endfor371  return a:layout372endfunction373374function! s:evaluate_opts(options)375  return type(a:options) == type([]) ?376        \ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options377endfunction378379" [name string,] [opts dict,] [fullscreen boolean]380function! fzf#wrap(...)381  let args = ['', {}, 0]382  let expects = map(copy(args), 'type(v:val)')383  let tidx = 0384  for arg in copy(a:000)385    let tidx = index(expects, type(arg) == 6 ? type(0) : type(arg), tidx)386    if tidx < 0387      throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'388    endif389    let args[tidx] = arg390    let tidx += 1391    unlet arg392  endfor393  let [name, opts, bang] = args394395  if len(name)396    let opts.name = name397  end398399  " Layout: g:fzf_layout (and deprecated g:fzf_height)400  if bang401    for key in s:layout_keys402      if has_key(opts, key)403        call remove(opts, key)404      endif405    endfor406  elseif !s:has_any(opts, s:layout_keys)407    if !exists('g:fzf_layout') && exists('g:fzf_height')408      let opts.down = g:fzf_height409    else410      let opts = extend(opts, s:validate_layout(get(g:, 'fzf_layout', s:default_layout())))411    endif412  endif413414  " Colors: g:fzf_colors415  let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))416417  " History: g:fzf_history_dir418  if len(name) && len(get(g:, 'fzf_history_dir', ''))419    let dir = s:fzf_expand(g:fzf_history_dir)420    if !isdirectory(dir)421      call mkdir(dir, 'p')422    endif423    let history = fzf#shellescape(dir.'/'.name)424    let opts.options = join(['--history', history, opts.options])425  endif426427  " Action: g:fzf_action428  if !s:has_any(opts, ['sink', 'sinklist', 'sink*'])429    let opts._action = get(g:, 'fzf_action', s:default_action)430    let opts.options .= ' --expect='.join(keys(opts._action), ',')431    function! opts.sinklist(lines) abort432      return s:common_sink(self._action, a:lines)433    endfunction434    let opts['sink*'] = opts.sinklist " For backward compatibility435  endif436437  return opts438endfunction439440function! s:use_sh()441  let [shell, shellslash, shellcmdflag, shellxquote] = [&shell, &shellslash, &shellcmdflag, &shellxquote]442  if s:is_win443    set shell=cmd.exe444    set noshellslash445    let &shellcmdflag = has('nvim') ? '/s /c' : '/c'446    let &shellxquote = has('nvim') ? '"' : '('447  else448    set shell=sh449  endif450  return [shell, shellslash, shellcmdflag, shellxquote]451endfunction452453function! s:writefile(...)454  if call('writefile', a:000) == -1455    throw 'Failed to write temporary file. Check if you can write to the path tempname() returns.'456  endif457endfunction458459function! s:extract_option(opts, name)460  let opt = ''461  let expect = 0462  " There are a few cases where this function doesn't work as expected.463  " Let's just assume such cases are extremely unlikely in real world.464  "   e.g. --query --border465  for word in split(a:opts)466    if expect && word !~ '^"\=-'467      let opt = opt . ' ' . word468      let expect = 0469    elseif word == '--no-'.a:name470      let opt = ''471    elseif word =~ '^--'.a:name.'='472      let opt = word473    elseif word =~ '^--'.a:name.'$'474      let opt = word475      let expect = 1476    elseif expect477      let expect = 0478    endif479  endfor480  return opt481endfunction482483function! fzf#run(...) abort484try485  let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()486487  let dict   = exists('a:1') ? copy(a:1) : {}488  let temps  = { 'result': s:fzf_tempname() }489  let optstr = s:evaluate_opts(get(dict, 'options', ''))490  try491    let fzf_exec = shellescape(fzf#exec())492  catch493    throw v:exception494  endtry495496  if !s:present(dict, 'dir')497    let dict.dir = s:fzf_getcwd()498  endif499  if has('win32unix') && s:present(dict, 'dir')500    let dict.dir = fnamemodify(dict.dir, ':p')501  endif502503  if has_key(dict, 'source')504    let source = remove(dict, 'source')505    let type = type(source)506    if type == 1507      let source_command = source508    elseif type == 3509      let temps.input = s:fzf_tempname()510      call s:writefile(source, temps.input)511      let source_command = (s:is_win ? 'type ' : 'cat ').fzf#shellescape(temps.input)512    else513      throw 'Invalid source type'514    endif515  else516    let source_command = ''517  endif518519  let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')520  let use_height = has_key(dict, 'down') && !has('gui_running') &&521        \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&522        \ executable('tput') && filereadable('/dev/tty')523  let has_vim8_term = has('terminal') && has('patch-8.0.995')524  let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win525  let use_term = has_nvim_term ||526    \ has_vim8_term && !has('win32unix') && (has('gui_running') || s:is_win || s:present(dict, 'down', 'up', 'left', 'right', 'window'))527  let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()528  if prefer_tmux && use_tmux529    let use_height = 0530    let use_term = 0531  endif532  if use_term533    let optstr .= ' --no-height'534  elseif use_height535    let height = s:calc_size(&lines, dict.down, dict)536    let optstr .= ' --height='.height537  endif538  " Respect --border option given in $FZF_DEFAULT_OPTS and 'options'539  let optstr = join([s:border_opt(get(dict, 'window', 0)), s:extract_option($FZF_DEFAULT_OPTS, 'border'), optstr])540  let prev_default_command = $FZF_DEFAULT_COMMAND541  if len(source_command)542    let $FZF_DEFAULT_COMMAND = source_command543  endif544  let command = (use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result545546  if use_term547    return s:execute_term(dict, command, temps)548  endif549550  let lines = use_tmux ? s:execute_tmux(dict, command, temps)551                 \ : s:execute(dict, command, use_height, temps)552  call s:callback(dict, lines)553  return lines554finally555  if exists('source_command') && len(source_command)556    if len(prev_default_command)557      let $FZF_DEFAULT_COMMAND = prev_default_command558    else559      let $FZF_DEFAULT_COMMAND = ''560      silent! execute 'unlet $FZF_DEFAULT_COMMAND'561    endif562  endif563  let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]564endtry565endfunction566567function! s:present(dict, ...)568  for key in a:000569    if !empty(get(a:dict, key, ''))570      return 1571    endif572  endfor573  return 0574endfunction575576function! s:fzf_tmux(dict)577  let size = get(a:dict, 'tmux', '')578  if empty(size)579    for o in ['up', 'down', 'left', 'right']580      if s:present(a:dict, o)581        let spec = a:dict[o]582        if (o == 'up' || o == 'down') && spec[0] == '~'583          let size = '-'.o[0].s:calc_size(&lines, spec, a:dict)584        else585          " Legacy boolean option586          let size = '-'.o[0].(spec == 1 ? '' : substitute(spec, '^\~', '', ''))587        endif588        break589      endif590    endfor591  endif592  return printf('LINES=%d COLUMNS=%d %s %s - --',593    \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size)594endfunction595596function! s:splittable(dict)597  return s:present(a:dict, 'up', 'down') && &lines > 15 ||598        \ s:present(a:dict, 'left', 'right') && &columns > 40599endfunction600601function! s:pushd(dict)602  if s:present(a:dict, 'dir')603    let cwd = s:fzf_getcwd()604    let w:fzf_pushd = {605    \   'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),606    \   'origin': cwd,607    \   'bufname': bufname('')608    \ }609    execute 'lcd' s:escape(a:dict.dir)610    let cwd = s:fzf_getcwd()611    let w:fzf_pushd.dir = cwd612    let a:dict.pushd = w:fzf_pushd613    return cwd614  endif615  return ''616endfunction617618augroup fzf_popd619  autocmd!620  autocmd WinEnter * call s:dopopd()621augroup END622623function! s:dopopd()624  if !exists('w:fzf_pushd')625    return626  endif627628  " FIXME: We temporarily change the working directory to 'dir' entry629  " of options dictionary (set to the current working directory if not given)630  " before running fzf.631  "632  " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})633  "634  " After processing the sink function, we have to restore the current working635  " directory. But doing so may not be desirable if the function changed the636  " working directory on purpose.637  "638  " So how can we tell if we should do it or not? A simple heuristic we use639  " here is that we change directory only if the current working directory640  " matches 'dir' entry. However, it is possible that the sink function did641  " change the directory to 'dir'. In that case, the user will have an642  " unexpected result.643  if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))644    execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)645  endif646  unlet! w:fzf_pushd647endfunction648649function! s:xterm_launcher()650  let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'651  if has('gui_macvim')652    let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'653  endif654  return printf(fmt,655    \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),656    \ &columns, &lines/2, getwinposx(), getwinposy())657endfunction658unlet! s:launcher659if s:is_win || has('win32unix')660  let s:launcher = '%s'661else662  let s:launcher = function('s:xterm_launcher')663endif664665function! s:exit_handler(code, command, ...)666  if a:code == 130667    return 0668  elseif has('nvim') && a:code == 129669    " When deleting the terminal buffer while fzf is still running,670    " Nvim sends SIGHUP.671    return 0672  elseif a:code > 1673    call s:error('Error running ' . a:command)674    if !empty(a:000)675      sleep676    endif677    return 0678  endif679  return 1680endfunction681682function! s:execute(dict, command, use_height, temps) abort683  call s:pushd(a:dict)684  if has('unix') && !a:use_height685    silent! !clear 2> /dev/null686  endif687  let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')688  if has('gui_running')689    let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))690    let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher691    if has('unix')692      let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"693    endif694    let command = printf(fmt, escaped)695  else696    let command = escaped697  endif698  if s:is_win699    let batchfile = s:fzf_tempname().'.bat'700    call s:writefile(s:wrap_cmds(command), batchfile)701    let command = batchfile702    let a:temps.batchfile = batchfile703    if has('nvim')704      let fzf = {}705      let fzf.dict = a:dict706      let fzf.temps = a:temps707      function! fzf.on_exit(job_id, exit_status, event) dict708        call s:pushd(self.dict)709        let lines = s:collect(self.temps)710        call s:callback(self.dict, lines)711      endfunction712      let cmd = 'start /wait cmd /c '.command713      call jobstart(cmd, fzf)714      return []715    endif716  elseif has('win32unix') && $TERM !=# 'cygwin'717    let shellscript = s:fzf_tempname()718    call s:writefile([command], shellscript)719    let command = 'cmd.exe /C '.fzf#shellescape('set "TERM=" & start /WAIT sh -c '.shellscript)720    let a:temps.shellscript = shellscript721  endif722  if a:use_height723    call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s < /dev/tty 2> /dev/tty', &lines, command))724  else725    execute 'silent !'.command726  endif727  let exit_status = v:shell_error728  redraw!729  let lines = s:collect(a:temps)730  return s:exit_handler(exit_status, command) ? lines : []731endfunction732733function! s:execute_tmux(dict, command, temps) abort734  let command = a:command735  let cwd = s:pushd(a:dict)736  if len(cwd)737    " -c '#{pane_current_path}' is only available on tmux 1.9 or above738    let command = join(['cd', fzf#shellescape(cwd), '&&', command])739  endif740741  call system(command)742  let exit_status = v:shell_error743  redraw!744  let lines = s:collect(a:temps)745  return s:exit_handler(exit_status, command) ? lines : []746endfunction747748function! s:calc_size(max, val, dict)749  let val = substitute(a:val, '^\~', '', '')750  if val =~ '%$'751    let size = a:max * str2nr(val[:-2]) / 100752  else753    let size = min([a:max, str2nr(val)])754  endif755756  let srcsz = -1757  if type(get(a:dict, 'source', 0)) == type([])758    let srcsz = len(a:dict.source)759  endif760761  let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))762  if opts =~ 'preview'763    return size764  endif765  let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2766  let margin += match(opts, '--border\([^-]\|$\)') > match(opts, '--no-border\([^-]\|$\)') ? 2 : 0767  if stridx(opts, '--header') > stridx(opts, '--no-header')768    let margin += len(split(opts, "\n"))769  endif770  return srcsz >= 0 ? min([srcsz + margin, size]) : size771endfunction772773function! s:getpos()774  return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}775endfunction776777function! s:border_opt(window)778  if type(a:window) != type({})779    return ''780  endif781782  " Border style783  let style = tolower(get(a:window, 'border', ''))784  if !has_key(a:window, 'border') && has_key(a:window, 'rounded')785    let style = a:window.rounded ? 'rounded' : 'sharp'786  endif787  if style == 'none' || style == 'no'788    return ''789  endif790791  " For --border styles, we need fzf 0.24.0 or above792  call fzf#exec('0.24.0')793  let opt = ' --border ' . style794  if has_key(a:window, 'highlight')795    let color = s:get_color('fg', a:window.highlight)796    if len(color)797      let opt .= ' --color=border:' . color798    endif799  endif800  return opt801endfunction802803function! s:split(dict)804  let directions = {805  \ 'up':    ['topleft', 'resize', &lines],806  \ 'down':  ['botright', 'resize', &lines],807  \ 'left':  ['vertical topleft', 'vertical resize', &columns],808  \ 'right': ['vertical botright', 'vertical resize', &columns] }809  let ppos = s:getpos()810  let is_popup = 0811  try812    if s:present(a:dict, 'window')813      if type(a:dict.window) == type({})814        if !s:popup_support()815          throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'816        end817        call s:popup(a:dict.window)818        let is_popup = 1819      else820        execute 'keepalt' a:dict.window821      endif822    elseif !s:splittable(a:dict)823      execute (tabpagenr()-1).'tabnew'824    else825      for [dir, triple] in items(directions)826        let val = get(a:dict, dir, '')827        if !empty(val)828          let [cmd, resz, max] = triple829          if (dir == 'up' || dir == 'down') && val[0] == '~'830            let sz = s:calc_size(max, val, a:dict)831          else832            let sz = s:calc_size(max, val, {})833          endif834          execute cmd sz.'new'835          execute resz sz836          return [ppos, {}, is_popup]837        endif838      endfor839    endif840    return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]841  finally842    if !is_popup843      setlocal winfixwidth winfixheight844    endif845  endtry846endfunction847848nnoremap <silent> <Plug>(fzf-insert) i849nnoremap <silent> <Plug>(fzf-normal) <Nop>850if exists(':tnoremap')851  tnoremap <silent> <Plug>(fzf-insert) <C-\><C-n>i852  tnoremap <silent> <Plug>(fzf-normal) <C-\><C-n>853endif854855let s:warned = 0856function! s:handle_ambidouble(dict)857  if &ambiwidth == 'double'858    let a:dict.env = { 'RUNEWIDTH_EASTASIAN': '1' }859  elseif !s:warned && $RUNEWIDTH_EASTASIAN == '1' && &ambiwidth !=# 'double'860    call s:warn("$RUNEWIDTH_EASTASIAN is '1' but &ambiwidth is not 'double'")861    2sleep862    let s:warned = 1863  endif864endfunction865866function! s:execute_term(dict, command, temps) abort867  let winrest = winrestcmd()868  let pbuf = bufnr('')869  let [ppos, winopts, is_popup] = s:split(a:dict)870  call s:use_sh()871  let b:fzf = a:dict872  let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,873            \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,874            \ 'columns': &columns, 'command': a:command }875  function! fzf.switch_back(inplace)876    if a:inplace && bufnr('') == self.buf877      if bufexists(self.pbuf)878        execute 'keepalt keepjumps b' self.pbuf879      endif880      " No other listed buffer881      if bufnr('') == self.buf882        enew883      endif884    endif885  endfunction886  function! fzf.on_exit(id, code, ...)887    if s:getpos() == self.ppos " {'window': 'enew'}888      for [opt, val] in items(self.winopts)889        execute 'let' opt '=' val890      endfor891      call self.switch_back(1)892    else893      if bufnr('') == self.buf894        " We use close instead of bd! since Vim does not close the split when895        " there's no other listed buffer (nvim +'set nobuflisted')896        close897      endif898      silent! execute 'tabnext' self.ppos.tab899      silent! execute self.ppos.win.'wincmd w'900    endif901902    if bufexists(self.buf)903      execute 'bd!' self.buf904    endif905906    if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos907      execute self.winrest908    endif909910    let lines = s:collect(self.temps)911    if !s:exit_handler(a:code, self.command, 1)912      return913    endif914915    call s:pushd(self.dict)916    call s:callback(self.dict, lines)917    call self.switch_back(s:getpos() == self.ppos)918919    if &buftype == 'terminal'920      call feedkeys(&filetype == 'fzf' ? "\<Plug>(fzf-insert)" : "\<Plug>(fzf-normal)")921    endif922  endfunction923924  try925    call s:pushd(a:dict)926    if s:is_win927      let fzf.temps.batchfile = s:fzf_tempname().'.bat'928      call s:writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)929      let command = fzf.temps.batchfile930    else931      let command = a:command932    endif933    let command .= s:term_marker934    if has('nvim')935      call s:handle_ambidouble(fzf)936      call termopen(command, fzf)937    else938      let term_opts = {'exit_cb': function(fzf.on_exit)}939      if v:version >= 802940        let term_opts.term_kill = 'term'941      endif942      if is_popup943        let term_opts.hidden = 1944      else945        let term_opts.curwin = 1946      endif947      call s:handle_ambidouble(term_opts)948      keepjumps let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)949      if is_popup && exists('#TerminalWinOpen')950        doautocmd <nomodeline> TerminalWinOpen951      endif952      if !has('patch-8.0.1261') && !s:is_win953        call term_wait(fzf.buf, 20)954      endif955    endif956    tnoremap <buffer> <c-z> <nop>957    if exists('&termwinkey') && (empty(&termwinkey) || &termwinkey =~? '<c-w>')958      tnoremap <buffer> <c-w> <c-w>.959    endif960  finally961    call s:dopopd()962  endtry963  setlocal nospell bufhidden=wipe nobuflisted nonumber964  setf fzf965  startinsert966  return []967endfunction968969function! s:collect(temps) abort970  try971    return filereadable(a:temps.result) ? readfile(a:temps.result) : []972  finally973    for tf in values(a:temps)974      silent! call delete(tf)975    endfor976  endtry977endfunction978979function! s:callback(dict, lines) abort980  let popd = has_key(a:dict, 'pushd')981  if popd982    let w:fzf_pushd = a:dict.pushd983  endif984985  try986    if has_key(a:dict, 'sink')987      for line in a:lines988        if type(a:dict.sink) == 2989          call a:dict.sink(line)990        else991          execute a:dict.sink s:escape(line)992        endif993      endfor994    endif995    if has_key(a:dict, 'sink*')996      call a:dict['sink*'](a:lines)997    elseif has_key(a:dict, 'sinklist')998      call a:dict['sinklist'](a:lines)999    endif1000  catch1001    if stridx(v:exception, ':E325:') < 01002      echoerr v:exception1003    endif1004  endtry10051006  " We may have opened a new window or tab1007  if popd1008    let w:fzf_pushd = a:dict.pushd1009    call s:dopopd()1010  endif1011endfunction10121013if has('nvim')1014  function s:create_popup(opts) abort1015    let buf = nvim_create_buf(v:false, v:true)1016    let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)1017    let win = nvim_open_win(buf, v:true, opts)1018    silent! call setwinvar(win, '&winhighlight', 'Pmenu:,Normal:Normal')1019    call setwinvar(win, '&colorcolumn', '')1020    return buf1021  endfunction1022else1023  function! s:create_popup(opts) abort1024    let s:popup_create = {buf -> popup_create(buf, #{1025      \ line: a:opts.row,1026      \ col: a:opts.col,1027      \ minwidth: a:opts.width,1028      \ maxwidth: a:opts.width,1029      \ minheight: a:opts.height,1030      \ maxheight: a:opts.height,1031      \ zindex: 1000,1032    \ })}1033    autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))1034  endfunction1035endif10361037function! s:popup(opts) abort1038  let xoffset = get(a:opts, 'xoffset', 0.5)1039  let yoffset = get(a:opts, 'yoffset', 0.5)1040  let relative = get(a:opts, 'relative', 0)10411042  " Use current window size for positioning relatively positioned popups1043  let columns = relative ? winwidth(0) : &columns1044  let lines = relative ? winheight(0) : (&lines - has('nvim'))10451046  " Size and position1047  let width = min([max([8, a:opts.width > 1 ? a:opts.width : float2nr(columns * a:opts.width)]), columns])1048  let height = min([max([4, a:opts.height > 1 ? a:opts.height : float2nr(lines * a:opts.height)]), lines])1049  let row = float2nr(yoffset * (lines - height)) + (relative ? win_screenpos(0)[0] - 1 : 0)1050  let col = float2nr(xoffset * (columns - width)) + (relative ? win_screenpos(0)[1] - 1 : 0)10511052  " Managing the differences1053  let row = min([max([0, row]), &lines - has('nvim') - height])1054  let col = min([max([0, col]), &columns - width])1055  let row += !has('nvim')1056  let col += !has('nvim')10571058  call s:create_popup({1059    \ 'row': row, 'col': col, 'width': width, 'height': height1060  \ })1061endfunction10621063let s:default_action = {1064  \ 'ctrl-t': 'tab split',1065  \ 'ctrl-x': 'split',1066  \ 'ctrl-v': 'vsplit' }10671068function! s:shortpath()1069  let short = fnamemodify(getcwd(), ':~:.')1070  if !has('win32unix')1071    let short = pathshorten(short)1072  endif1073  let slash = (s:is_win && !&shellslash) ? '\' : '/'1074  return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)1075endfunction10761077function! s:cmd(bang, ...) abort1078  let args = copy(a:000)1079  let opts = { 'options': ['--multi'] }1080  if len(args) && isdirectory(expand(args[-1]))1081    let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1082    if s:is_win && !&shellslash1083      let opts.dir = substitute(opts.dir, '/', '\\', 'g')1084    endif1085    let prompt = opts.dir1086  else1087    let prompt = s:shortpath()1088  endif1089  let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '1090  call extend(opts.options, ['--prompt', prompt])1091  call extend(opts.options, args)1092  call fzf#run(fzf#wrap('FZF', opts, a:bang))1093endfunction10941095command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)10961097let &cpo = s:cpo_save1098unlet s:cpo_save