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

How do I use an external formatter with the gq operator in Vim?

Answer

:set formatprg={program}

Explanation

Vim's gq operator normally reflows text to fit textwidth, but by setting formatprg you can delegate formatting to any external tool — a language formatter, a linter, or a custom script. With formatprg set, gq{motion} pipes the selected lines through the program's stdin and replaces them with stdout.

How it works

  • :set formatprg={program} assigns an external command as the format program
  • gq{motion} pipes the covered text through the program (e.g., gqip formats the current paragraph, gggqG formats the whole file)
  • The selected text is sent to the program's stdin; the program's stdout replaces the original text
  • Setting formatprg to an empty string (:set formatprg=) reverts to Vim's built-in text reflow

Example

Format the current buffer with black for Python:

:set formatprg=black\ -q\ -
gggqG

Or format only the current paragraph with prettier:

:set formatprg=prettier\ --parser\ babel
gqip

You can also set it per filetype in your vimrc:

autocmd FileType python setlocal formatprg=black\ -q\ -
autocmd FileType rust   setlocal formatprg=rustfmt

Tips

  • Use gw{motion} instead of gq{motion} to format without moving the cursor
  • formatprg only affects gq; the = operator uses equalprg instead
  • Backslash-escape spaces in the program name: black\ -
  • Set formatprg locally per buffer with setlocal formatprg=... to avoid affecting other file types

Next

How do I open the command-line window while in the middle of typing a command?