How do I reformat a paragraph to fit a specific line width in Vim?
Answer
gqap
Explanation
The gq operator reformats text by wrapping lines to fit within the textwidth setting. Combined with the ap text object (a paragraph), gqap reflows the paragraph under the cursor so that no line exceeds the configured width. This is essential when editing prose, commit messages, documentation, or any text where consistent line lengths matter.
How it works
gq— The format operator. It wraps text according totextwidth(or 79 if unset, depending onformatoptions).ap— The "a paragraph" text object, which selects the current paragraph (contiguous non-blank lines).- Together,
gqapreformats the entire paragraph around the cursor.
Set your desired width first:
:set textwidth=80
Example
Before (a long, unwrapped line):
This is a very long line that contains a lot of text and should really be wrapped to a more reasonable width for readability in a terminal or editor window.
After gqap with textwidth=40:
This is a very long line that
contains a lot of text and should
really be wrapped to a more
reasonable width for readability
in a terminal or editor window.
Tips
- Use
gqqto reformat just the current line. - Use
gq}to reformat from the cursor to the end of the paragraph. - In visual mode, select lines and press
gqto reformat the selection. - Use
gwinstead ofgqto reformat without moving the cursor. - Set
formatoptions+=afor automatic reformatting as you type.