fzf.vim
This file
Path
plugin/fzf.vim
984 lines · 28.3 KiB
Last changed by
[vim] &termwinkey may not be availableJunegunn Choibefore adoption7acdaf0
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 return s:fzf_call('shellescape', a:arg)100endfunction101102function! s:fzf_getcwd()103 return s:fzf_call('getcwd')104endfunction105106function! s:fzf_fnamemodify(fname, mods)107 return s:fzf_call('fnamemodify', a:fname, a:mods)108endfunction109110function! s:fzf_expand(fmt)111 return s:fzf_call('expand', a:fmt, 1)112endfunction113114function! s:fzf_tempname()115 return s:fzf_call('tempname')116endfunction117118let s:layout_keys = ['window', 'tmux', 'up', 'down', 'left', 'right']119let s:fzf_go = s:base_dir.'/bin/fzf'120let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'121122let s:cpo_save = &cpo123set cpo&vim124125function! s:popup_support()126 return has('nvim') ? has('nvim-0.4') : has('popupwin') && has('patch-8.2.191')127endfunction128129function! s:default_layout()130 return s:popup_support()131 \ ? { 'window' : { 'width': 0.9, 'height': 0.6 } }132 \ : { 'down': '~40%' }133endfunction134135function! fzf#install()136 if s:is_win && !has('win32unix')137 let script = s:base_dir.'/install.ps1'138 if !filereadable(script)139 throw script.' not found'140 endif141 let script = 'powershell -ExecutionPolicy Bypass -file ' . script142 else143 let script = s:base_dir.'/install'144 if !executable(script)145 throw script.' not found'146 endif147 let script .= ' --bin'148 endif149150 call s:warn('Running fzf installer ...')151 call system(script)152 if v:shell_error153 throw 'Failed to download fzf: '.script154 endif155endfunction156157function! s:version_requirement(val, min)158 let val = split(a:val, '\.')159 let min = split(a:min, '\.')160 for idx in range(0, len(min) - 1)161 let v = get(val, idx, 0)162 if v < min[idx] | return 0163 elseif v > min[idx] | return 1164 endif165 endfor166 return 1167endfunction168169let s:checked = {}170function! fzf#exec(...)171 if !exists('s:exec')172 if executable(s:fzf_go)173 let s:exec = s:fzf_go174 elseif executable('fzf')175 let s:exec = 'fzf'176 elseif input('fzf executable not found. Download binary? (y/n) ') =~? '^y'177 redraw178 call fzf#install()179 return fzf#exec()180 else181 redraw182 throw 'fzf executable not found'183 endif184 endif185186 if a:0 && !has_key(s:checked, a:1)187 let command = s:exec . ' --version'188 let output = systemlist(command)189 if v:shell_error || empty(output)190 throw printf('Failed to run "%s": %s', command, output)191 endif192 let fzf_version = matchstr(output[-1], '[0-9.]\+')193 if s:version_requirement(fzf_version, a:1)194 let s:checked[a:1] = 1195 return s:exec196 elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', a:1, fzf_version)) =~? '^y'197 redraw198 call fzf#install()199 return fzf#exec(a:1, 1)200 else201 throw printf('You need to upgrade fzf (required: %s or above)', a:1)202 endif203 endif204205 return s:exec206endfunction207208function! s:tmux_enabled()209 if has('gui_running') || !exists('$TMUX')210 return 0211 endif212213 if exists('s:tmux')214 return s:tmux215 endif216217 let s:tmux = 0218 if !executable(s:fzf_tmux)219 if executable('fzf-tmux')220 let s:fzf_tmux = 'fzf-tmux'221 else222 return 0223 endif224 endif225226 let output = system('tmux -V')227 let s:tmux = !v:shell_error && output >= 'tmux 1.7'228 return s:tmux229endfunction230231function! s:escape(path)232 let path = fnameescape(a:path)233 return s:is_win ? escape(path, '$') : path234endfunction235236function! s:error(msg)237 echohl ErrorMsg238 echom a:msg239 echohl None240endfunction241242function! s:warn(msg)243 echohl WarningMsg244 echom a:msg245 echohl None246endfunction247248function! s:has_any(dict, keys)249 for key in a:keys250 if has_key(a:dict, key)251 return 1252 endif253 endfor254 return 0255endfunction256257function! s:open(cmd, target)258 if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')259 return260 endif261 execute a:cmd s:escape(a:target)262endfunction263264function! s:common_sink(action, lines) abort265 if len(a:lines) < 2266 return267 endif268 let key = remove(a:lines, 0)269 let Cmd = get(a:action, key, 'e')270 if type(Cmd) == type(function('call'))271 return Cmd(a:lines)272 endif273 if len(a:lines) > 1274 augroup fzf_swap275 autocmd SwapExists * let v:swapchoice='o'276 \| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))277 augroup END278 endif279 try280 let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified281 " Preserve the current working directory in case it's changed during282 " the execution (e.g. `set autochdir` or `autocmd BufEnter * lcd ...`)283 let cwd = exists('w:fzf_pushd') ? w:fzf_pushd.dir : expand('%:p:h')284 for item in a:lines285 if item[0] != '~' && item !~ (s:is_win ? '^[A-Z]:\' : '^/')286 let sep = s:is_win ? '\' : '/'287 let item = join([cwd, item], cwd[len(cwd)-1] == sep ? '' : sep)288 endif289 if empty290 execute 'e' s:escape(item)291 let empty = 0292 else293 call s:open(Cmd, item)294 endif295 if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')296 \ && isdirectory(item)297 doautocmd BufEnter298 endif299 endfor300 catch /^Vim:Interrupt$/301 finally302 silent! autocmd! fzf_swap303 endtry304endfunction305306function! s:get_color(attr, ...)307 let gui = !s:is_win && !has('win32unix') && has('termguicolors') && &termguicolors308 let fam = gui ? 'gui' : 'cterm'309 let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'310 for group in a:000311 let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)312 if code =~? pat313 return code314 endif315 endfor316 return ''317endfunction318319function! s:defaults()320 let rules = copy(get(g:, 'fzf_colors', {}))321 let colors = join(map(items(filter(map(rules, 'call("s:get_color", v:val)'), '!empty(v:val)')), 'join(v:val, ":")'), ',')322 return empty(colors) ? '' : fzf#shellescape('--color='.colors)323endfunction324325function! s:validate_layout(layout)326 for key in keys(a:layout)327 if index(s:layout_keys, key) < 0328 throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',329 \ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')330 endif331 endfor332 return a:layout333endfunction334335function! s:evaluate_opts(options)336 return type(a:options) == type([]) ?337 \ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options338endfunction339340" [name string,] [opts dict,] [fullscreen boolean]341function! fzf#wrap(...)342 let args = ['', {}, 0]343 let expects = map(copy(args), 'type(v:val)')344 let tidx = 0345 for arg in copy(a:000)346 let tidx = index(expects, type(arg) == 6 ? type(0) : type(arg), tidx)347 if tidx < 0348 throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'349 endif350 let args[tidx] = arg351 let tidx += 1352 unlet arg353 endfor354 let [name, opts, bang] = args355356 if len(name)357 let opts.name = name358 end359360 " Layout: g:fzf_layout (and deprecated g:fzf_height)361 if bang362 for key in s:layout_keys363 if has_key(opts, key)364 call remove(opts, key)365 endif366 endfor367 elseif !s:has_any(opts, s:layout_keys)368 if !exists('g:fzf_layout') && exists('g:fzf_height')369 let opts.down = g:fzf_height370 else371 let opts = extend(opts, s:validate_layout(get(g:, 'fzf_layout', s:default_layout())))372 endif373 endif374375 " Colors: g:fzf_colors376 let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))377378 " History: g:fzf_history_dir379 if len(name) && len(get(g:, 'fzf_history_dir', ''))380 let dir = s:fzf_expand(g:fzf_history_dir)381 if !isdirectory(dir)382 call mkdir(dir, 'p')383 endif384 let history = fzf#shellescape(dir.'/'.name)385 let opts.options = join(['--history', history, opts.options])386 endif387388 " Action: g:fzf_action389 if !s:has_any(opts, ['sink', 'sink*'])390 let opts._action = get(g:, 'fzf_action', s:default_action)391 let opts.options .= ' --expect='.join(keys(opts._action), ',')392 function! opts.sink(lines) abort393 return s:common_sink(self._action, a:lines)394 endfunction395 let opts['sink*'] = remove(opts, 'sink')396 endif397398 return opts399endfunction400401function! s:use_sh()402 let [shell, shellslash, shellcmdflag, shellxquote] = [&shell, &shellslash, &shellcmdflag, &shellxquote]403 if s:is_win404 set shell=cmd.exe405 set noshellslash406 let &shellcmdflag = has('nvim') ? '/s /c' : '/c'407 let &shellxquote = has('nvim') ? '"' : '('408 else409 set shell=sh410 endif411 return [shell, shellslash, shellcmdflag, shellxquote]412endfunction413414function! fzf#run(...) abort415try416 let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()417418 let dict = exists('a:1') ? copy(a:1) : {}419 let temps = { 'result': s:fzf_tempname() }420 let optstr = s:evaluate_opts(get(dict, 'options', ''))421 try422 let fzf_exec = fzf#shellescape(fzf#exec())423 catch424 throw v:exception425 endtry426427 if !has_key(dict, 'dir')428 let dict.dir = s:fzf_getcwd()429 endif430 if has('win32unix') && has_key(dict, 'dir')431 let dict.dir = fnamemodify(dict.dir, ':p')432 endif433434 if has_key(dict, 'source')435 let source = dict.source436 let type = type(source)437 if type == 1438 let prefix = '( '.source.' )|'439 elseif type == 3440 let temps.input = s:fzf_tempname()441 call writefile(source, temps.input)442 let prefix = (s:is_win ? 'type ' : 'cat ').fzf#shellescape(temps.input).'|'443 else444 throw 'Invalid source type'445 endif446 else447 let prefix = ''448 endif449450 let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')451 let use_height = has_key(dict, 'down') && !has('gui_running') &&452 \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&453 \ executable('tput') && filereadable('/dev/tty')454 let has_vim8_term = has('terminal') && has('patch-8.0.995')455 let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win456 let use_term = has_nvim_term ||457 \ has_vim8_term && !has('win32unix') && (has('gui_running') || s:is_win || !use_height && s:present(dict, 'down', 'up', 'left', 'right', 'window'))458 let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()459 if prefer_tmux && use_tmux460 let use_height = 0461 let use_term = 0462 endif463 if use_height464 let height = s:calc_size(&lines, dict.down, dict)465 let optstr .= ' --height='.height466 elseif use_term467 let optstr .= ' --no-height'468 endif469 let optstr .= s:border_opt(get(dict, 'window', 0))470 let command = prefix.(use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result471472 if use_term473 return s:execute_term(dict, command, temps)474 endif475476 let lines = use_tmux ? s:execute_tmux(dict, command, temps)477 \ : s:execute(dict, command, use_height, temps)478 call s:callback(dict, lines)479 return lines480finally481 let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]482endtry483endfunction484485function! s:present(dict, ...)486 for key in a:000487 if !empty(get(a:dict, key, ''))488 return 1489 endif490 endfor491 return 0492endfunction493494function! s:fzf_tmux(dict)495 let size = get(a:dict, 'tmux', '')496 if empty(size)497 for o in ['up', 'down', 'left', 'right']498 if s:present(a:dict, o)499 let spec = a:dict[o]500 if (o == 'up' || o == 'down') && spec[0] == '~'501 let size = '-'.o[0].s:calc_size(&lines, spec, a:dict)502 else503 " Legacy boolean option504 let size = '-'.o[0].(spec == 1 ? '' : substitute(spec, '^\~', '', ''))505 endif506 break507 endif508 endfor509 endif510 return printf('LINES=%d COLUMNS=%d %s %s %s --',511 \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))512endfunction513514function! s:splittable(dict)515 return s:present(a:dict, 'up', 'down') && &lines > 15 ||516 \ s:present(a:dict, 'left', 'right') && &columns > 40517endfunction518519function! s:pushd(dict)520 if s:present(a:dict, 'dir')521 let cwd = s:fzf_getcwd()522 let w:fzf_pushd = {523 \ 'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),524 \ 'origin': cwd,525 \ 'bufname': bufname('')526 \ }527 execute 'lcd' s:escape(a:dict.dir)528 let cwd = s:fzf_getcwd()529 let w:fzf_pushd.dir = cwd530 let a:dict.pushd = w:fzf_pushd531 return cwd532 endif533 return ''534endfunction535536augroup fzf_popd537 autocmd!538 autocmd WinEnter * call s:dopopd()539augroup END540541function! s:dopopd()542 if !exists('w:fzf_pushd')543 return544 endif545546 " FIXME: We temporarily change the working directory to 'dir' entry547 " of options dictionary (set to the current working directory if not given)548 " before running fzf.549 "550 " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})551 "552 " After processing the sink function, we have to restore the current working553 " directory. But doing so may not be desirable if the function changed the554 " working directory on purpose.555 "556 " So how can we tell if we should do it or not? A simple heuristic we use557 " here is that we change directory only if the current working directory558 " matches 'dir' entry. However, it is possible that the sink function did559 " change the directory to 'dir'. In that case, the user will have an560 " unexpected result.561 if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))562 execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)563 endif564 unlet! w:fzf_pushd565endfunction566567function! s:xterm_launcher()568 let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'569 if has('gui_macvim')570 let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'571 endif572 return printf(fmt,573 \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),574 \ &columns, &lines/2, getwinposx(), getwinposy())575endfunction576unlet! s:launcher577if s:is_win || has('win32unix')578 let s:launcher = '%s'579else580 let s:launcher = function('s:xterm_launcher')581endif582583function! s:exit_handler(code, command, ...)584 if a:code == 130585 return 0586 elseif has('nvim') && a:code == 129587 " When deleting the terminal buffer while fzf is still running,588 " Nvim sends SIGHUP.589 return 0590 elseif a:code > 1591 call s:error('Error running ' . a:command)592 if !empty(a:000)593 sleep594 endif595 return 0596 endif597 return 1598endfunction599600function! s:execute(dict, command, use_height, temps) abort601 call s:pushd(a:dict)602 if has('unix') && !a:use_height603 silent! !clear 2> /dev/null604 endif605 let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')606 if has('gui_running')607 let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))608 let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher609 if has('unix')610 let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"611 endif612 let command = printf(fmt, escaped)613 else614 let command = escaped615 endif616 if s:is_win617 let batchfile = s:fzf_tempname().'.bat'618 call writefile(s:wrap_cmds(command), batchfile)619 let command = batchfile620 let a:temps.batchfile = batchfile621 if has('nvim')622 let fzf = {}623 let fzf.dict = a:dict624 let fzf.temps = a:temps625 function! fzf.on_exit(job_id, exit_status, event) dict626 call s:pushd(self.dict)627 let lines = s:collect(self.temps)628 call s:callback(self.dict, lines)629 endfunction630 let cmd = 'start /wait cmd /c '.command631 call jobstart(cmd, fzf)632 return []633 endif634 elseif has('win32unix') && $TERM !=# 'cygwin'635 let shellscript = s:fzf_tempname()636 call writefile([command], shellscript)637 let command = 'cmd.exe /C '.fzf#shellescape('set "TERM=" & start /WAIT sh -c '.shellscript)638 let a:temps.shellscript = shellscript639 endif640 if a:use_height641 let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'642 call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))643 else644 execute 'silent !'.command645 endif646 let exit_status = v:shell_error647 redraw!648 let lines = s:collect(a:temps)649 return s:exit_handler(exit_status, command) ? lines : []650endfunction651652function! s:execute_tmux(dict, command, temps) abort653 let command = a:command654 let cwd = s:pushd(a:dict)655 if len(cwd)656 " -c '#{pane_current_path}' is only available on tmux 1.9 or above657 let command = join(['cd', fzf#shellescape(cwd), '&&', command])658 endif659660 call system(command)661 let exit_status = v:shell_error662 redraw!663 let lines = s:collect(a:temps)664 return s:exit_handler(exit_status, command) ? lines : []665endfunction666667function! s:calc_size(max, val, dict)668 let val = substitute(a:val, '^\~', '', '')669 if val =~ '%$'670 let size = a:max * str2nr(val[:-2]) / 100671 else672 let size = min([a:max, str2nr(val)])673 endif674675 let srcsz = -1676 if type(get(a:dict, 'source', 0)) == type([])677 let srcsz = len(a:dict.source)678 endif679680 let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))681 if opts =~ 'preview'682 return size683 endif684 let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2685 let margin += stridx(opts, '--border') > stridx(opts, '--no-border') ? 2 : 0686 if stridx(opts, '--header') > stridx(opts, '--no-header')687 let margin += len(split(opts, "\n"))688 endif689 return srcsz >= 0 ? min([srcsz + margin, size]) : size690endfunction691692function! s:getpos()693 return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}694endfunction695696function! s:border_opt(window)697 if type(a:window) != type({})698 return ''699 endif700701 " Border style702 let style = tolower(get(a:window, 'border', 'rounded'))703 if !has_key(a:window, 'border') && !get(a:window, 'rounded', 1)704 let style = 'sharp'705 endif706 if style == 'none' || style == 'no'707 return ''708 endif709710 " For --border styles, we need fzf 0.24.0 or above711 call fzf#exec('0.24.0')712 let opt = ' --border=' . style713 if has_key(a:window, 'highlight')714 let color = s:get_color('fg', a:window.highlight)715 if len(color)716 let opt .= ' --color=border:' . color717 endif718 endif719 return opt720endfunction721722function! s:split(dict)723 let directions = {724 \ 'up': ['topleft', 'resize', &lines],725 \ 'down': ['botright', 'resize', &lines],726 \ 'left': ['vertical topleft', 'vertical resize', &columns],727 \ 'right': ['vertical botright', 'vertical resize', &columns] }728 let ppos = s:getpos()729 let is_popup = 0730 try731 if s:present(a:dict, 'window')732 if type(a:dict.window) == type({})733 if !s:popup_support()734 throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'735 end736 call s:popup(a:dict.window)737 let is_popup = 1738 else739 execute 'keepalt' a:dict.window740 endif741 elseif !s:splittable(a:dict)742 execute (tabpagenr()-1).'tabnew'743 else744 for [dir, triple] in items(directions)745 let val = get(a:dict, dir, '')746 if !empty(val)747 let [cmd, resz, max] = triple748 if (dir == 'up' || dir == 'down') && val[0] == '~'749 let sz = s:calc_size(max, val, a:dict)750 else751 let sz = s:calc_size(max, val, {})752 endif753 execute cmd sz.'new'754 execute resz sz755 return [ppos, {}, is_popup]756 endif757 endfor758 endif759 return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]760 finally761 if !is_popup762 setlocal winfixwidth winfixheight763 endif764 endtry765endfunction766767function! s:execute_term(dict, command, temps) abort768 let winrest = winrestcmd()769 let pbuf = bufnr('')770 let [ppos, winopts, is_popup] = s:split(a:dict)771 call s:use_sh()772 let b:fzf = a:dict773 let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,774 \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,775 \ 'columns': &columns, 'command': a:command }776 function! fzf.switch_back(inplace)777 if a:inplace && bufnr('') == self.buf778 if bufexists(self.pbuf)779 execute 'keepalt b' self.pbuf780 endif781 " No other listed buffer782 if bufnr('') == self.buf783 enew784 endif785 endif786 endfunction787 function! fzf.on_exit(id, code, ...)788 if s:getpos() == self.ppos " {'window': 'enew'}789 for [opt, val] in items(self.winopts)790 execute 'let' opt '=' val791 endfor792 call self.switch_back(1)793 else794 if bufnr('') == self.buf795 " We use close instead of bd! since Vim does not close the split when796 " there's no other listed buffer (nvim +'set nobuflisted')797 close798 endif799 silent! execute 'tabnext' self.ppos.tab800 silent! execute self.ppos.win.'wincmd w'801 endif802803 if bufexists(self.buf)804 execute 'bd!' self.buf805 endif806807 if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos808 execute self.winrest809 endif810811 let lines = s:collect(self.temps)812 if !s:exit_handler(a:code, self.command, 1)813 return814 endif815816 call s:pushd(self.dict)817 call s:callback(self.dict, lines)818 call self.switch_back(s:getpos() == self.ppos)819 endfunction820821 try822 call s:pushd(a:dict)823 if s:is_win824 let fzf.temps.batchfile = s:fzf_tempname().'.bat'825 call writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)826 let command = fzf.temps.batchfile827 else828 let command = a:command829 endif830 let command .= s:term_marker831 if has('nvim')832 call termopen(command, fzf)833 else834 let term_opts = {'exit_cb': function(fzf.on_exit)}835 if is_popup836 let term_opts.hidden = 1837 else838 let term_opts.curwin = 1839 endif840 let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)841 if exists('&termwinkey')842 call setbufvar(fzf.buf, '&termwinkey', '<c-z>')843 endif844 if is_popup && exists('#TerminalWinOpen')845 doautocmd <nomodeline> TerminalWinOpen846 endif847 if !has('patch-8.0.1261') && !s:is_win848 call term_wait(fzf.buf, 20)849 endif850 endif851 tnoremap <buffer> <c-z> <nop>852 finally853 call s:dopopd()854 endtry855 setlocal nospell bufhidden=wipe nobuflisted nonumber856 setf fzf857 startinsert858 return []859endfunction860861function! s:collect(temps) abort862 try863 return filereadable(a:temps.result) ? readfile(a:temps.result) : []864 finally865 for tf in values(a:temps)866 silent! call delete(tf)867 endfor868 endtry869endfunction870871function! s:callback(dict, lines) abort872 let popd = has_key(a:dict, 'pushd')873 if popd874 let w:fzf_pushd = a:dict.pushd875 endif876877 try878 if has_key(a:dict, 'sink')879 for line in a:lines880 if type(a:dict.sink) == 2881 call a:dict.sink(line)882 else883 execute a:dict.sink s:escape(line)884 endif885 endfor886 endif887 if has_key(a:dict, 'sink*')888 call a:dict['sink*'](a:lines)889 endif890 catch891 if stridx(v:exception, ':E325:') < 0892 echoerr v:exception893 endif894 endtry895896 " We may have opened a new window or tab897 if popd898 let w:fzf_pushd = a:dict.pushd899 call s:dopopd()900 endif901endfunction902903if has('nvim')904 function s:create_popup(hl, opts) abort905 let buf = nvim_create_buf(v:false, v:true)906 let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)907 let border = has_key(opts, 'border') ? remove(opts, 'border') : []908 let win = nvim_open_win(buf, v:true, opts)909 call setwinvar(win, '&winhighlight', 'NormalFloat:'..a:hl)910 call setwinvar(win, '&colorcolumn', '')911 if !empty(border)912 call nvim_buf_set_lines(buf, 0, -1, v:true, border)913 endif914 return buf915 endfunction916else917 function! s:create_popup(hl, opts) abort918 let s:popup_create = {buf -> popup_create(buf, #{919 \ line: a:opts.row,920 \ col: a:opts.col,921 \ minwidth: a:opts.width,922 \ maxwidth: a:opts.width,923 \ minheight: a:opts.height,924 \ maxheight: a:opts.height,925 \ zindex: 1000,926 \ })}927 autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))928 endfunction929endif930931function! s:popup(opts) abort932 " Size and position933 let width = min([max([8, a:opts.width > 1 ? a:opts.width : float2nr(&columns * a:opts.width)]), &columns])934 let height = min([max([4, a:opts.height > 1 ? a:opts.height : float2nr(&lines * a:opts.height)]), &lines - has('nvim')])935 let row = float2nr(get(a:opts, 'yoffset', 0.5) * (&lines - height))936 let col = float2nr(get(a:opts, 'xoffset', 0.5) * (&columns - width))937938 " Managing the differences939 let row = min([max([0, row]), &lines - has('nvim') - height])940 let col = min([max([0, col]), &columns - width])941 let row += !has('nvim')942 let col += !has('nvim')943944 call s:create_popup('Normal', {945 \ 'row': row, 'col': col, 'width': width, 'height': height946 \ })947endfunction948949let s:default_action = {950 \ 'ctrl-t': 'tab split',951 \ 'ctrl-x': 'split',952 \ 'ctrl-v': 'vsplit' }953954function! s:shortpath()955 let short = fnamemodify(getcwd(), ':~:.')956 if !has('win32unix')957 let short = pathshorten(short)958 endif959 let slash = (s:is_win && !&shellslash) ? '\' : '/'960 return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)961endfunction962963function! s:cmd(bang, ...) abort964 let args = copy(a:000)965 let opts = { 'options': ['--multi'] }966 if len(args) && isdirectory(expand(args[-1]))967 let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')968 if s:is_win && !&shellslash969 let opts.dir = substitute(opts.dir, '/', '\\', 'g')970 endif971 let prompt = opts.dir972 else973 let prompt = s:shortpath()974 endif975 let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '976 call extend(opts.options, ['--prompt', prompt])977 call extend(opts.options, args)978 call fzf#run(fzf#wrap('FZF', opts, a:bang))979endfunction980981command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)982983let &cpo = s:cpo_save984unlet s:cpo_save