Skip to content
Myr

fzf.vim

This file

Path

plugin/fzf.vim

1,103 lines · 31.9 KiB

Last changed by

[vim] Use 24-bit colors on gvim even when &termguicolors is offJunegunn Choibefore adoption779e3cc

History of this file

Take it

The walk stopped after 200 commits: lines older than fd513f8 point at it.

Add missing --list-border=* parserJunegunn Choibefore adoptionfd513f8

lines 1–360why, one step back
1" Copyright (c) 2013-2024 Junegunn Choi
2"3" MIT License4"5" Permission is hereby granted, free of charge, to any person obtaining6" a copy of this software and associated documentation files (the7" "Software"), to deal in the Software without restriction, including8" without limitation the rights to use, copy, modify, merge, publish,9" distribute, sublicense, and/or sell copies of the Software, and to10" permit persons to whom the Software is furnished to do so, subject to11" the following conditions:12"13" The above copyright notice and this permission notice shall be14" included in all copies or substantial portions of the Software.15"16" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,17" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF18" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND19" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE20" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION21" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION22" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.2324if exists('g:loaded_fzf')25 finish26endif27let g:loaded_fzf = 12829let s:is_win = has('win32') || has('win64')30if s:is_win && &shellslash31 set noshellslash32 let s:base_dir = expand('<sfile>:h:h')33 set shellslash34else35 let s:base_dir = expand('<sfile>:h:h')36endif37if s:is_win38 let s:term_marker = '&::FZF'3940 function! s:fzf_call(fn, ...)41 let shellslash = &shellslash42 try43 set noshellslash44 return call(a:fn, a:000)45 finally46 let &shellslash = shellslash47 endtry48 endfunction4950 " Use utf-8 for fzf.vim commands51 " Return array of shell commands for cmd.exe52 function! s:enc_to_cp(str)53 if !has('iconv')54 return a:str55 endif56 if !exists('s:codepage')57 let s:codepage = libcallnr('kernel32.dll', 'GetACP', 0)58 endif59 return iconv(a:str, &encoding, 'cp'.s:codepage)60 endfunction61 function! s:wrap_cmds(cmds)62 return map(['@echo off']63 \ + (has('gui_running') ? ['set TERM= > nul'] : [])64 \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds]),65 \ '<SID>enc_to_cp(v:val."\r")')66 endfunction67else68 let s:term_marker = ";#FZF"6970 function! s:fzf_call(fn, ...)71 return call(a:fn, a:000)72 endfunction7374 function! s:wrap_cmds(cmds)75 return a:cmds76 endfunction7778 function! s:enc_to_cp(str)79 return a:str80 endfunction81endif8283function! s:shellesc_cmd(arg)84 let e = '"'85 let slashes = 086 for c in split(a:arg, '\zs')87 if c ==# '\'88 let slashes += 189 elseif c ==# '"'90 let e .= repeat('\', slashes + 1)91 let slashes = 092 else93 let slashes = 094 endif95 let e .= c96 endfor97 let e .= repeat('\', slashes) .'"'98 return substitute(substitute(e, '[&|<>()^!"]', '^&', 'g'), '%', '%%', 'g')99endfunction100101function! fzf#shellescape(arg, ...)102 let shell = get(a:000, 0, s:is_win ? 'cmd.exe' : 'sh')103 if shell =~# 'cmd.exe$'104 return s:shellesc_cmd(a:arg)105 endif106 try107 let [shell, &shell] = [&shell, shell]108 return s:fzf_call('shellescape', a:arg)109 finally110 let [shell, &shell] = [&shell, shell]111 endtry112endfunction113114function! s:fzf_getcwd()115 return s:fzf_call('getcwd')116endfunction117118function! s:fzf_fnamemodify(fname, mods)119 return s:fzf_call('fnamemodify', a:fname, a:mods)120endfunction121122function! s:fzf_expand(fmt)123 return s:fzf_call('expand', a:fmt, 1)124endfunction125126function! s:fzf_tempname()127 return s:fzf_call('tempname')128endfunction129130let s:layout_keys = ['window', 'tmux', 'up', 'down', 'left', 'right']131let s:fzf_go = s:base_dir.'/bin/fzf'132let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'133134let s:cpo_save = &cpo135set cpo&vim136137function! s:popup_support()138 return has('nvim') ? has('nvim-0.4') : has('popupwin') && has('patch-8.2.191')139endfunction140141function! s:default_layout()142 return s:popup_support()143 \ ? { 'window' : { 'width': 0.9, 'height': 0.6 } }144 \ : { 'down': '~40%' }145endfunction146147function! fzf#install()148 if s:is_win && !has('win32unix')149 let script = s:base_dir.'/install.ps1'150 if !filereadable(script)151 throw script.' not found'152 endif153 let script = 'powershell -ExecutionPolicy Bypass -file ' . shellescape(script)154 else155 let script = s:base_dir.'/install'156 if !executable(script)157 throw script.' not found'158 endif159 let script .= ' --bin'160 endif161162 call s:warn('Running fzf installer ...')163 call system(script)164 if v:shell_error165 throw 'Failed to download fzf: '.script166 endif167endfunction168169let s:versions = {}170function s:get_version(bin)171 if has_key(s:versions, a:bin)172 return s:versions[a:bin]173 end174 let command = (&shell =~ 'powershell\|pwsh' ? '&' : '') . s:fzf_call('shellescape', a:bin) . ' --version --no-height'175 let output = systemlist(command)176 if v:shell_error || empty(output)177 return ''178 endif179 let ver = matchstr(output[-1], '[0-9.]\+')180 let s:versions[a:bin] = ver181 return ver182endfunction183184function! s:compare_versions(a, b)185 let a = split(a:a, '\.')186 let b = split(a:b, '\.')187 for idx in range(0, max([len(a), len(b)]) - 1)188 let v1 = str2nr(get(a, idx, 0))189 let v2 = str2nr(get(b, idx, 0))190 if v1 < v2 | return -1191 elseif v1 > v2 | return 1192 endif193 endfor194 return 0195endfunction196197function! s:compare_binary_versions(a, b)198 return s:compare_versions(s:get_version(a:a), s:get_version(a:b))199endfunction200201let s:min_version = '0.53.0'202let s:checked = {}203function! fzf#exec(...)204 if !exists('s:exec')205 let binaries = []206 if executable('fzf')207 call add(binaries, 'fzf')208 endif209 if executable(s:fzf_go)210 call add(binaries, s:fzf_go)211 endif212213 if empty(binaries)214 if input('fzf executable not found. Download binary? (y/n) ') =~? '^y'215 redraw216 call fzf#install()217 return fzf#exec()218 else219 redraw220 throw 'fzf executable not found'221 endif222 elseif len(binaries) > 1223 call sort(binaries, 's:compare_binary_versions')224 endif225226 let s:exec = binaries[-1]227 endif228229 let min_version = s:min_version230 if a:0 && s:compare_versions(a:1, min_version) > 0231 let min_version = a:1232 endif233 if !has_key(s:checked, min_version)234 let fzf_version = s:get_version(s:exec)235 if empty(fzf_version)236 let message = printf('Failed to run "%s --version"', s:exec)237 unlet s:exec238 throw message239 end240241 if s:compare_versions(fzf_version, min_version) >= 0242 let s:checked[min_version] = 1243 return s:exec244 elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', min_version, fzf_version)) =~? '^y'245 let s:versions = {}246 unlet s:exec247 redraw248 call fzf#install()249 return fzf#exec(min_version, 1)250 else251 throw printf('You need to upgrade fzf (required: %s or above)', min_version)252 endif253 endif254255 return s:exec256endfunction257258function! s:tmux_enabled()259 if has('gui_running') || !exists('$TMUX')260 return 0261 endif262263 if exists('s:tmux')264 return s:tmux265 endif266267 let s:tmux = 0268 if !executable(s:fzf_tmux)269 if executable('fzf-tmux')270 let s:fzf_tmux = 'fzf-tmux'271 else272 return 0273 endif274 endif275276 let output = system('tmux -V')277 let s:tmux = !v:shell_error && output >= 'tmux 1.7'278 return s:tmux279endfunction280281function! s:escape(path)282 let path = fnameescape(a:path)283 return s:is_win ? escape(path, '$') : path284endfunction285286function! s:error(msg)287 echohl ErrorMsg288 echom a:msg289 echohl None290endfunction291292function! s:warn(msg)293 echohl WarningMsg294 echom a:msg295 echohl None296endfunction297298function! s:has_any(dict, keys)299 for key in a:keys300 if has_key(a:dict, key)301 return 1302 endif303 endfor304 return 0305endfunction306307function! s:open(cmd, target)308 if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')309 return310 endif311 execute a:cmd s:escape(a:target)312endfunction313314function! s:common_sink(action, lines) abort315 if len(a:lines) < 2316 return317 endif318 let key = remove(a:lines, 0)319 let Cmd = get(a:action, key, 'e')320 if type(Cmd) == type(function('call'))321 return Cmd(a:lines)322 endif323 if len(a:lines) > 1324 augroup fzf_swap325 autocmd SwapExists * let v:swapchoice='o'326 \| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))327 augroup END328 endif329 try330 let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified331 " Preserve the current working directory in case it's changed during332 " the execution (e.g. `set autochdir` or `autocmd BufEnter * lcd ...`)333 let cwd = exists('w:fzf_pushd') ? w:fzf_pushd.dir : expand('%:p:h')334 for item in a:lines335 if has('win32unix') && item !~ '/'336 let item = substitute(item, '\', '/', 'g')337 end338 if item[0] != '~' && item !~ (s:is_win ? '^\([A-Z]:\)\?\' : '^/')339 let sep = s:is_win ? '\' : '/'340 let item = join([cwd, item], cwd[len(cwd)-1] == sep ? '' : sep)341 endif342 if empty343 execute 'e' s:escape(item)344 let empty = 0345 else346 call s:open(Cmd, item)347 endif348 if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')349 \ && isdirectory(item)350 doautocmd BufEnter351 endif352 endfor353 catch /^Vim:Interrupt$/354 finally355 silent! autocmd! fzf_swap356 endtry357endfunction358359function! s:get_color(attr, ...)360 " Force 24 bit colors: g:fzf_force_termguicolors (temporary workaround for https://github.com/junegunn/fzf.vim/issues/1152)

[vim] Use 24-bit colors on gvim even when &termguicolors is offJunegunn Choibefore adoption779e3cc

line 361why, one step back
361 let gui = get(g:, 'fzf_force_termguicolors', 0) || (!s:is_win && !has('win32unix') && (has('gui_running') || has('termguicolors') && &termguicolors))

Add missing --list-border=* parserJunegunn Choibefore adoptionfd513f8

lines 362–1083why, one step back
362 let fam = gui ? 'gui' : 'cterm'
363 let pat = gui ? '^#[a-f0-9]\+' : '^[0-9]\+$'364 for group in a:000365 let code = synIDattr(synIDtrans(hlID(group)), a:attr, fam)366 if code =~? pat367 return code368 endif369 endfor370 return ''371endfunction372373function! s:defaults()374 let rules = copy(get(g:, 'fzf_colors', {}))375 let colors = join(map(items(filter(map(rules, 'call("s:get_color", v:val)'), '!empty(v:val)')), 'join(v:val, ":")'), ',')376 return empty(colors) ? '' : fzf#shellescape('--color='.colors)377endfunction378379function! s:validate_layout(layout)380 for key in keys(a:layout)381 if index(s:layout_keys, key) < 0382 throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',383 \ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')384 endif385 endfor386 return a:layout387endfunction388389function! s:evaluate_opts(options)390 return type(a:options) == type([]) ?391 \ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options392endfunction393394" [name string,] [opts dict,] [fullscreen boolean]395function! fzf#wrap(...)396 let args = ['', {}, 0]397 let expects = map(copy(args), 'type(v:val)')398 let tidx = 0399 for arg in copy(a:000)400 let tidx = index(expects, type(arg) == 6 ? type(0) : type(arg), tidx)401 if tidx < 0402 throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'403 endif404 let args[tidx] = arg405 let tidx += 1406 unlet arg407 endfor408 let [name, opts, bang] = args409410 if len(name)411 let opts.name = name412 end413414 " Layout: g:fzf_layout (and deprecated g:fzf_height)415 if bang416 for key in s:layout_keys417 if has_key(opts, key)418 call remove(opts, key)419 endif420 endfor421 elseif !s:has_any(opts, s:layout_keys)422 if !exists('g:fzf_layout') && exists('g:fzf_height')423 let opts.down = g:fzf_height424 else425 let opts = extend(opts, s:validate_layout(get(g:, 'fzf_layout', s:default_layout())))426 endif427 endif428429 " Colors: g:fzf_colors430 let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))431432 " History: g:fzf_history_dir433 if len(name) && len(get(g:, 'fzf_history_dir', ''))434 let dir = s:fzf_expand(g:fzf_history_dir)435 if !isdirectory(dir)436 call mkdir(dir, 'p')437 endif438 let history = fzf#shellescape(dir.'/'.name)439 let opts.options = join(['--history', history, opts.options])440 endif441442 " Action: g:fzf_action443 if !s:has_any(opts, ['sink', 'sinklist', 'sink*'])444 let opts._action = get(g:, 'fzf_action', s:default_action)445 let opts.options .= ' --expect='.join(keys(opts._action), ',')446 function! opts.sinklist(lines) abort447 return s:common_sink(self._action, a:lines)448 endfunction449 let opts['sink*'] = opts.sinklist " For backward compatibility450 endif451452 return opts453endfunction454455function! s:use_sh()456 let [shell, shellslash, shellcmdflag, shellxquote] = [&shell, &shellslash, &shellcmdflag, &shellxquote]457 if s:is_win458 set shell=cmd.exe459 set noshellslash460 let &shellcmdflag = has('nvim') ? '/s /c' : '/c'461 let &shellxquote = has('nvim') ? '"' : '('462 else463 set shell=sh464 endif465 return [shell, shellslash, shellcmdflag, shellxquote]466endfunction467468function! s:writefile(...)469 if call('writefile', a:000) == -1470 throw 'Failed to write temporary file. Check if you can write to the path tempname() returns.'471 endif472endfunction473474function! s:extract_option(opts, name)475 let opt = ''476 let expect = 0477 " There are a few cases where this function doesn't work as expected.478 " Let's just assume such cases are extremely unlikely in real world.479 " e.g. --query --border480 for word in split(a:opts)481 if expect && word !~ '^"\=-'482 let opt = opt . ' ' . word483 let expect = 0484 elseif word == '--no-'.a:name485 let opt = ''486 elseif word =~ '^--'.a:name.'='487 let opt = word488 elseif word =~ '^--'.a:name.'$'489 let opt = word490 let expect = 1491 elseif expect492 let expect = 0493 endif494 endfor495 return opt496endfunction497498let s:need_cmd_window = has('win32unix') && $TERM_PROGRAM ==# 'mintty' && s:compare_versions($TERM_PROGRAM_VERSION, '3.4.5') < 0 && !executable('winpty')499500function! fzf#run(...) abort501try502 let [shell, shellslash, shellcmdflag, shellxquote] = s:use_sh()503504 let dict = exists('a:1') ? copy(a:1) : {}505 let temps = { 'result': s:fzf_tempname() }506 let optstr = s:evaluate_opts(get(dict, 'options', ''))507 try508 let fzf_exec = shellescape(fzf#exec())509 catch510 throw v:exception511 endtry512513 if !s:present(dict, 'dir')514 let dict.dir = s:fzf_getcwd()515 endif516 if has('win32unix') && s:present(dict, 'dir')517 let dict.dir = fnamemodify(dict.dir, ':p')518 endif519520 if has_key(dict, 'source')521 let source = dict.source522 let type = type(source)523 if type == 1524 let prefix = '('.source.')|'525 elseif type == 3526 let temps.input = s:fzf_tempname()527 call s:writefile(source, temps.input)528 let prefix = (s:is_win ? 'type ' : 'command cat ').fzf#shellescape(temps.input).'|'529 else530 throw 'Invalid source type'531 endif532 else533 let prefix = ''534 endif535536 let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0) || has_key(dict, 'tmux')537 let use_height = has_key(dict, 'down') && !has('gui_running') &&538 \ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right', 'window')) &&539 \ executable('tput') && filereadable('/dev/tty')540 let has_vim8_term = has('terminal') && has('patch-8.0.995')541 let has_nvim_term = has('nvim-0.2.1') || has('nvim') && !s:is_win542 let use_term = has_nvim_term || has_vim8_term543 \ && !s:need_cmd_window544 \ && (has('gui_running') || s:is_win || s:present(dict, 'down', 'up', 'left', 'right', 'window'))545 let use_tmux = (has_key(dict, 'tmux') || (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:splittable(dict)) && s:tmux_enabled()546 if prefer_tmux && use_tmux547 let use_height = 0548 let use_term = 0549 endif550 if use_term551 let optstr .= ' --no-height --no-tmux'552 elseif use_height553 let height = s:calc_size(&lines, dict.down, dict)554 let optstr .= ' --no-tmux --height='.height555 endif556 " Respect --border option given in $FZF_DEFAULT_OPTS and 'options'557 let optstr = join([s:border_opt(get(dict, 'window', 0)), s:extract_option($FZF_DEFAULT_OPTS, 'border'), optstr])558 let command = prefix.(use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result559560 if use_term561 return s:execute_term(dict, command, temps)562 endif563564 let lines = use_tmux ? s:execute_tmux(dict, command, temps)565 \ : s:execute(dict, command, use_height, temps)566 call s:callback(dict, lines)567 return lines568finally569 let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]570endtry571endfunction572573function! s:present(dict, ...)574 for key in a:000575 if !empty(get(a:dict, key, ''))576 return 1577 endif578 endfor579 return 0580endfunction581582function! s:fzf_tmux(dict)583 let size = get(a:dict, 'tmux', '')584 if empty(size)585 for o in ['up', 'down', 'left', 'right']586 if s:present(a:dict, o)587 let size = o . ',' . a:dict[o]588 break589 endif590 endfor591 endif592593 " Legacy fzf-tmux options594 if size =~ '-'595 return printf('LINES=%d COLUMNS=%d %s %s %s --',596 \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))597 end598599 " Using native --tmux option600 let in = (has_key(a:dict, 'source') ? '' : ' --force-tty-in')601 return printf('%s --tmux %s%s', fzf#shellescape(fzf#exec()), size, in)602endfunction603604function! s:splittable(dict)605 return s:present(a:dict, 'up', 'down') && &lines > 15 ||606 \ s:present(a:dict, 'left', 'right') && &columns > 40607endfunction608609function! s:pushd(dict)610 if s:present(a:dict, 'dir')611 let cwd = s:fzf_getcwd()612 let w:fzf_pushd = {613 \ 'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),614 \ 'origin': cwd,615 \ 'bufname': bufname('')616 \ }617 execute 'lcd' s:escape(a:dict.dir)618 let cwd = s:fzf_getcwd()619 let w:fzf_pushd.dir = cwd620 let a:dict.pushd = w:fzf_pushd621 return cwd622 endif623 return ''624endfunction625626augroup fzf_popd627 autocmd!628 autocmd WinEnter * call s:dopopd()629augroup END630631function! s:dopopd()632 if !exists('w:fzf_pushd')633 return634 endif635636 " FIXME: We temporarily change the working directory to 'dir' entry637 " of options dictionary (set to the current working directory if not given)638 " before running fzf.639 "640 " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})641 "642 " After processing the sink function, we have to restore the current working643 " directory. But doing so may not be desirable if the function changed the644 " working directory on purpose.645 "646 " So how can we tell if we should do it or not? A simple heuristic we use647 " here is that we change directory only if the current working directory648 " matches 'dir' entry. However, it is possible that the sink function did649 " change the directory to 'dir'. In that case, the user will have an650 " unexpected result.651 if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))652 execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)653 endif654 unlet! w:fzf_pushd655endfunction656657function! s:xterm_launcher()658 let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'659 if has('gui_macvim')660 let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'661 endif662 return printf(fmt,663 \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),664 \ &columns, &lines/2, getwinposx(), getwinposy())665endfunction666unlet! s:launcher667if s:is_win || has('win32unix')668 let s:launcher = '%s'669else670 let s:launcher = function('s:xterm_launcher')671endif672673function! s:exit_handler(dict, code, command, ...)674 if has_key(a:dict, 'exit')675 call a:dict.exit(a:code)676 endif677 if a:code == 2678 call s:error('Error running ' . a:command)679 if !empty(a:000)680 sleep681 endif682 endif683 return a:code684endfunction685686function! s:execute(dict, command, use_height, temps) abort687 call s:pushd(a:dict)688 if has('unix') && !a:use_height689 silent! !clear 2> /dev/null690 endif691 let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')692 if has('gui_running')693 let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))694 let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher695 if has('unix')696 let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"697 endif698 let command = printf(fmt, escaped)699 else700 let command = escaped701 endif702 if s:is_win703 let batchfile = s:fzf_tempname().'.bat'704 call s:writefile(s:wrap_cmds(command), batchfile)705 let command = batchfile706 let a:temps.batchfile = batchfile707 if has('nvim')708 let fzf = {}709 let fzf.dict = a:dict710 let fzf.temps = a:temps711 function! fzf.on_exit(job_id, exit_status, event) dict712 call s:pushd(self.dict)713 let lines = s:collect(self.temps)714 call s:callback(self.dict, lines)715 endfunction716 let cmd = 'start /wait cmd /c '.command717 call jobstart(cmd, fzf)718 return []719 endif720 elseif s:need_cmd_window721 let shellscript = s:fzf_tempname()722 call s:writefile([command], shellscript)723 let command = 'start //WAIT sh -c '.shellscript724 let a:temps.shellscript = shellscript725 endif726 if a:use_height727 let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'728 call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))729 else730 execute 'silent !'.command731 endif732 let exit_status = v:shell_error733 redraw!734 let lines = s:collect(a:temps)735 return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []736endfunction737738function! s:execute_tmux(dict, command, temps) abort739 let command = a:command740 let cwd = s:pushd(a:dict)741 if len(cwd)742 " -c '#{pane_current_path}' is only available on tmux 1.9 or above743 let command = join(['cd', fzf#shellescape(cwd), '&&', command])744 endif745746 call system(command)747 let exit_status = v:shell_error748 redraw!749 let lines = s:collect(a:temps)750 return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []751endfunction752753function! s:calc_size(max, val, dict)754 let val = substitute(a:val, '^\~', '', '')755 if val =~ '%$'756 let size = a:max * str2nr(val[:-2]) / 100757 else758 let size = min([a:max, str2nr(val)])759 endif760761 let srcsz = -1762 if type(get(a:dict, 'source', 0)) == type([])763 let srcsz = len(a:dict.source)764 endif765766 let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))767 if opts =~ 'preview'768 return size769 endif770 let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2771 let margin += match(opts, '--border\([^-]\|$\)') > match(opts, '--no-border\([^-]\|$\)') ? 2 : 0772 if stridx(opts, '--header') > stridx(opts, '--no-header')773 let margin += len(split(opts, "\n"))774 endif775 return srcsz >= 0 ? min([srcsz + margin, size]) : size776endfunction777778function! s:getpos()779 return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}780endfunction781782function! s:border_opt(window)783 if type(a:window) != type({})784 return ''785 endif786787 " Border style788 let style = tolower(get(a:window, 'border', ''))789 if !has_key(a:window, 'border') && has_key(a:window, 'rounded')790 let style = a:window.rounded ? 'rounded' : 'sharp'791 endif792 if style == 'none' || style == 'no'793 return ''794 endif795796 " For --border styles, we need fzf 0.24.0 or above797 call fzf#exec('0.24.0')798 let opt = ' --border ' . style799 if has_key(a:window, 'highlight')800 let color = s:get_color('fg', a:window.highlight)801 if len(color)802 let opt .= ' --color=border:' . color803 endif804 endif805 return opt806endfunction807808function! s:split(dict)809 let directions = {810 \ 'up': ['topleft', 'resize', &lines],811 \ 'down': ['botright', 'resize', &lines],812 \ 'left': ['vertical topleft', 'vertical resize', &columns],813 \ 'right': ['vertical botright', 'vertical resize', &columns] }814 let ppos = s:getpos()815 let is_popup = 0816 try817 if s:present(a:dict, 'window')818 if type(a:dict.window) == type({})819 if !s:popup_support()820 throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'821 end822 call s:popup(a:dict.window)823 let is_popup = 1824 else825 execute 'keepalt' a:dict.window826 endif827 elseif !s:splittable(a:dict)828 execute (tabpagenr()-1).'tabnew'829 else830 for [dir, triple] in items(directions)831 let val = get(a:dict, dir, '')832 if !empty(val)833 let [cmd, resz, max] = triple834 if (dir == 'up' || dir == 'down') && val[0] == '~'835 let sz = s:calc_size(max, val, a:dict)836 else837 let sz = s:calc_size(max, val, {})838 endif839 execute cmd sz.'new'840 execute resz sz841 return [ppos, {}, is_popup]842 endif843 endfor844 endif845 return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]846 finally847 if !is_popup848 setlocal winfixwidth winfixheight849 endif850 endtry851endfunction852853nnoremap <silent> <Plug>(fzf-insert) i854nnoremap <silent> <Plug>(fzf-normal) <Nop>855if exists(':tnoremap')856 tnoremap <silent> <Plug>(fzf-insert) <C-\><C-n>i857 tnoremap <silent> <Plug>(fzf-normal) <C-\><C-n>858endif859860let s:warned = 0861function! s:handle_ambidouble(dict)862 if &ambiwidth == 'double'863 let a:dict.env = { 'RUNEWIDTH_EASTASIAN': '1' }864 elseif !s:warned && $RUNEWIDTH_EASTASIAN == '1' && &ambiwidth !=# 'double'865 call s:warn("$RUNEWIDTH_EASTASIAN is '1' but &ambiwidth is not 'double'")866 2sleep867 let s:warned = 1868 endif869endfunction870871function! s:execute_term(dict, command, temps) abort872 let winrest = winrestcmd()873 let pbuf = bufnr('')874 let [ppos, winopts, is_popup] = s:split(a:dict)875 call s:use_sh()876 let b:fzf = a:dict877 let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,878 \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,879 \ 'columns': &columns, 'command': a:command }880 function! fzf.switch_back(inplace)881 if a:inplace && bufnr('') == self.buf882 if bufexists(self.pbuf)883 execute 'keepalt keepjumps b' self.pbuf884 endif885 " No other listed buffer886 if bufnr('') == self.buf887 enew888 endif889 endif890 endfunction891 function! fzf.on_exit(id, code, ...)892 if s:getpos() == self.ppos " {'window': 'enew'}893 for [opt, val] in items(self.winopts)894 execute 'let' opt '=' val895 endfor896 call self.switch_back(1)897 else898 if bufnr('') == self.buf899 " We use close instead of bd! since Vim does not close the split when900 " there's no other listed buffer (nvim +'set nobuflisted')901 close902 endif903 silent! execute 'tabnext' self.ppos.tab904 silent! execute self.ppos.win.'wincmd w'905 endif906907 if bufexists(self.buf)908 execute 'bd!' self.buf909 endif910911 if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos912 execute self.winrest913 endif914915 let lines = s:collect(self.temps)916 if s:exit_handler(self.dict, a:code, self.command, 1) >= 2917 return918 endif919920 call s:pushd(self.dict)921 call s:callback(self.dict, lines)922 call self.switch_back(s:getpos() == self.ppos)923924 if &buftype == 'terminal'925 call feedkeys(&filetype == 'fzf' ? "\<Plug>(fzf-insert)" : "\<Plug>(fzf-normal)")926 endif927 endfunction928929 try930 call s:pushd(a:dict)931 if s:is_win932 let fzf.temps.batchfile = s:fzf_tempname().'.bat'933 call s:writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)934 let command = fzf.temps.batchfile935 else936 let command = a:command937 endif938 let command .= s:term_marker939 if has('nvim')940 call s:handle_ambidouble(fzf)941 call termopen(command, fzf)942 else943 let term_opts = {'exit_cb': function(fzf.on_exit)}944 if v:version >= 802945 let term_opts.term_kill = 'term'946 endif947 if is_popup948 let term_opts.hidden = 1949 else950 let term_opts.curwin = 1951 endif952 call s:handle_ambidouble(term_opts)953 keepjumps let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)954 if is_popup && exists('#TerminalWinOpen')955 doautocmd <nomodeline> TerminalWinOpen956 endif957 if !has('patch-8.0.1261') && !s:is_win958 call term_wait(fzf.buf, 20)959 endif960 endif961 tnoremap <buffer> <c-z> <nop>962 if exists('&termwinkey') && (empty(&termwinkey) || &termwinkey =~? '<c-w>')963 tnoremap <buffer> <c-w> <c-w>.964 endif965 finally966 call s:dopopd()967 endtry968 setlocal nospell bufhidden=wipe nobuflisted nonumber969 setf fzf970 startinsert971 return []972endfunction973974function! s:collect(temps) abort975 try976 return filereadable(a:temps.result) ? readfile(a:temps.result) : []977 finally978 for tf in values(a:temps)979 silent! call delete(tf)980 endfor981 endtry982endfunction983984function! s:callback(dict, lines) abort985 let popd = has_key(a:dict, 'pushd')986 if popd987 let w:fzf_pushd = a:dict.pushd988 endif989990 try991 if has_key(a:dict, 'sink')992 for line in a:lines993 if type(a:dict.sink) == 2994 call a:dict.sink(line)995 else996 execute a:dict.sink s:escape(line)997 endif998 endfor999 endif1000 if has_key(a:dict, 'sink*')1001 call a:dict['sink*'](a:lines)1002 elseif has_key(a:dict, 'sinklist')1003 call a:dict['sinklist'](a:lines)1004 endif1005 catch1006 if stridx(v:exception, ':E325:') < 01007 echoerr v:exception1008 endif1009 endtry10101011 " We may have opened a new window or tab1012 if popd1013 let w:fzf_pushd = a:dict.pushd1014 call s:dopopd()1015 endif1016endfunction10171018if has('nvim')1019 function s:create_popup(opts) abort1020 let buf = nvim_create_buf(v:false, v:true)1021 let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)1022 let win = nvim_open_win(buf, v:true, opts)1023 silent! call setwinvar(win, '&winhighlight', 'Pmenu:,Normal:Normal')1024 call setwinvar(win, '&colorcolumn', '')1025 return buf1026 endfunction1027else1028 function! s:create_popup(opts) abort1029 let s:popup_create = {buf -> popup_create(buf, #{1030 \ line: a:opts.row,1031 \ col: a:opts.col,1032 \ minwidth: a:opts.width,1033 \ maxwidth: a:opts.width,1034 \ minheight: a:opts.height,1035 \ maxheight: a:opts.height,1036 \ zindex: 1000,1037 \ })}1038 autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))1039 endfunction1040endif10411042function! s:popup(opts) abort1043 let xoffset = get(a:opts, 'xoffset', 0.5)1044 let yoffset = get(a:opts, 'yoffset', 0.5)1045 let relative = get(a:opts, 'relative', 0)10461047 " Use current window size for positioning relatively positioned popups1048 let columns = relative ? winwidth(0) : &columns1049 let lines = relative ? winheight(0) : (&lines - has('nvim'))10501051 " Size and position1052 let width = min([max([8, a:opts.width > 1 ? a:opts.width : float2nr(columns * a:opts.width)]), columns])1053 let height = min([max([4, a:opts.height > 1 ? a:opts.height : float2nr(lines * a:opts.height)]), lines])1054 let row = float2nr(yoffset * (lines - height)) + (relative ? win_screenpos(0)[0] - 1 : 0)1055 let col = float2nr(xoffset * (columns - width)) + (relative ? win_screenpos(0)[1] - 1 : 0)10561057 " Managing the differences1058 let row = min([max([0, row]), &lines - has('nvim') - height])1059 let col = min([max([0, col]), &columns - width])1060 let row += !has('nvim')1061 let col += !has('nvim')10621063 call s:create_popup({1064 \ 'row': row, 'col': col, 'width': width, 'height': height1065 \ })1066endfunction10671068let s:default_action = {1069 \ 'ctrl-t': 'tab split',1070 \ 'ctrl-x': 'split',1071 \ 'ctrl-v': 'vsplit' }10721073function! s:shortpath()1074 let short = fnamemodify(getcwd(), ':~:.')1075 if !has('win32unix')1076 let short = pathshorten(short)1077 endif1078 let slash = (s:is_win && !&shellslash) ? '\' : '/'1079 return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)1080endfunction10811082function! s:cmd(bang, ...) abort1083 let args = copy(a:000)

Option to prioritize file name matches (#4192)Junegunn Choibefore adoption243a760

line 1084why, one step back
1084 let opts = { 'options': ['--multi', '--scheme', 'path'] }

Add missing --list-border=* parserJunegunn Choibefore adoptionfd513f8

lines 1085–1103why, one step back
1085 if len(args) && isdirectory(expand(args[-1]))
1086 let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1087 if s:is_win && !&shellslash1088 let opts.dir = substitute(opts.dir, '/', '\\', 'g')1089 endif1090 let prompt = opts.dir1091 else1092 let prompt = s:shortpath()1093 endif1094 let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '1095 call extend(opts.options, ['--prompt', prompt])1096 call extend(opts.options, args)1097 call fzf#run(fzf#wrap('FZF', opts, a:bang))1098endfunction10991100command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)11011102let &cpo = s:cpo_save1103unlet s:cpo_save