如何创建目录搜索并替换为vimscript和fzf

时间:2016-07-26 03:40:49

标签: vim fzf

我正在尝试使用fzf在vimscript中创建目录搜索和替换函数。我阻止的地方是尝试使用Alt-a fzf绑定来选择整个列表。我甚至不确定这是否可能,因为fzf是一个外部过程,但我可能错了。

这是我目前的功能。

function! CWDSearchAndReplace()

    " Try to get word under cursor else prompt user for a word
    let wordToReplace = expand("<cword>")
    if wordToReplace == ""
        call inputsave()
        let wordToReplace = input("Replace: ")
        call inputrestore()
    endif

    " Prompt for replacement
    call inputsave()
    let replacement = input("Replace \"" . wordToReplace . "\" with: ")
    call inputrestore()
    execute "Ag " . wordToReplace

    " =====>  Here I'd like to execute Alt-a followed by <CR>

    execute "cdo %s//" . replacement . "/gc"
end function

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

pointed out的创建者fzf.vim作为toArray() method,此处无需使用fzf,只需使用ag即可。

function! s:ag_to_qf(line)
  let parts = split(a:line, ':')
  echo parts
  return {'filename': parts[0], 'lnum': parts[1], 'col': parts[2],
        \ 'text': join(parts[3:], ':')}
endfunction

function! AgToQF(query)
  call setqflist(map(systemlist('ag --column '.a:query), 's:ag_to_qf(v:val)'))
endfunction

function! CWDSearchAndReplace()
    let wordUnderCursor = expand("<cword>")
    call inputsave()
    let wordToReplace = input("Replace : ", wordUnderCursor)
    call inputrestore()
    call inputsave()
    let replacement = input("Replace \"" . wordUnderCursor . "\" with: ")
    call inputrestore()
    call AgToQF(wordUnderCursor)
    execute "cdo %s/" . wordToReplace . "/" . replacement ."/gc"
endfunction

nnoremap <leader>r :call FileSearchAndReplace()<CR>