How do I hard-wrap or reformat a paragraph to fit the current textwidth?
Answer
gq{motion}
Explanation
The gq{motion} operator reformats text to fit within Vim's textwidth setting, inserting hard line breaks where lines are too long. It's the go-to command for wrapping prose, doc comments, and commit messages to a consistent column limit without doing it manually.
How it works
gq— the format operator; it reformats the text covered by the motion or text object{motion}— any Vim motion or text object:apfor a paragraph,jfor the current and next line,Gfor everything to end of file- Vim uses the
textwidthoption to determine the target line length. Set it with:set textwidth=80 - If
textwidthis 0 (the default), lines are not wrapped — set it before usinggq
Common combos:
| Keys | Effect |
|---|---|
gqap |
Reformat the current paragraph |
gqq |
Reformat the current line only |
gq} |
Reformat from cursor to end of paragraph |
gggqG |
Reformat the entire buffer |
Example
With :set textwidth=40 and this text:
This is a sentence that is much too long to fit within forty characters comfortably.
After gqap:
This is a sentence that is much
too long to fit within forty
characters comfortably.
Tips
gw{motion}behaves identically but leaves the cursor at its original position instead of moving it to the end of the reformatted area — useful in mappings- Set
formatprgto routegqthrough an external tool (e.g.,prettier,par,fmt) - In visual mode, select a block then press
gqto reformat only the selection - The
fo-tflag informatoptionsenables automatic wrapping as you type;gqis the manual counterpart