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

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

Answer

:set formatprg=<cmd>

Explanation

When formatprg is set, the gq operator pipes the selected text through that external program and replaces it with the program's output. This lets you format any text object or motion with tools like prettier, black, gofmt, or anything that reads from stdin and writes to stdout.

How it works

  • gq{motion} — the format operator; applies to any motion or text object (e.g., gqip for a paragraph, gqq for the current line, gqG for rest of file)
  • formatprg — holds the shell command Vim pipes text into; the program must read from stdin and write formatted output to stdout
  • formatexpr — if this is set (e.g., by an LSP), it takes priority over formatprg; use :setlocal formatexpr= to clear it

Example

Format a Python file selection with black:

:set formatprg=python3\ -m\ black\ -

Then gqip reformats the current paragraph. For a Go file with gofmt:

:set formatprg=gofmt

For JavaScript with prettier:

:set formatprg=prettier\ --parser\ babel

Tips

  • Use :setlocal formatprg=... to configure it per-buffer via a FileType autocmd
  • If formatting fails, Vim keeps the original text unchanged
  • gqq formats just the current line; gqG formats from cursor to end of file
  • When formatexpr is set by an LSP plugin, gq uses it instead; clear with :setlocal formatexpr= to force formatprg

Next

How do I create a Vim mapping where the keys it produces are computed dynamically at runtime?