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

How do I make the = operator format code with an external tool like gofmt or black?

Answer

:set equalprg=gofmt

Explanation

By default, Vim's = operator re-indents text using its internal rules. Setting equalprg replaces that behaviour entirely: instead of re-indenting, Vim pipes the selected lines through the external program and replaces them with its output. This gives you one-keystroke formatting with any CLI formatter — no plugin required.

How it works

:set equalprg=gofmt

Now gg=G (the classic "re-indent entire file" sequence) runs gofmt on the buffer contents. Any = motion works the same way:

  • == — format the current line
  • =ip — format the current paragraph
  • =G — format from cursor to end of file
  • gg=G — format the entire file

The formatter receives the selected lines on stdin and must write the result to stdout.

Example

For different languages, set equalprg in your ftplugin or an autocmd:

autocmd FileType python setlocal equalprg=black\ -
autocmd FileType go    setlocal equalprg=gofmt
autocmd FileType json  setlocal equalprg=python3\ -m\ json.tool

With the cursor anywhere in a Python file, gg=G runs black - on the entire file.

Tips

  • Use setlocal (not set) so the setting applies only to the current buffer.
  • equalprg is a drop-in path — use \ to escape spaces in arguments.
  • Reset to Vim's built-in re-indent with :set equalprg= (empty string).
  • For formatters that need a filename hint (e.g. Prettier): :set equalprg=prettier\ --stdin-filepath\ %

Next

How do I exclude compiled files and dependency folders from Vim's file name completion?