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 programgq{motion}pipes the covered text through the program (e.g.,gqipformats the current paragraph,gggqGformats the whole file)- The selected text is sent to the program's stdin; the program's stdout replaces the original text
- Setting
formatprgto 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 ofgq{motion}to format without moving the cursor formatprgonly affectsgq; the=operator usesequalprginstead- Backslash-escape spaces in the program name:
black\ - - Set
formatprglocally per buffer withsetlocal formatprg=...to avoid affecting other file types