vimtricks.wiki Concise Vim tricks, one at a time.

How do I make the = operator use an external formatter instead of Vim's built-in indentation?

Answer

:set equalprg={program}

Explanation

The equalprg option replaces Vim's built-in = indentation operator with any external formatting program. When set, commands like gg=G (indent whole file) or =ip (indent paragraph) pipe the selected text through the configured program and replace it with the formatted output.

How it works

  • By default, = uses Vim's internal indentation rules (cindent, lisp, indentexpr)
  • Setting equalprg to an external command name causes = to pipe selected lines to that program's stdin and read the result from stdout
  • Use setlocal equalprg in filetype-specific files to apply different formatters per language
  • Set equalprg= (empty string) to revert to Vim's built-in indenter

Example

Format Python files with black:

:setlocal equalprg=black\ -q\ -

Now gg=G reformats the entire file with black:

gg=G

Format Go files with gofmt:

:setlocal equalprg=gofmt

Add to ~/.vim/ftplugin/go.vim for automatic setup:

setlocal equalprg=gofmt

Tips

  • The = operator accepts any motion: =ip formats a paragraph, =5j formats the next 5 lines
  • Related options: formatprg controls the external program used by gq; grepprg controls :grep
  • To reset to Vim's internal indenter: :set equalprg=
  • If the external program exits with an error, the buffer content is not changed

Next

How do I duplicate every line matching a pattern, placing a copy directly below each one?