How do I reformat a paragraph to fit a specific line width?
Answer
gqip
Explanation
The gqip command reformats the current paragraph to fit within the configured textwidth. It reflows the text by breaking long lines and joining short ones, making it ideal for wrapping prose, comments, and documentation to a consistent width.
How it works
gqis the format operatoripis the "inner paragraph" text object — all contiguous non-blank lines around the cursor- Together they reformat the paragraph so that no line exceeds the
textwidthsetting
Example
With :set textwidth=40, given the text:
This is a very long line that definitely exceeds forty characters and needs to be wrapped properly.
Pressing gqip reformats it to:
This is a very long line that
definitely exceeds forty characters
and needs to be wrapped properly.
Setting the text width
Before using gq, set your desired line width:
:set textwidth=80
If textwidth is 0, Vim uses the value of columns or 79, whichever is smaller.
Tips
- Use
gqqto reformat just the current line - Use
gq}to reformat from the cursor to the end of the paragraph - Use
gqapto reformat the paragraph including one trailing blank line - In visual mode, select lines and press
gqto reformat the selection - Use
gwinstead ofgqto reformat without moving the cursor - Use
gqGto reformat from the current line to the end of the file - Use
:set formatoptions+=ato enable automatic reformatting as you type — the paragraph reflows in real time - For code comments, Vim respects comment leaders (like
//or#) when reformatting ifformatoptionsincludescandr