fzf.vim
This file
Path
plugin/fzf.vim
1,074 lines · 31.1 KiB
Last changed by
[vim] Simplify --border injectionJunegunn Choibefore adoption0f4af38
History of this fileTake it
The walk stopped after 200 commits: lines older than b3ab631 point at it.
0.36.0Junegunn Choibefore adoption2023011
line 1why, one step back1" Copyright (c) 2013-2023 Junegunn ChoiHide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 2–98why, one step back2"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 endif[vim] Fix fzf#shellescape when shell=fish (#2828)Daniel Zhangbefore adoption3b7a962
lines 99–104why, one step back99 try100 let [shell, &shell] = [&shell, shell]101 return s:fzf_call('shellescape', a:arg)102 finally103 let [shell, &shell] = [&shell, shell]104 endtryHide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 105–145why, one step back105endfunction106107function! 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 endif[vim] Update fzf#install to handle spaces on Windows (#2993)Kyle L. Davisbefore adoption07da058
line 146why, one step back146 let script = 'powershell -ExecutionPolicy Bypass -file ' . shellescape(script)Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 147–166why, one step back147 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 end[vim] Fix version check on Windows when shellslash is setJunegunn Choibefore adoption0de1aac
line 167why, one step back167 let command = (&shell =~ 'powershell' ? '&' : '') . s:fzf_call('shellescape', a:bin) . ' --version --no-height'Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 168–344why, one step back168 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, ...)[vim] Add option to force 24 bit colors on Windows (#2889)Carl Kamholtzbefore adoptiond083f01
lines 345–346why, one step back345 " 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)Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 347–466why, one step back347 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 try[vim] Remove unnecessary powershell checkJunegunn Choibefore adoptionf9d5330
line 467why, one step back467 let fzf_exec = shellescape(fzf#exec())Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 468–513why, one step back468 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 endif[vim] Use system-default border styleJunegunn Choibefore adoptiona6d6cdd
line 514why, one step back514 " Respect --border option given in 'options'[vim] Simplify --border injectionJunegunn Choibefore adoption0f4af38
line 515why, one step back515 let optstr = join([s:border_opt(get(dict, 'window', 0)), optstr])Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 516–741why, one step back516 let prev_default_command = $FZF_DEFAULT_COMMAND517 if len(source_command)518 let $FZF_DEFAULT_COMMAND = source_command519 endif520 let command = (use_tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result521522 if use_term523 return s:execute_term(dict, command, temps)524 endif525526 let lines = use_tmux ? s:execute_tmux(dict, command, temps)527 \ : s:execute(dict, command, use_height, temps)528 call s:callback(dict, lines)529 return lines530finally531 if exists('source_command') && len(source_command)532 if len(prev_default_command)533 let $FZF_DEFAULT_COMMAND = prev_default_command534 else535 let $FZF_DEFAULT_COMMAND = ''536 silent! execute 'unlet $FZF_DEFAULT_COMMAND'537 endif538 endif539 let [&shell, &shellslash, &shellcmdflag, &shellxquote] = [shell, shellslash, shellcmdflag, shellxquote]540endtry541endfunction542543function! s:present(dict, ...)544 for key in a:000545 if !empty(get(a:dict, key, ''))546 return 1547 endif548 endfor549 return 0550endfunction551552function! s:fzf_tmux(dict)553 let size = get(a:dict, 'tmux', '')554 if empty(size)555 for o in ['up', 'down', 'left', 'right']556 if s:present(a:dict, o)557 let spec = a:dict[o]558 if (o == 'up' || o == 'down') && spec[0] == '~'559 let size = '-'.o[0].s:calc_size(&lines, spec, a:dict)560 else561 " Legacy boolean option562 let size = '-'.o[0].(spec == 1 ? '' : substitute(spec, '^\~', '', ''))563 endif564 break565 endif566 endfor567 endif568 return printf('LINES=%d COLUMNS=%d %s %s - --',569 \ &lines, &columns, fzf#shellescape(s:fzf_tmux), size)570endfunction571572function! s:splittable(dict)573 return s:present(a:dict, 'up', 'down') && &lines > 15 ||574 \ s:present(a:dict, 'left', 'right') && &columns > 40575endfunction576577function! s:pushd(dict)578 if s:present(a:dict, 'dir')579 let cwd = s:fzf_getcwd()580 let w:fzf_pushd = {581 \ 'command': haslocaldir() ? 'lcd' : (exists(':tcd') && haslocaldir(-1) ? 'tcd' : 'cd'),582 \ 'origin': cwd,583 \ 'bufname': bufname('')584 \ }585 execute 'lcd' s:escape(a:dict.dir)586 let cwd = s:fzf_getcwd()587 let w:fzf_pushd.dir = cwd588 let a:dict.pushd = w:fzf_pushd589 return cwd590 endif591 return ''592endfunction593594augroup fzf_popd595 autocmd!596 autocmd WinEnter * call s:dopopd()597augroup END598599function! s:dopopd()600 if !exists('w:fzf_pushd')601 return602 endif603604 " FIXME: We temporarily change the working directory to 'dir' entry605 " of options dictionary (set to the current working directory if not given)606 " before running fzf.607 "608 " e.g. call fzf#run({'dir': '/tmp', 'source': 'ls', 'sink': 'e'})609 "610 " After processing the sink function, we have to restore the current working611 " directory. But doing so may not be desirable if the function changed the612 " working directory on purpose.613 "614 " So how can we tell if we should do it or not? A simple heuristic we use615 " here is that we change directory only if the current working directory616 " matches 'dir' entry. However, it is possible that the sink function did617 " change the directory to 'dir'. In that case, the user will have an618 " unexpected result.619 if s:fzf_getcwd() ==# w:fzf_pushd.dir && (!&autochdir || w:fzf_pushd.bufname ==# bufname(''))620 execute w:fzf_pushd.command s:escape(w:fzf_pushd.origin)621 endif622 unlet! w:fzf_pushd623endfunction624625function! s:xterm_launcher()626 let fmt = 'xterm -T "[fzf]" -bg "%s" -fg "%s" -geometry %dx%d+%d+%d -e bash -ic %%s'627 if has('gui_macvim')628 let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'629 endif630 return printf(fmt,631 \ escape(synIDattr(hlID("Normal"), "bg"), '#'), escape(synIDattr(hlID("Normal"), "fg"), '#'),632 \ &columns, &lines/2, getwinposx(), getwinposy())633endfunction634unlet! s:launcher635if s:is_win || has('win32unix')636 let s:launcher = '%s'637else638 let s:launcher = function('s:xterm_launcher')639endif640641function! s:exit_handler(code, command, ...)642 if a:code == 130643 return 0644 elseif has('nvim') && a:code == 129645 " When deleting the terminal buffer while fzf is still running,646 " Nvim sends SIGHUP.647 return 0648 elseif a:code > 1649 call s:error('Error running ' . a:command)650 if !empty(a:000)651 sleep652 endif653 return 0654 endif655 return 1656endfunction657658function! s:execute(dict, command, use_height, temps) abort659 call s:pushd(a:dict)660 if has('unix') && !a:use_height661 silent! !clear 2> /dev/null662 endif663 let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')664 if has('gui_running')665 let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))666 let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher667 if has('unix')668 let escaped = "'".substitute(escaped, "'", "'\"'\"'", 'g')."'"669 endif670 let command = printf(fmt, escaped)671 else672 let command = escaped673 endif674 if s:is_win675 let batchfile = s:fzf_tempname().'.bat'676 call s:writefile(s:wrap_cmds(command), batchfile)677 let command = batchfile678 let a:temps.batchfile = batchfile679 if has('nvim')680 let fzf = {}681 let fzf.dict = a:dict682 let fzf.temps = a:temps683 function! fzf.on_exit(job_id, exit_status, event) dict684 call s:pushd(self.dict)685 let lines = s:collect(self.temps)686 call s:callback(self.dict, lines)687 endfunction688 let cmd = 'start /wait cmd /c '.command689 call jobstart(cmd, fzf)690 return []691 endif692 elseif has('win32unix') && $TERM !=# 'cygwin'693 let shellscript = s:fzf_tempname()694 call s:writefile([command], shellscript)695 let command = 'cmd.exe /C '.fzf#shellescape('set "TERM=" & start /WAIT sh -c '.shellscript)696 let a:temps.shellscript = shellscript697 endif698 if a:use_height699 call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s < /dev/tty 2> /dev/tty', &lines, command))700 else701 execute 'silent !'.command702 endif703 let exit_status = v:shell_error704 redraw!705 let lines = s:collect(a:temps)706 return s:exit_handler(exit_status, command) ? lines : []707endfunction708709function! s:execute_tmux(dict, command, temps) abort710 let command = a:command711 let cwd = s:pushd(a:dict)712 if len(cwd)713 " -c '#{pane_current_path}' is only available on tmux 1.9 or above714 let command = join(['cd', fzf#shellescape(cwd), '&&', command])715 endif716717 call system(command)718 let exit_status = v:shell_error719 redraw!720 let lines = s:collect(a:temps)721 return s:exit_handler(exit_status, command) ? lines : []722endfunction723724function! s:calc_size(max, val, dict)725 let val = substitute(a:val, '^\~', '', '')726 if val =~ '%$'727 let size = a:max * str2nr(val[:-2]) / 100728 else729 let size = min([a:max, str2nr(val)])730 endif731732 let srcsz = -1733 if type(get(a:dict, 'source', 0)) == type([])734 let srcsz = len(a:dict.source)735 endif736737 let opts = $FZF_DEFAULT_OPTS.' '.s:evaluate_opts(get(a:dict, 'options', ''))738 if opts =~ 'preview'739 return size740 endif741 let margin = match(opts, '--inline-info\|--info[^-]\{-}inline') > match(opts, '--no-inline-info\|--info[^-]\{-}\(default\|hidden\)') ? 1 : 2[vim] Fix missing --border when --border-label is presentJunegunn Choibefore adoptionaef39f1
line 742why, one step back742 let margin += match(opts, '--border\([^-]\|$\)') > match(opts, '--no-border\([^-]\|$\)') ? 2 : 0Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 743–758why, one step back743 if stridx(opts, '--header') > stridx(opts, '--no-header')744 let margin += len(split(opts, "\n"))745 endif746 return srcsz >= 0 ? min([srcsz + margin, size]) : size747endfunction748749function! s:getpos()750 return {'tab': tabpagenr(), 'win': winnr(), 'winid': win_getid(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}751endfunction752753function! s:border_opt(window)754 if type(a:window) != type({})755 return ''756 endif757758 " Border style[vim] Use system-default border styleJunegunn Choibefore adoptiona6d6cdd
lines 759–761why, one step back759 let style = tolower(get(a:window, 'border', ''))760 if !has_key(a:window, 'border') && has_key(a:window, 'rounded')761 let style = a:window.rounded ? 'rounded' : 'sharp'Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 762–768why, one step back762 endif763 if style == 'none' || style == 'no'764 return ''765 endif766767 " For --border styles, we need fzf 0.24.0 or above768 call fzf#exec('0.24.0')[vim] Use system-default border styleJunegunn Choibefore adoptiona6d6cdd
line 769why, one step back769 let opt = ' --border ' . styleHide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 770–830why, one step back770 if has_key(a:window, 'highlight')771 let color = s:get_color('fg', a:window.highlight)772 if len(color)773 let opt .= ' --color=border:' . color774 endif775 endif776 return opt777endfunction778779function! s:split(dict)780 let directions = {781 \ 'up': ['topleft', 'resize', &lines],782 \ 'down': ['botright', 'resize', &lines],783 \ 'left': ['vertical topleft', 'vertical resize', &columns],784 \ 'right': ['vertical botright', 'vertical resize', &columns] }785 let ppos = s:getpos()786 let is_popup = 0787 try788 if s:present(a:dict, 'window')789 if type(a:dict.window) == type({})790 if !s:popup_support()791 throw 'Nvim 0.4+ or Vim 8.2.191+ with popupwin feature is required for pop-up window'792 end793 call s:popup(a:dict.window)794 let is_popup = 1795 else796 execute 'keepalt' a:dict.window797 endif798 elseif !s:splittable(a:dict)799 execute (tabpagenr()-1).'tabnew'800 else801 for [dir, triple] in items(directions)802 let val = get(a:dict, dir, '')803 if !empty(val)804 let [cmd, resz, max] = triple805 if (dir == 'up' || dir == 'down') && val[0] == '~'806 let sz = s:calc_size(max, val, a:dict)807 else808 let sz = s:calc_size(max, val, {})809 endif810 execute cmd sz.'new'811 execute resz sz812 return [ppos, {}, is_popup]813 endif814 endfor815 endif816 return [ppos, is_popup ? {} : { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }, is_popup]817 finally818 if !is_popup819 setlocal winfixwidth winfixheight820 endif821 endtry822endfunction823824nnoremap <silent> <Plug>(fzf-insert) i825nnoremap <silent> <Plug>(fzf-normal) <Nop>826if exists(':tnoremap')827 tnoremap <silent> <Plug>(fzf-insert) <C-\><C-n>i828 tnoremap <silent> <Plug>(fzf-normal) <C-\><C-n>829endif830[vim] Automatically set RUNEWIDTH_EASTASIAN=1 when &ambiwidth == doubleJunegunn Choibefore adoptionb46e40e
lines 831–841why, one step back831let s:warned = 0832function! s:handle_ambidouble(dict)833 if &ambiwidth == 'double'834 let a:dict.env = { 'RUNEWIDTH_EASTASIAN': '1' }835 elseif !s:warned && $RUNEWIDTH_EASTASIAN == '1' && &ambiwidth !=# 'double'836 call s:warn("$RUNEWIDTH_EASTASIAN is '1' but &ambiwidth is not 'double'")837 2sleep838 let s:warned = 1839 endif840endfunction841Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 842–910why, one step back842function! s:execute_term(dict, command, temps) abort843 let winrest = winrestcmd()844 let pbuf = bufnr('')845 let [ppos, winopts, is_popup] = s:split(a:dict)846 call s:use_sh()847 let b:fzf = a:dict848 let fzf = { 'buf': bufnr(''), 'pbuf': pbuf, 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,849 \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,850 \ 'columns': &columns, 'command': a:command }851 function! fzf.switch_back(inplace)852 if a:inplace && bufnr('') == self.buf853 if bufexists(self.pbuf)854 execute 'keepalt keepjumps b' self.pbuf855 endif856 " No other listed buffer857 if bufnr('') == self.buf858 enew859 endif860 endif861 endfunction862 function! fzf.on_exit(id, code, ...)863 if s:getpos() == self.ppos " {'window': 'enew'}864 for [opt, val] in items(self.winopts)865 execute 'let' opt '=' val866 endfor867 call self.switch_back(1)868 else869 if bufnr('') == self.buf870 " We use close instead of bd! since Vim does not close the split when871 " there's no other listed buffer (nvim +'set nobuflisted')872 close873 endif874 silent! execute 'tabnext' self.ppos.tab875 silent! execute self.ppos.win.'wincmd w'876 endif877878 if bufexists(self.buf)879 execute 'bd!' self.buf880 endif881882 if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos883 execute self.winrest884 endif885886 let lines = s:collect(self.temps)887 if !s:exit_handler(a:code, self.command, 1)888 return889 endif890891 call s:pushd(self.dict)892 call s:callback(self.dict, lines)893 call self.switch_back(s:getpos() == self.ppos)894895 if &buftype == 'terminal'896 call feedkeys(&filetype == 'fzf' ? "\<Plug>(fzf-insert)" : "\<Plug>(fzf-normal)")897 endif898 endfunction899900 try901 call s:pushd(a:dict)902 if s:is_win903 let fzf.temps.batchfile = s:fzf_tempname().'.bat'904 call s:writefile(s:wrap_cmds(a:command), fzf.temps.batchfile)905 let command = fzf.temps.batchfile906 else907 let command = a:command908 endif909 let command .= s:term_marker910 if has('nvim')[vim] Automatically set RUNEWIDTH_EASTASIAN=1 when &ambiwidth == doubleJunegunn Choibefore adoptionb46e40e
line 911why, one step back911 call s:handle_ambidouble(fzf)Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 912–922why, one step back912 call termopen(command, fzf)913 else914 let term_opts = {'exit_cb': function(fzf.on_exit)}915 if v:version >= 802916 let term_opts.term_kill = 'term'917 endif918 if is_popup919 let term_opts.hidden = 1920 else921 let term_opts.curwin = 1922 endif[vim] Automatically set RUNEWIDTH_EASTASIAN=1 when &ambiwidth == doubleJunegunn Choibefore adoptionb46e40e
line 923why, one step back923 call s:handle_ambidouble(term_opts)Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 924–989why, one step back924 let fzf.buf = term_start([&shell, &shellcmdflag, command], term_opts)925 if is_popup && exists('#TerminalWinOpen')926 doautocmd <nomodeline> TerminalWinOpen927 endif928 if !has('patch-8.0.1261') && !s:is_win929 call term_wait(fzf.buf, 20)930 endif931 endif932 tnoremap <buffer> <c-z> <nop>933 if exists('&termwinkey') && (empty(&termwinkey) || &termwinkey =~? '<c-w>')934 tnoremap <buffer> <c-w> <c-w>.935 endif936 finally937 call s:dopopd()938 endtry939 setlocal nospell bufhidden=wipe nobuflisted nonumber940 setf fzf941 startinsert942 return []943endfunction944945function! s:collect(temps) abort946 try947 return filereadable(a:temps.result) ? readfile(a:temps.result) : []948 finally949 for tf in values(a:temps)950 silent! call delete(tf)951 endfor952 endtry953endfunction954955function! s:callback(dict, lines) abort956 let popd = has_key(a:dict, 'pushd')957 if popd958 let w:fzf_pushd = a:dict.pushd959 endif960961 try962 if has_key(a:dict, 'sink')963 for line in a:lines964 if type(a:dict.sink) == 2965 call a:dict.sink(line)966 else967 execute a:dict.sink s:escape(line)968 endif969 endfor970 endif971 if has_key(a:dict, 'sink*')972 call a:dict['sink*'](a:lines)973 elseif has_key(a:dict, 'sinklist')974 call a:dict['sinklist'](a:lines)975 endif976 catch977 if stridx(v:exception, ':E325:') < 0978 echoerr v:exception979 endif980 endtry981982 " We may have opened a new window or tab983 if popd984 let w:fzf_pushd = a:dict.pushd985 call s:dopopd()986 endif987endfunction988989if has('nvim')[neovim] Do not use Pmenu group colors for floating windowJunegunn Choibefore adoption0881a6b
line 990why, one step back990 function s:create_popup(opts) abortHide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 991–993why, one step back991 let buf = nvim_create_buf(v:false, v:true)992 let opts = extend({'relative': 'editor', 'style': 'minimal'}, a:opts)993 let win = nvim_open_win(buf, v:true, opts)[neovim] Use Normal group colors for floating windowJunegunn Choibefore adoption2eec989
line 994why, one step back994 silent! call setwinvar(win, '&winhighlight', 'Pmenu:,Normal:Normal')Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 995–998why, one step back995 call setwinvar(win, '&colorcolumn', '')996 return buf997 endfunction998else[neovim] Do not use Pmenu group colors for floating windowJunegunn Choibefore adoption0881a6b
line 999why, one step back999 function! s:create_popup(opts) abortHide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 1000–1033why, one step back1000 let s:popup_create = {buf -> popup_create(buf, #{1001 \ line: a:opts.row,1002 \ col: a:opts.col,1003 \ minwidth: a:opts.width,1004 \ maxwidth: a:opts.width,1005 \ minheight: a:opts.height,1006 \ maxheight: a:opts.height,1007 \ zindex: 1000,1008 \ })}1009 autocmd TerminalOpen * ++once call s:popup_create(str2nr(expand('<abuf>')))1010 endfunction1011endif10121013function! s:popup(opts) abort1014 let xoffset = get(a:opts, 'xoffset', 0.5)1015 let yoffset = get(a:opts, 'yoffset', 0.5)1016 let relative = get(a:opts, 'relative', 0)10171018 " Use current window size for positioning relatively positioned popups1019 let columns = relative ? winwidth(0) : &columns1020 let lines = relative ? winheight(0) : (&lines - has('nvim'))10211022 " Size and position1023 let width = min([max([8, a:opts.width > 1 ? a:opts.width : float2nr(columns * a:opts.width)]), columns])1024 let height = min([max([4, a:opts.height > 1 ? a:opts.height : float2nr(lines * a:opts.height)]), lines])1025 let row = float2nr(yoffset * (lines - height)) + (relative ? win_screenpos(0)[0] - 1 : 0)1026 let col = float2nr(xoffset * (columns - width)) + (relative ? win_screenpos(0)[1] - 1 : 0)10271028 " Managing the differences1029 let row = min([max([0, row]), &lines - has('nvim') - height])1030 let col = min([max([0, col]), &columns - width])1031 let row += !has('nvim')1032 let col += !has('nvim')1033[neovim] Do not use Pmenu group colors for floating windowJunegunn Choibefore adoption0881a6b
line 1034why, one step back1034 call s:create_popup({Hide cursor while rendering the screenJunegunn Choibefore adoptionb3ab631
lines 1035–1074why, one step back1035 \ 'row': row, 'col': col, 'width': width, 'height': height1036 \ })1037endfunction10381039let s:default_action = {1040 \ 'ctrl-t': 'tab split',1041 \ 'ctrl-x': 'split',1042 \ 'ctrl-v': 'vsplit' }10431044function! s:shortpath()1045 let short = fnamemodify(getcwd(), ':~:.')1046 if !has('win32unix')1047 let short = pathshorten(short)1048 endif1049 let slash = (s:is_win && !&shellslash) ? '\' : '/'1050 return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)1051endfunction10521053function! s:cmd(bang, ...) abort1054 let args = copy(a:000)1055 let opts = { 'options': ['--multi'] }1056 if len(args) && isdirectory(expand(args[-1]))1057 let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1058 if s:is_win && !&shellslash1059 let opts.dir = substitute(opts.dir, '/', '\\', 'g')1060 endif1061 let prompt = opts.dir1062 else1063 let prompt = s:shortpath()1064 endif1065 let prompt = strwidth(prompt) < &columns - 20 ? prompt : '> '1066 call extend(opts.options, ['--prompt', prompt])1067 call extend(opts.options, args)1068 call fzf#run(fzf#wrap('FZF', opts, a:bang))1069endfunction10701071command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)10721073let &cpo = s:cpo_save1074unlet s:cpo_save