Wiki

by yszheda

View project onGitHub

Tip 109: Customize the grep Program

Return to the top: <<Practical Vim>>

Vim's Default grep Settings

  • 'grepprg' setting specifies what to run in the shell when Vim's :grep command is executed.

References:

# If you open the file in vim,
# then you can \"ayy@a the next line to execute the vim command: 
:h 'grepprg'
  • 'grepformat' setting tells Vim how to parse the output returned by the :grep command.

References:

# If you open the file in vim,
# then you can \"ayy@a the next line to execute the vim command: 
:h 'grepformat'
  • Default settings on Unix systems:
    grepprg="grep -n $* /dev/null"
    grepformat="%f:%l:%m,%f:%l%m,%f %l%m"
    
    • The $* symbol used in the 'grepprg' setting is a placeholder, which is replaced with any arguments supplied to the :grep command.
    • The special tokens used in the 'grepformat' string are the same as those used by 'errorformat'.
      # If you open the file in vim,
      # then you can \"ayy@a the next line to execute the vim command: 
      :h errorformat
      
      • %f matches the filename
      • %l matches the line number
      • %m matches the text on that line

Make :grep Call ack

:set grepprg=ack\ --nogroup\ $*

Make ack Jump to Line and Column

  • %c matches the column number
    :set grepprg=ack\ --nogroup\ --column\ $*
    :set grepformat=%f:%l:%c:%m
    

Alternative grep Plugins

  • grep uses POSIX regular expressions, whereas ack uses Perl regular expressions.
  • ack.vim and fugitive.vim create custom commands rather than overriding the :grep command, they can all coexist without conflict.