fzf.vim
This file
Path
plugin/fzf.vim
1,060 lines · 30.6 KiB
Last changed by
[neovim] Use Normal group colors for floating windowJunegunn Choibefore adoption2eec989
History of this fileTake 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 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' ? '&' : '') . 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! fzf#run(...) abort460try461 let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()462463 let dict = exists('a:1') ? copy(a:1) : {}464 let temps = { 'result': s:fzf_tempname() }465 let optstr = s:evaluate_opts(get(dict, 'options', ''))466 try467 let fzf_exec = shellescape(fzf#exec())468 catch469 throw v:exception470 endtry471472 if !s:present(dict, 'dir')473 let dict.dir = s:fzf_getcwd()474 endif475 if has('win32unix') && s:present(dict, 'dir')476 let dict.dir = fnamemodify(dict.dir, ':p')477 endif478479 if has_key(dict, 'source')480 let source = remove(dict, 'source')481 let type = type(source)482 if type == 1483 let source_command = source484 elseif type == 3485 let temps.input = s:fzf_tempname()486 call s:writefile(source, temps.input)487 let source_command = (s:is_win ? 'type ' : 'cat ').fzf#shellescape(temps.input)488 else489 throw 'Invalid source type'490 endif491 else492 let source_command = ''493 endif494495 let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')496 let use_height = has_key(dict, 'down') && !has('gui_running') &&497 \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&498 \ executable('tput') && filereadable('/dev/tty')499 let has_vim8_term = has('terminal') && has('patch-8.0.995')500 let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win501 let use_term = has_nvim_term ||502 \ has_vim8_term && !has('win32unix') && (has('gui_running') || s:is_win || s:present(dict, 'down', 'up', 'left', 'right', 'window'))503 let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()504 if prefer_tmux && use_tmux505 let use_height = 0506 let use_term = 0507 endif508 if use_term509 let optstr .= ' --no-height'510 elseif use_height511 let height = s:calc_size(&lines, dict.down, dict)512 let optstr .= ' --height='.height513 endif514 let optstr .= s:border_opt(get(dict, 'window', 0))515 let prev_default_command = $FZF_DEFAULT_COMMAND516 if len(source_command)517 let $FZF_DEFAULT_COMMAND = source_command518 endif519 let command = (use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result520521 if use_term522 return s:execute_term(dict, command, temps)523 endif524525 let lines = use_tmux ? s:execute_tmux(dict, command, temps)526 \ : s:execute(dict, command, use_height, temps)527 call s:callback(dict, lines)528 return lines529finally530 if exists('source_command') && len(source_command)531 if len(prev_default_command)532 let $FZF_DEFAULT_COMMAND = prev_default_command533 else534 let $FZF_DEFAULT_COMMAND = ''535 silent! execute 'unlet $FZF_DEFAULT_COMMAND'536 endif537 endif538 let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]539endtry540endfunction541542function! s:present(dict, ...)543 for key in a:000544 if !empty(get(a:dict, key, ''))545 return 1546 endif547 endfor548 return 0549endfunction550551function! s:fzf_tmux(dict)552 let size = get(a:dict, 'tmux', '')553 if empty(size)554 for o in ['up', 'down', 'left', 'right']555 if s:present(a:dict, o)556 let spec = a:dict[o]557 if (o == 'up' || o == 'down') && spec[0] == '~'558 let size = '-'.o[0].s:calc_size(&lines, spec, a:dict)559 else560 " Legacy boolean option561 let size = '-'.o[0].(spec == 1 ? '' : substitute(spec, '^\~', '', ''))562 endif563 break564 endif565 endfor566 endif567 return printf('LINES=%d COLUMNS=%d %s %s - --',568 \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size)569endfunction570571function! s:splittable(dict)572 return s:present(a:dict, 'up', 'down') && &lines > 15 ||573 \ s:present(a:dict, 'left', 'right') && &columns > 40574endfunction575576function! s:pushd(dict)577 if s:present(a:dict, 'dir')578 let cwd = s:fzf_getcwd()579 let w:fzf_pushd = {580 \ 'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),581 \ 'origin': cwd,582 \ 'bufname': bufname('')583 \ }584 execute 'lcd' s:escape(a:dict.dir)585 let cwd = s:fzf_getcwd()586 let w:fzf_pushd.dir = cwd587 let a:dict.pushd = w:fzf_pushd588 return cwd589 endif590 return ''591endfunction592593augroup fzf_popd594 autocmd!595 autocmd WinEnter * call s:dopopd()596augroup END597598function! s:dopopd()599 if !exists('w:fzf_pushd')600 return601 endif602603 " FIXME: We temporarily change the working directory to 'dir' entry604 " of options dictionary (set to the current working directory if not given)605 " before running fzf.606 "607 " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})608 "609 " After processing the sink function, we have to restore the current working610 " directory. But doing so may not be desirable if the function changed the611 " working directory on purpose.612 "613 " So how can we tell if we should do it or not? A simple heuristic we use614 " here is that we change directory only if the current working directory615 " matches 'dir' entry. However, it is possible that the sink function did616 " change the directory to 'dir'. In that case, the user will have an617 " unexpected result.618 if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))619 execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)620 endif621 unlet! w:fzf_pushd622endfunction623624function! s:xterm_launcher()625 let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'626 if has('gui_macvim')627 let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'628 endif629 return printf(fmt,630 \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),631 \ &columns, &lines/2, getwinposx(), getwinposy())632endfunction633unlet! s:launcher634if s:is_win || has('win32unix')635 let s:launcher = '%s'636else637 let s:launcher = function('s:xterm_launcher')638endif639640function! s:exit_handler(code, command, ...)641 if a:code == 130642 return 0643 elseif has('nvim') && a:code == 129644 " When deleting the terminal buffer while fzf is still running,645 " Nvim sends SIGHUP.646 return 0647 elseif a:code > 1648 call s:error('Error running ' . a:command)649 if !empty(a:000)650 sleep651 endif652 return 0653 endif654 return 1655endfunction656657function! s:execute(dict, command, use_height, temps) abort658 call s:pushd(a:dict)659 if has('unix') && !a:use_height660 silent! !clear 2> /dev/null661 endif662 let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')663 if has('gui_running')664 let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))665 let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher666 if has('unix')667 let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"668 endif669 let command = printf(fmt, escaped)670 else671 let command = escaped672 endif673 if s:is_win674 let batchfile = s:fzf_tempname().'.bat'675 call s:writefile(s:wrap_cmds(command), batchfile)676 let command = batchfile677 let a:temps.batchfile = batchfile678 if has('nvim')679 let fzf = {}680 let fzf.dict = a:dict681 let fzf.temps = a:temps682 function! fzf.on_exit(job_id, exit_status, event) dict683 call s:pushd(self.dict)684 let lines = s:collect(self.temps)685 call s:callback(self.dict, lines)686 endfunction687 let cmd = 'start /wait cmd /c '.command688 call jobstart(cmd, fzf)689 return []690 endif691 elseif has('win32unix') && $TERM !=# 'cygwin'692 let shellscript = s:fzf_tempname()693 call s:writefile([command], shellscript)694 let command = 'cmd.exe /C '.fzf#shellescape('set "TERM=" & start /WAIT sh -c '.shellscript)695 let a:temps.shellscript = shellscript696 endif697 if a:use_height698 call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s < /dev/tty 2> /dev/tty', &lines, command))699 else700 execute 'silent !'.command701 endif702 let exit_status = v:shell_error703 redraw!704 let lines = s:collect(a:temps)705 return s:exit_handler(exit_status, command) ? lines : []706endfunction707708function! s:execute_tmux(dict, command, temps) abort709 let command = a:command710 let cwd = s:pushd(a:dict)711 if len(cwd)712 " -c '#{pane_current_path}' is only available on tmux 1.9 or above713 let command = join(['cd', fzf#shellescape(cwd), '&&', command])714 endif715716 call system(command)717 let exit_status = v:shell_error718 redraw!719 let lines = s:collect(a:temps)720 return s:exit_handler(exit_status, command) ? lines : []721endfunction722723function! s:calc_size(max, val, dict)724 let val = substitute(a:val, '^\~', '', '')725 if val =~ '%$'726 let size = a:max * str2nr(val[:-2]) / 100727 else728 let size = min([a:max, str2nr(val)])729 endif730731 let srcsz = -1732 if type(get(a:dict, 'source', 0)) == type([])733 let srcsz = len(a:dict.source)734 endif735736 let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))737 if opts =~ 'preview'738 return size739 endif740 let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2741 let margin += stridx(opts, '--border') > stridx(opts, '--no-border') ? 2 : 0742 if stridx(opts, '--header') > stridx(opts, '--no-header')743 let margin += len(split(opts, "\n"))744 endif745 return srcsz >= 0 ? min([srcsz + margin, size]) : size746endfunction747748function! s:getpos()749 return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}750endfunction751752function! s:border_opt(window)753 if type(a:window) != type({})754 return ''755 endif756757 " Border style758 let style = tolower(get(a:window, 'border', 'rounded'))759 if !has_key(a:window, 'border') && !get(a:window, 'rounded', 1)760 let style = 'sharp'761 endif762 if style == 'none' || style == 'no'763 return ''764 endif765766 " For --border styles, we need fzf 0.24.0 or above767 call fzf#exec('0.24.0')768 let opt = ' --border=' . style769 if has_key(a:window, 'highlight')770 let color = s:get_color('fg', a:window.highlight)771 if len(color)772 let opt .= ' --color=border:' . color773 endif774 endif775 return opt776endfunction777778function! s:split(dict)779 let directions = {780 \ 'up': ['topleft', 'resize', &lines],781 \ 'down': ['botright', 'resize', &lines],782 \ 'left': ['vertical topleft', 'vertical resize', &columns],783 \ 'right': ['vertical botright', 'vertical resize', &columns] }784 let ppos = s:getpos()785 let is_popup = 0786 try787 if s:present(a:dict, 'window')788 if type(a:dict.window) == type({})789 if !s:popup_support()790 throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'791 end792 call s:popup(a:dict.window)793 let is_popup = 1794 else795 execute 'keepalt' a:dict.window796 endif797 elseif !s:splittable(a:dict)798 execute (tabpagenr()-1).'tabnew'799 else800 for [dir, triple] in items(directions)801 let val = get(a:dict, dir, '')802 if !empty(val)803 let [cmd, resz, max] = triple804 if (dir == 'up' || dir == 'down') && val[0] == '~'805 let sz = s:calc_size(max, val, a:dict)806 else807 let sz = s:calc_size(max, val, {})808 endif809 execute cmd sz.'new'810 execute resz sz811 return [ppos, {}, is_popup]812 endif813 endfor814 endif815 return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]816 finally817 if !is_popup818 setlocal winfixwidth winfixheight819 endif820 endtry821endfunction822823nnoremap <silent> <Plug>(fzf-insert) i824nnoremap <silent> <Plug>(fzf-normal) <Nop>825if exists(':tnoremap')826 tnoremap <silent> <Plug>(fzf-insert) <C-\><C-n>i827 tnoremap <silent> <Plug>(fzf-normal) <C-\><C-n>828endif829830function! s:execute_term(dict, command, temps) abort831 let winrest = winrestcmd()832 let pbuf = bufnr('')833 let [ppos, winopts, is_popup] = s:split(a:dict)834 call s:use_sh()835 let b:fzf = a:dict836 let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,837 \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,838 \ 'columns': &columns, 'command': a:command }839 function! fzf.switch_back(inplace)840 if a:inplace && bufnr('') == self.buf841 if bufexists(self.pbuf)842 execute 'keepalt keepjumps b' self.pbuf843 endif844 " No other listed buffer845 if bufnr('') == self.buf846 enew847 endif848 endif849 endfunction850 function! fzf.on_exit(id, code, ...)851 if s:getpos() == self.ppos " {'window': 'enew'}852 for [opt, val] in items(self.winopts)853 execute 'let' opt '=' val854 endfor855 call self.switch_back(1)856 else857 if bufnr('') == self.buf858 " We use close instead of bd! since Vim does not close the split when859 " there's no other listed buffer (nvim +'set nobuflisted')860 close861 endif862 silent! execute 'tabnext' self.ppos.tab863 silent! execute self.ppos.win.'wincmd w'864 endif865866 if bufexists(self.buf)867 execute 'bd!' self.buf868 endif869870 if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos871 execute self.winrest872 endif873874 let lines = s:collect(self.temps)875 if !s:exit_handler(a:code, self.command, 1)876 return877 endif878879 call s:pushd(self.dict)880 call s:callback(self.dict, lines)881 call self.switch_back(s:getpos() == self.ppos)882883 if &buftype == 'terminal'884 call feedkeys(&filetype == 'fzf' ? "\<Plug>(fzf-insert)" : "\<Plug>(fzf-normal)")885 endif886 endfunction887888 try889 call s:pushd(a:dict)890 if s:is_win891 let fzf.temps.batchfile = s:fzf_tempname().'.bat'892 call s:writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)893 let command = fzf.temps.batchfile894 else895 let command = a:command896 endif897 let command .= s:term_marker898 if has('nvim')899 call termopen(command, fzf)900 else901 let term_opts = {'exit_cb': function(fzf.on_exit)}902 if v:version >= 802903 let term_opts.term_kill = 'term'904 endif905 if is_popup906 let term_opts.hidden = 1907 else908 let term_opts.curwin = 1909 endif910 let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)911 if is_popup && exists('#TerminalWinOpen')912 doautocmd <nomodeline> TerminalWinOpen913 endif914 if !has('patch-8.0.1261') && !s:is_win915 call term_wait(fzf.buf, 20)916 endif917 endif918 tnoremap <buffer> <c-z> <nop>919 if exists('&termwinkey') && (empty(&termwinkey) || &termwinkey =~? '<c-w>')920 tnoremap <buffer> <c-w> <c-w>.921 endif922 finally923 call s:dopopd()924 endtry925 setlocal nospell bufhidden=wipe nobuflisted nonumber926 setf fzf927 startinsert928 return []929endfunction930931function! s:collect(temps) abort932 try933 return filereadable(a:temps.result) ? readfile(a:temps.result) : []934 finally935 for tf in values(a:temps)936 silent! call delete(tf)937 endfor938 endtry939endfunction940941function! s:callback(dict, lines) abort942 let popd = has_key(a:dict, 'pushd')943 if popd944 let w:fzf_pushd = a:dict.pushd945 endif946947 try948 if has_key(a:dict, 'sink')949 for line in a:lines950 if type(a:dict.sink) == 2951 call a:dict.sink(line)952 else953 execute a:dict.sink s:escape(line)954 endif955 endfor956 endif957 if has_key(a:dict, 'sink*')958 call a:dict['sink*'](a:lines)959 elseif has_key(a:dict, 'sinklist')960 call a:dict['sinklist'](a:lines)961 endif962 catch963 if stridx(v:exception, ':E325:') < 0964 echoerr v:exception965 endif966 endtry967968 " We may have opened a new window or tab969 if popd970 let w:fzf_pushd = a:dict.pushd971 call s:dopopd()972 endif973endfunction974975if has('nvim')976 function s:create_popup(opts) abort977 let buf = nvim_create_buf(v:false, v:true)978 let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)979 let win = nvim_open_win(buf, v:true, opts)980 silent! call setwinvar(win, '&winhighlight', 'Pmenu:,Normal:Normal')981 call setwinvar(win, '&colorcolumn', '')982 return buf983 endfunction984else985 function! s:create_popup(opts) abort986 let s:popup_create = {buf -> popup_create(buf, #{987 \ line: a:opts.row,988 \ col: a:opts.col,989 \ minwidth: a:opts.width,990 \ maxwidth: a:opts.width,991 \ minheight: a:opts.height,992 \ maxheight: a:opts.height,993 \ zindex: 1000,994 \ })}995 autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))996 endfunction997endif998999function! s:popup(opts) abort1000 let xoffset = get(a:opts, 'xoffset', 0.5)1001 let yoffset = get(a:opts, 'yoffset', 0.5)1002 let relative = get(a:opts, 'relative', 0)10031004 " Use current window size for positioning relatively positioned popups1005 let columns = relative ? winwidth(0) : &columns1006 let lines = relative ? winheight(0) : (&lines - has('nvim'))10071008 " Size and position1009 let width = min([max([8, a:opts.width > 1 ? a:opts.width : float2nr(columns * a:opts.width)]), columns])1010 let height = min([max([4, a:opts.height > 1 ? a:opts.height : float2nr(lines * a:opts.height)]), lines])1011 let row = float2nr(yoffset * (lines - height)) + (relative ? win_screenpos(0)[0] - 1 : 0)1012 let col = float2nr(xoffset * (columns - width)) + (relative ? win_screenpos(0)[1] - 1 : 0)10131014 " Managing the differences1015 let row = min([max([0, row]), &lines - has('nvim') - height])1016 let col = min([max([0, col]), &columns - width])1017 let row += !has('nvim')1018 let col += !has('nvim')10191020 call s:create_popup({1021 \ 'row': row, 'col': col, 'width': width, 'height': height1022 \ })1023endfunction10241025let s:default_action = {1026 \ 'ctrl-t': 'tab split',1027 \ 'ctrl-x': 'split',1028 \ 'ctrl-v': 'vsplit' }10291030function! s:shortpath()1031 let short = fnamemodify(getcwd(), ':~:.')1032 if !has('win32unix')1033 let short = pathshorten(short)1034 endif1035 let slash = (s:is_win && !&shellslash) ? '\' : '/'1036 return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)1037endfunction10381039function! s:cmd(bang, ...) abort1040 let args = copy(a:000)1041 let opts = { 'options': ['--multi'] }1042 if len(args) && isdirectory(expand(args[-1]))1043 let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1044 if s:is_win && !&shellslash1045 let opts.dir = substitute(opts.dir, '/', '\\', 'g')1046 endif1047 let prompt = opts.dir1048 else1049 let prompt = s:shortpath()1050 endif1051 let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '1052 call extend(opts.options, ['--prompt', prompt])1053 call extend(opts.options, args)1054 call fzf#run(fzf#wrap('FZF', opts, a:bang))1055endfunction10561057command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)10581059let &cpo = s:cpo_save1060unlet s:cpo_save