Skip to content

Leaderf rg

Yggdroot edited this page Aug 17, 2024 · 22 revisions

About

Grep using the famous rg(ripgrep)

  • grep asynchronously
  • easy to use just like using rg in the command line
  • take advantage of the fuzzy matching algorithm for a secondary filter
  • find and replace in multiple files

Requirements

  • ripgrep 0.10.0+

Usage

  • :Leaderf rg -h
usage: Leaderf[!] rg [-h] [-A <NUM>] [-B <NUM>] [-C <NUM>] [--context-separator <SEPARATOR>] [--crlf]
                     [-e <PATTERN>...] [-F | --no-fixed-strings] [-i] [-L] [-P] [-S] [-s] [-v] [-w] [-x]
                     [--binary] [--column] [--hidden] [--heading] [--no-config] [--no-ignore]
                     [--no-ignore-global] [--no-ignore-parent] [--no-ignore-vcs] [--no-messages]
                     [--no-pcre2-unicode] [-E <ENCODING>] [-M <NUM>] [-m <NUM>] [-U] [--multiline-dotall]
                     [--max-depth <NUM>] [--max-filesize <NUM+SUFFIX?>] [--path-separator <SEPARATOR>]
                     [--sort <SORTBY>] [--sortr <SORTBY>] [-f <PATTERNFILE>...] [-g <GLOB>...]
                     [--iglob <GLOB>...] [--ignore-file <PATH>...] [--type-add <TYPE_SPEC>...]
                     [-t <TYPE>...] [-T <TYPE>...] [--current-buffer | --all-buffers] [--append]
                     [--match-path] [--wd-mode <MODE>] [--live] [--reverse] [--stayOpen]
                     [--input <INPUT> | --cword]
                     [--top | --bottom | --left | --right | --belowright | --aboveleft | --fullScreen | --popup]
                     [--nameOnly | --fullPath | --fuzzy | --regexMode] [--nowrap] [--next | --previous]
                     [--recall] [--popup-height <POPUP_HEIGHT>] [--popup-width <POPUP_WIDTH>] [--no-sort]
                     [--case-insensitive] [--auto-preview | --no-auto-preview]
                     [<PATH> ...]

options:
  -h, --help            show this help message and exit

specific arguments:
  -A <NUM>, --after-context <NUM>
                        Show NUM lines after each match.
  -B <NUM>, --before-context <NUM>
                        Show NUM lines before each match.
  -C <NUM>, --context <NUM>
                        Show NUM lines before and after each match.
  --context-separator <SEPARATOR>
                        The string used to separate non-contiguous context lines in the output.
  --crlf                ripgrep will treat CRLF (' ') as a line terminator instead of just ' '.
  -e <PATTERN>..., --regexp <PATTERN>...
                        A pattern to search for. This option can be provided multiple times, where all
                        patterns given are searched.
  -F, --fixed-strings   Treat the pattern as a literal string instead of a regular expression.
  --no-fixed-strings    Treat the pattern as a regular expression.
  -i, --ignore-case     Searches case insensitively.
  -L, --follow          Follow symbolic links while traversing directories.
  -P, --pcre2           When this flag is present, rg will use the PCRE2 regex engine instead of its
                        default regex engine.
  -S, --smart-case      Searches case insensitively if the pattern is all lowercase, case sensitively
                        otherwise.
  -s, --case-sensitive  Searches case sensitively.
  -v, --invert-match    Invert matching. Show lines that do not match the given patterns.
  -w, --word-regexp     Only show matches surrounded by word boundaries. This is roughly equivalent to
                        putting \b before and after all of the search patterns.
  -x, --line-regexp     Only show matches surrounded by line boundaries.
  --binary              Enabling this flag will cause ripgrep to search binary files.
  --column              Show column numbers (1-based). This only shows the column numbers for the first
                        match on each line.
  --hidden              Search hidden files and directories. By default, hidden files and directories are
                        skipped.
  --heading             Prints the file path above clusters of matches from each file instead of printing
                        the file path as a prefix for each matched line.
  --no-config           Never read configuration files. When this flag is present, rg will not respect
                        the RIPGREP_CONFIG_PATH environment variable.
  --no-ignore           Don't respect ignore files (.gitignore, .ignore, etc.). This implies --no-ignore-
                        parent and --no-ignore-vcs.
  --no-ignore-global    Don't respect ignore files that come from 'global' sources such as git's
                        `core.excludesFile` configuration option (which defaults to
                        `$HOME/.config/git/ignore`).
  --no-ignore-parent    Don't respect ignore files (.gitignore, .ignore, etc.) in parent directories.
  --no-ignore-vcs       Don't respect version control ignore files (.gitignore, etc.).
  --no-messages         Suppress all error messages related to opening and reading files.
  --no-pcre2-unicode    When PCRE2 matching is enabled, this flag will disable Unicode mode, which is
                        otherwise enabled by default.
  -E <ENCODING>, --encoding <ENCODING>
                        Specify the text encoding that rg will use on all files searched.
  -M <NUM>, --max-columns <NUM>
                        Don't print lines longer than this limit in bytes.
  -m <NUM>, --max-count <NUM>
                        Limit the number of matching lines per file searched to NUM.
  -U, --multiline       Enable matching across multiple lines.
  --multiline-dotall    This flag enables 'dot all' in your regex pattern, which causes '.' to match
                        newlines when multiline searching is enabled.
  --max-depth <NUM>     Limit the depth of directory traversal to NUM levels beyond the paths given.
  --max-filesize <NUM+SUFFIX?>
                        Ignore files larger than NUM in size. This does not apply to directories.
  --path-separator <SEPARATOR>
                        Set the path separator to use when printing file paths.
  --sort <SORTBY>       This flag enables sorting of results in ascending order.
  --sortr <SORTBY>      This flag enables sorting of results in descending order.
  -f <PATTERNFILE>..., --file <PATTERNFILE>...
                        Search for patterns from the given file, with one pattern per line.(This option
                        can be provided multiple times.)
  -g <GLOB>..., --glob <GLOB>...
                        Include or exclude files and directories for searching that match the given
                        glob.(This option can be provided multiple times.)
  --iglob <GLOB>...     Include or exclude files and directories for searching that match the given glob.
                        Globs are matched case insensitively.(This option can be provided multiple
                        times.)
  --ignore-file <PATH>...
                        Specifies a path to one or more .gitignore format rules files.
  --type-add <TYPE_SPEC>...
                        Add a new glob for a particular file type.
  -t <TYPE>..., --type <TYPE>...
                        Only search files matching TYPE. Multiple type flags may be provided.
  -T <TYPE>..., --type-not <TYPE>...
                        Do not search files matching TYPE. Multiple type-not flags may be provided.
  <PATH>                A file or directory to search. Directories are searched recursively. Paths
                        specified on the command line override glob and ignore rules.
  --current-buffer      Searches in current buffer.
  --all-buffers         Searches in all listed buffers.
  --append              Append to the previous search results.
  --match-path          Match the file path when fuzzy searching.
  --wd-mode <MODE>      Specify the working directory mode, value has the same meaning as
                        g:Lf_WorkingDirectoryMode.
  --live                Perform the so called live grep. This option implies `-F`

common arguments:
  --reverse             show results in bottom-up order
  --stayOpen            don't quit LeaderF after accepting an entry
  --input <INPUT>       specifies INPUT as the pattern inputted in advance
  --cword               current word under cursor is inputted in advance
  --top                 the LeaderF window is at the top of the screen
  --bottom              the LeaderF window is at the bottom of the screen
  --left                the LeaderF window is at the left of the screen
  --right               the LeaderF window is at the right of the screen
  --belowright          the LeaderF window is at the belowright of the screen
  --aboveleft           the LeaderF window is at the aboveleft of the screen
  --fullScreen          the LeaderF window takes up the full screen
  --popup               the LeaderF window is a popup window or floating window
  --nameOnly            LeaderF is in NameOnly mode by default
  --fullPath            LeaderF is in FullPath mode by default
  --fuzzy               LeaderF is in Fuzzy mode by default
  --regexMode           LeaderF is in Regex mode by default
  --nowrap              long lines in the LeaderF window won't wrap
  --next                Jump to the next result.
  --previous            Jump to the previous result.
  --recall              Recall last search. If the result window is closed, reopen it.
  --popup-height <POPUP_HEIGHT>
                        specifies the maximum height of popup window, only available in popup mode.
  --popup-width <POPUP_WIDTH>
                        specifies the width of popup window, only available in popup mode.
  --no-sort             do not sort the result.
  --case-insensitive    fuzzy search case insensitively.
  --auto-preview        open preview window automatically.
  --no-auto-preview     don't open preview window automatically.

If [!] is given, enter normal mode directly.
  • Normal mode command

    <CR>/<double-click>/o : open file under cursor
    x : open file under cursor in a horizontally split window
    v : open file under cursor in a vertically split window
    t : open file under cursor in a new tabpage
    p : preview the result
    d : delete the line under the cursor
    Q : output result quickfix list
    L : output result location list
    i/<Tab> : switch to input mode
    r : replace a pattern
    w : apply the changes to buffer without saving
    W : apply the changes to buffer and save
    U : undo the last changes applied
    q : quit
    <F1> : toggle this help
    

Find and replace in multiple files

Some traditional methods of finding and replacing in multiple files in vim can be found
in https://jdhao.github.io/2020/03/14/nvim_search_replace_multiple_file/.

By using Leaderf rg, you can achieve your goal more easily.
Firstly, find some pattern, .e.g, Leaderf! rg foo --bottom, then in normal mode, use the following commands:

Command Description
r replace a pattern
w apply the changes to buffer without saving
W apply the changes to buffer and save
U undo the last changes applied
u the builtin vim command.

If the buffer has been changed, :w and :W are the same as w and W in normal mode.
Command :Undo is the same as U in normal mode.

Leaderf_rg_1.mp4

PS: popup mode in vim does not support this feature.

Live grep

To enable the live grep mode for Leaderf rg, you simply need to add the option --live. Below is a demonstration of how to use it:

Leaderf_rg_2.mp4

Leaderf rg --live implies the --fixed-strings parameter, which means that each character input is treated as a literal value, rather than a regular expression. If you wish to perform a regular expression search, you can use the Leaderf rg --live --no-fixed-strings command. Furthermore, you can append other Leaderf rg parameters after Leaderf rg --live to conduct more refined searches. For instance, to exclude txt files from the search: Leaderf rg --live -g!*.txt.

Configuration examples

let g:Lf_RgConfig = [
        \ "--max-columns=150",
        \ "--type-add web:*.{html,css,js}*",
        \ "--glob=!git/*",
        \ "--hidden"
    \ ]

let g:Lf_PreviewInPopup = 1
" open the preview window automatically
let g:Lf_PreviewResult = {'Rg': 1 }

" search word under cursor, the pattern is treated as regex, and enter normal mode directly
noremap <C-F> :<C-U><C-R>=printf("Leaderf! rg -e %s ", expand("<cword>"))<CR>

" search word under cursor, use --heading
noremap <C-H> :<C-U><C-R>=printf("Leaderf! rg -e %s --heading -C3 ", expand("<cword>"))<CR>

" search word under cursor, the pattern is treated as regex,
" append the result to previous search results.
noremap <C-G> :<C-U><C-R>=printf("Leaderf! rg --append -e %s ", expand("<cword>"))<CR>

" search word under cursor literally only in current buffer
noremap <C-B> :<C-U><C-R>=printf("Leaderf! rg -F --current-buffer -e %s ", expand("<cword>"))<CR>

" search word under cursor literally in all listed buffers
noremap <C-D> :<C-U><C-R>=printf("Leaderf! rg -F --all-buffers -e %s ", expand("<cword>"))<CR>

" search visually selected text literally, don't quit LeaderF after accepting an entry
xnoremap gf :<C-U><C-R>=printf("Leaderf! rg -F --stayOpen -e %s ", leaderf#Rg#visual())<CR>

" recall last search. If the result window is closed, reopen it.
noremap go :<C-U>Leaderf! rg --recall<CR>


" search word under cursor in *.h and *.cpp files.
noremap <Leader>a :<C-U><C-R>=printf("Leaderf! rg -e %s -g *.h -g *.cpp", expand("<cword>"))<CR>
" the same as above
noremap <Leader>a :<C-U><C-R>=printf('Leaderf! rg -e %s -g "*.{h,cpp}"', expand("<cword>"))<CR>

" search word under cursor in cpp and java files.
noremap <Leader>b :<C-U><C-R>=printf("Leaderf! rg -e %s -t cpp -t java", expand("<cword>"))<CR>

" search word under cursor in cpp files, exclude the *.hpp files
noremap <Leader>c :<C-U><C-R>=printf("Leaderf! rg -e %s -t cpp -g !*.hpp", expand("<cword>"))<CR>

Reference

Screenshots

Clone this wiki locally