Skip to content
Myr

fzf.vim

This file

Path

plugin/fzf.vim

571 lines · 15.7 KiB

Last changed by

[neovim] Do not resize if the size of the screen has changedJunegunn Choibefore adoptiond873909

History of this file

Take it

1" Copyright (c) 2016 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.2324let s:default_layout = { 'down': '~40%' }25let s:layout_keys = ['window', 'up', 'down', 'left', 'right']26let s:fzf_go = expand('<sfile>:h:h').'/bin/fzf'27let s:install = expand('<sfile>:h:h').'/install'28let s:installed = 029let s:fzf_tmux = expand('<sfile>:h:h').'/bin/fzf-tmux'3031let s:cpo_save = &cpo32set cpo&vim3334function! s:fzf_exec()35  if !exists('s:exec')36    if executable(s:fzf_go)37      let s:exec = s:fzf_go38    elseif executable('fzf')39      let s:exec = 'fzf'40    elseif !s:installed && executable(s:install) &&41          \ input('fzf executable not found. Download binary? (y/n) ') =~? '^y'42      redraw43      echo44      call s:warn('Downloading fzf binary. Please wait ...')45      let s:installed = 146      call system(s:install.' --bin')47      return s:fzf_exec()48    else49      redraw50      throw 'fzf executable not found'51    endif52  endif53  return s:shellesc(s:exec)54endfunction5556function! s:tmux_enabled()57  if has('gui_running')58    return 059  endif6061  if exists('s:tmux')62    return s:tmux63  endif6465  let s:tmux = 066  if exists('$TMUX') && executable(s:fzf_tmux)67    let output = system('tmux -V')68    let s:tmux = !v:shell_error && output >= 'tmux 1.7'69  endif70  return s:tmux71endfunction7273function! s:shellesc(arg)74  return '"'.substitute(a:arg, '"', '\\"', 'g').'"'75endfunction7677function! s:escape(path)78  return escape(a:path, ' $%#''"\')79endfunction8081" Upgrade legacy options82function! s:upgrade(dict)83  let copy = copy(a:dict)84  if has_key(copy, 'tmux')85    let copy.down = remove(copy, 'tmux')86  endif87  if has_key(copy, 'tmux_height')88    let copy.down = remove(copy, 'tmux_height')89  endif90  if has_key(copy, 'tmux_width')91    let copy.right = remove(copy, 'tmux_width')92  endif93  return copy94endfunction9596function! s:error(msg)97  echohl ErrorMsg98  echom a:msg99  echohl None100endfunction101102function! s:warn(msg)103  echohl WarningMsg104  echom a:msg105  echohl None106endfunction107108function! s:has_any(dict, keys)109  for key in a:keys110    if has_key(a:dict, key)111      return 1112    endif113  endfor114  return 0115endfunction116117function! s:open(cmd, target)118  if stridx('edit', a:cmd) == 0 && fnamemodify(a:target, ':p') ==# expand('%:p')119    return120  endif121  execute a:cmd s:escape(a:target)122endfunction123124function! s:common_sink(action, lines) abort125  if len(a:lines) < 2126    return127  endif128  let key = remove(a:lines, 0)129  let cmd = get(a:action, key, 'e')130  if len(a:lines) > 1131    augroup fzf_swap132      autocmd SwapExists * let v:swapchoice='o'133            \| call s:warn('fzf: E325: swap file exists: '.expand('<afile>'))134    augroup END135  endif136  try137    let empty = empty(expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified138    let autochdir = &autochdir139    set noautochdir140    for item in a:lines141      if empty142        execute 'e' s:escape(item)143        let empty = 0144      else145        call s:open(cmd, item)146      endif147      if exists('#BufEnter') && isdirectory(item)148        doautocmd BufEnter149      endif150    endfor151  finally152    let &autochdir = autochdir153    silent! autocmd! fzf_swap154  endtry155endfunction156157" [name string,] [opts dict,] [fullscreen boolean]158function! fzf#wrap(...)159  let args = ['', {}, 0]160  let expects = map(copy(args), 'type(v:val)')161  let tidx = 0162  for arg in copy(a:000)163    let tidx = index(expects, type(arg), tidx)164    if tidx < 0165      throw 'invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'166    endif167    let args[tidx] = arg168    let tidx += 1169    unlet arg170  endfor171  let [name, opts, bang] = args172173  " Layout: g:fzf_layout (and deprecated g:fzf_height)174  if bang175    for key in s:layout_keys176      if has_key(opts, key)177        call remove(opts, key)178      endif179    endfor180  elseif !s:has_any(opts, s:layout_keys)181    if !exists('g:fzf_layout') && exists('g:fzf_height')182      let opts.down = g:fzf_height183    else184      let opts = extend(opts, get(g:, 'fzf_layout', s:default_layout))185    endif186  endif187188  " History: g:fzf_history_dir189  let opts.options = get(opts, 'options', '')190  if len(name) && len(get(g:, 'fzf_history_dir', ''))191    let dir = expand(g:fzf_history_dir)192    if !isdirectory(dir)193      call mkdir(dir, 'p')194    endif195    let opts.options = join(['--history', s:escape(dir.'/'.name), opts.options])196  endif197198  " Action: g:fzf_action199  if !s:has_any(opts, ['sink', 'sink*'])200    let opts._action = get(g:, 'fzf_action', s:default_action)201    let opts.options .= ' --expect='.join(keys(opts._action), ',')202    function! opts.sink(lines) abort203      return s:common_sink(self._action, a:lines)204    endfunction205    let opts['sink*'] = remove(opts, 'sink')206  endif207208  return opts209endfunction210211function! fzf#run(...) abort212try213  let oshell = &shell214  set shell=sh215  if has('nvim') && len(filter(range(1, bufnr('$')), 'bufname(v:val) =~# ";#FZF"'))216    call s:warn('FZF is already running!')217    return []218  endif219  let dict   = exists('a:1') ? s:upgrade(a:1) : {}220  let temps  = { 'result': tempname() }221  let optstr = get(dict, 'options', '')222  try223    let fzf_exec = s:fzf_exec()224  catch225    throw v:exception226  endtry227228  if !has_key(dict, 'source') && !empty($FZF_DEFAULT_COMMAND)229    let temps.source = tempname()230    call writefile(split($FZF_DEFAULT_COMMAND, "\n"), temps.source)231    let dict.source = (empty($SHELL) ? 'sh' : $SHELL) . ' ' . s:shellesc(temps.source)232  endif233234  if has_key(dict, 'source')235    let source = dict.source236    let type = type(source)237    if type == 1238      let prefix = source.'|'239    elseif type == 3240      let temps.input = tempname()241      call writefile(source, temps.input)242      let prefix = 'cat '.s:shellesc(temps.input).'|'243    else244      throw 'invalid source type'245    endif246  else247    let prefix = ''248  endif249  let tmux = (!has('nvim') || get(g:, 'fzf_prefer_tmux', 0)) && s:tmux_enabled() && s:splittable(dict)250  let command = prefix.(tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result251252  if has('nvim') && !tmux253    return s:execute_term(dict, command, temps)254  endif255256  let lines = tmux ? s:execute_tmux(dict, command, temps) : s:execute(dict, command, temps)257  call s:callback(dict, lines)258  return lines259finally260  let &shell = oshell261endtry262endfunction263264function! s:present(dict, ...)265  for key in a:000266    if !empty(get(a:dict, key, ''))267      return 1268    endif269  endfor270  return 0271endfunction272273function! s:fzf_tmux(dict)274  let size = ''275  for o in ['up', 'down', 'left', 'right']276    if s:present(a:dict, o)277      let spec = a:dict[o]278      if (o == 'up' || o == 'down') && spec[0] == '~'279        let size = '-'.o[0].s:calc_size(&lines, spec, a:dict)280      else281        " Legacy boolean option282        let size = '-'.o[0].(spec == 1 ? '' : substitute(spec, '^\~', '', ''))283      endif284      break285    endif286  endfor287  return printf('LINES=%d COLUMNS=%d %s %s %s --',288    \ &lines, &columns, s:shellesc(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))289endfunction290291function! s:splittable(dict)292  return s:present(a:dict, 'up', 'down', 'left', 'right')293endfunction294295function! s:pushd(dict)296  if s:present(a:dict, 'dir')297    let cwd = getcwd()298    if get(a:dict, 'prev_dir', '') ==# cwd299      return 1300    endif301    let a:dict.prev_dir = cwd302    execute 'lcd' s:escape(a:dict.dir)303    let a:dict.dir = getcwd()304    return 1305  endif306  return 0307endfunction308309augroup fzf_popd310  autocmd!311  autocmd WinEnter * call s:dopopd()312augroup END313314function! s:dopopd()315  if !exists('w:fzf_prev_dir') || exists('*haslocaldir') && !haslocaldir()316    return317  endif318  execute 'lcd' s:escape(w:fzf_prev_dir)319  unlet w:fzf_prev_dir320endfunction321322function! s:xterm_launcher()323  let fmt = 'xterm -T "[fzf]" -bg "\%s" -fg "\%s" -geometry %dx%d+%d+%d -e bash -ic %%s'324  if has('gui_macvim')325    let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'326  endif327  return printf(fmt,328    \ synIDattr(hlID("Normal"), "bg"), synIDattr(hlID("Normal"), "fg"),329    \ &columns, &lines/2, getwinposx(), getwinposy())330endfunction331unlet! s:launcher332let s:launcher = function('s:xterm_launcher')333334function! s:exit_handler(code, command, ...)335  if a:code == 130336    return 0337  elseif a:code > 1338    call s:error('Error running ' . a:command)339    if !empty(a:000)340      sleep341    endif342    return 0343  endif344  return 1345endfunction346347function! s:execute(dict, command, temps) abort348  call s:pushd(a:dict)349  silent! !clear 2> /dev/null350  let escaped = escape(substitute(a:command, '\n', '\\n', 'g'), '%#')351  if has('gui_running')352    let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))353    let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher354    let command = printf(fmt, "'".substitute(escaped, "'", "'\"'\"'", 'g')."'")355  else356    let command = escaped357  endif358  execute 'silent !'.command359  let exit_status = v:shell_error360  redraw!361  return s:exit_handler(exit_status, command) ? s:collect(a:temps) : []362endfunction363364function! s:execute_tmux(dict, command, temps) abort365  let command = a:command366  if s:pushd(a:dict)367    " -c '#{pane_current_path}' is only available on tmux 1.9 or above368    let command = 'cd '.s:escape(a:dict.dir).' && '.command369  endif370371  call system(command)372  let exit_status = v:shell_error373  redraw!374  return s:exit_handler(exit_status, command) ? s:collect(a:temps) : []375endfunction376377function! s:calc_size(max, val, dict)378  let val = substitute(a:val, '^\~', '', '')379  if val =~ '%$'380    let size = a:max * str2nr(val[:-2]) / 100381  else382    let size = min([a:max, str2nr(val)])383  endif384385  let srcsz = -1386  if type(get(a:dict, 'source', 0)) == type([])387    let srcsz = len(a:dict.source)388  endif389390  let opts = get(a:dict, 'options', '').$FZF_DEFAULT_OPTS391  let margin = stridx(opts, '--inline-info') > stridx(opts, '--no-inline-info') ? 1 : 2392  let margin += stridx(opts, '--header') > stridx(opts, '--no-header')393  return srcsz >= 0 ? min([srcsz + margin, size]) : size394endfunction395396function! s:getpos()397  return {'tab': tabpagenr(), 'win': winnr(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}398endfunction399400function! s:split(dict)401  let directions = {402  \ 'up':    ['topleft', 'resize', &lines],403  \ 'down':  ['botright', 'resize', &lines],404  \ 'left':  ['vertical topleft', 'vertical resize', &columns],405  \ 'right': ['vertical botright', 'vertical resize', &columns] }406  let ppos = s:getpos()407  try408    for [dir, triple] in items(directions)409      let val = get(a:dict, dir, '')410      if !empty(val)411        let [cmd, resz, max] = triple412        if (dir == 'up' || dir == 'down') && val[0] == '~'413          let sz = s:calc_size(max, val, a:dict)414        else415          let sz = s:calc_size(max, val, {})416        endif417        execute cmd sz.'new'418        execute resz sz419        return [ppos, {}]420      endif421    endfor422    if s:present(a:dict, 'window')423      execute a:dict.window424    else425      execute (tabpagenr()-1).'tabnew'426    endif427    return [ppos, { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }]428  finally429    setlocal winfixwidth winfixheight430  endtry431endfunction432433function! s:execute_term(dict, command, temps) abort434  let winrest = winrestcmd()435  let [ppos, winopts] = s:split(a:dict)436  let fzf = { 'buf': bufnr('%'), 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,437            \ 'winopts': winopts, 'winrest': winrest, 'lines': &lines,438            \ 'columns': &columns, 'command': a:command }439  function! fzf.switch_back(inplace)440    if a:inplace && bufnr('') == self.buf441      " FIXME: Can't re-enter normal mode from terminal mode442      " execute "normal! \<c-^>"443      b #444      " No other listed buffer445      if bufnr('') == self.buf446        enew447      endif448    endif449  endfunction450  function! fzf.on_exit(id, code)451    if s:getpos() == self.ppos " {'window': 'enew'}452      for [opt, val] in items(self.winopts)453        execute 'let' opt '=' val454      endfor455      call self.switch_back(1)456    else457      if bufnr('') == self.buf458        " We use close instead of bd! since Vim does not close the split when459        " there's no other listed buffer (nvim +'set nobuflisted')460        close461      endif462      execute 'tabnext' self.ppos.tab463      execute self.ppos.win.'wincmd w'464    endif465466    if bufexists(self.buf)467      execute 'bd!' self.buf468    endif469470    if &lines == self.lines && &columns == self.columns && s:getpos() == self.ppos471      execute self.winrest472    endif473474    if !s:exit_handler(a:code, self.command, 1)475      return476    endif477478    call s:pushd(self.dict)479    let lines = s:collect(self.temps)480    call s:callback(self.dict, lines)481    call self.switch_back(s:getpos() == self.ppos)482  endfunction483484  try485    if s:present(a:dict, 'dir')486      execute 'lcd' s:escape(a:dict.dir)487    endif488    call termopen(a:command . ';#FZF', fzf)489  finally490    if s:present(a:dict, 'dir')491      lcd -492    endif493  endtry494  setlocal nospell bufhidden=wipe nobuflisted495  setf fzf496  startinsert497  return []498endfunction499500function! s:collect(temps) abort501  try502    return filereadable(a:temps.result) ? readfile(a:temps.result) : []503  finally504    for tf in values(a:temps)505      silent! call delete(tf)506    endfor507  endtry508endfunction509510function! s:callback(dict, lines) abort511  " Since anything can be done in the sink function, there is no telling that512  " the change of the working directory was made by &autochdir setting.513  "514  " We use the following heuristic to determine whether to restore CWD:515  " - Always restore the current directory when &autochdir is disabled.516  "   FIXME This makes it impossible to change directory from inside the sink517  "   function when &autochdir is not used.518  " - In case of an error or an interrupt, a:lines will be empty.519  "   And it will be an array of a single empty string when fzf was finished520  "   without a match. In these cases, we presume that the change of the521  "   directory is not expected and should be undone.522  let popd = has_key(a:dict, 'prev_dir') &&523        \ (!&autochdir || (empty(a:lines) || len(a:lines) == 1 && empty(a:lines[0])))524  if popd525    let w:fzf_prev_dir = a:dict.prev_dir526  endif527528  try529    if has_key(a:dict, 'sink')530      for line in a:lines531        if type(a:dict.sink) == 2532          call a:dict.sink(line)533        else534          execute a:dict.sink s:escape(line)535        endif536      endfor537    endif538    if has_key(a:dict, 'sink*')539      call a:dict['sink*'](a:lines)540    endif541  catch542    if stridx(v:exception, ':E325:') < 0543      echoerr v:exception544    endif545  endtry546547  " We may have opened a new window or tab548  if popd549    let w:fzf_prev_dir = a:dict.prev_dir550    call s:dopopd()551  endif552endfunction553554let s:default_action = {555  \ 'ctrl-t': 'tab split',556  \ 'ctrl-x': 'split',557  \ 'ctrl-v': 'vsplit' }558559function! s:cmd(bang, ...) abort560  let args = copy(a:000)561  let opts = {}562  if len(args) && isdirectory(expand(args[-1]))563    let opts.dir = substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g')564  endif565  call fzf#run(fzf#wrap('FZF', extend({'options': join(args)}, opts), a:bang))566endfunction567568command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)569570let &cpo = s:cpo_save571unlet s:cpo_save