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
equalprgto an external command name causes=to pipe selected lines to that program's stdin and read the result from stdout - Use
setlocal equalprgin 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:=ipformats a paragraph,=5jformats the next 5 lines - Related options:
formatprgcontrols the external program used bygq;grepprgcontrols:grep - To reset to Vim's internal indenter:
:set equalprg= - If the external program exits with an error, the buffer content is not changed