junegunn / fzf.vim

fzf :heart: vim
MIT License
9.55k stars 583 forks source link

Question:how to use Rg on current word/selection #1429

Closed nkh closed 1 year ago

nkh commented 1 year ago

fzf.vim Rg is slowly replacing ctags for me, I'd like to Rg the current word or selection, can't find an example here nor in will wild internet.

lanker commented 1 year ago

nnoremap <leader>a :Rg <c-r><c-w><cr> for word under cursor.

nkh commented 1 year ago

@lanker Great! thank you.

okoriko commented 1 year ago

This is a bit old but I'll leave a different option below, it might be helpful to others.

Another strategy is to forward the current word as the search query, when it is empty.

For example in the context of the Advanced ripgrep integration the below would fallback on the current word if nothing is provided (similar to how vim-ripgrep behaves) :

fun! s:RGSearchTerm(query)
  if empty(a:query)
    return expand("<cword>")
  else
    return a:query
  endif
endfun

function! RipgrepFzf(query, fullscreen)
  let query = s:RGSearchTerm(a:query)
  let command_fmt = 'rg --column --line-number --no-heading --color=always --smart-case %s || true'
  let initial_command = printf(command_fmt, shellescape(query))
  let reload_command = printf(command_fmt, '{q}')
  let spec = {'options': ['--disabled', '--query', query, '--bind', 'change:reload:'.reload_command]}
  let spec = fzf#vim#with_preview(spec, 'right', 'ctrl-/')
  call fzf#vim#grep(initial_command, 1, fzf#vim#with_preview(spec), a:fullscreen)
endfunction

command! -nargs=* -bang RG call RipgrepFzf(<q-args>, <bang>0)
nkh commented 1 year ago

@okoriko "Another strategy is to forward the current word as the search query, when it is empty." doesn't make any sense to me; could you please explain?

The code above searches for the current word and not positioned on a word you get to give the search.