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.,gqipfor a paragraph,gqqfor the current line,gqGfor rest of file)formatprg— holds the shell command Vim pipes text into; the program must read from stdin and write formatted output to stdoutformatexpr— if this is set (e.g., by an LSP), it takes priority overformatprg; 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 aFileTypeautocmd - If formatting fails, Vim keeps the original text unchanged
gqqformats just the current line;gqGformats from cursor to end of file- When
formatexpris set by an LSP plugin,gquses it instead; clear with:setlocal formatexpr=to forceformatprg