junegunn / fzf.vim

fzf :heart: vim
MIT License
9.52k stars 582 forks source link

How to use Rg to search recent file contents #1496

Closed chunxuan-hs closed 9 months ago

chunxuan-hs commented 10 months ago

How do I customize the Rg to search string/patterns in the recent files in :History? That would be very helpful in daily usages.

Thanks!

nkouevda commented 10 months ago

:History uses fzf#vim#_recent_files() as its source, so you can define a variant of :Rg that passes those files as args to rg:

command! -bang -nargs=* RgHistory call fzf#vim#grep(
  \ 'rg --no-heading --with-filename --line-number --column --color=always -- '
  \ . shellescape(<q-args>)
  \ . ' ' . join(fzf#vim#_recent_files(), ' '), fzf#vim#with_preview(), <bang>0)

--with-filename (not present in the :Rg definition) is to force rg to include the filename in its output when fzf#vim#_recent_files() contains exactly 1 file.

Another edge case is if fzf#vim#_recent_files() is empty, this will invoke rg without any path args, which is equivalent to :Rg, i.e. searches in pwd. Could check for that case explicitly, but at that point this should probably be a separate function:

command! -bang -nargs=* RgHistory
  \    if empty(fzf#vim#_recent_files())
  \ |    echoerr 'error: No recent files'
  \ |  else
  \ |    call fzf#vim#grep(
  \        'rg --no-heading --with-filename --line-number --column --color=always -- '
  \        . shellescape(<q-args>)
  \        . ' ' . join(fzf#vim#_recent_files(), ' '), fzf#vim#with_preview(), <bang>0)
  \ |  endif
chunxuan-hs commented 10 months ago

Many thanks for the solutions! I think it works but with a small caveat. There are duplicates in the filtered results. See the screenshot for an example.

In the bottom, the same hits, 02.main.R row 22 appeared 5 times. Also happened for other lines. Any ideas on where the duplicates come from

Screenshot 2023-09-13 at 16 52 01
nkouevda commented 9 months ago

Do you have a ripgreprc and/or do you override rg in any way, like an exported shell function? My suspicion is that some other options are being passed to rg, e.g. --vimgrep would result in similar behavior with many duplicates.

That would affect more than this one command, though; I'm not sure what could cause such behavior here but not with other commands like :Rg.

chunxuan-hs commented 9 months ago

@nkouevda Here is the full codes I used in my vim setting, adding the "--type r":

command! -bang -nargs=* RgHistory call fzf#vim#grep(
  \ 'rg --column --line-number --with-filename --no-heading --color=always --smart-case --type r '
  \ .shellescape(<q-args>)
  \ . ' ' . join(fzf#vim#_recent_files(), ' '), fzf#vim#with_preview(), <bang>0)

It looks "--type r" causes the duplicates, and your original version without it works nicely. I have no idea why adding the global pattern leads to duplicates.

chunxuan-hs commented 9 months ago

Just a short note that the duplicates are still persistent with or without --type r.