How do I reformat a paragraph or visual selection to fit a specific line width?
Answer
gq
Explanation
The gq operator reformats text to fit within your configured textwidth. When applied to a visual selection or combined with a motion, it reflows the text so that each line stays within the specified width, intelligently breaking at word boundaries. This is invaluable for writing prose, comments, commit messages, or any text that needs consistent line lengths.
How it works
gq{motion}in normal mode reformats from the cursor to the target of the motion. For example,gqapreformats the entire current paragraph, andgq}reformats to the end of the paragraph.gqin visual mode reformats the selected lines.gqqreformats the current line only.- The target width is controlled by the
textwidthoption::set textwidth=80sets it to 80 columns. - Vim breaks lines at spaces, respecting word boundaries. It merges short lines and splits long ones.
- Use
gwinstead ofgqif you want to reformat without moving the cursor.
Example
With :set textwidth=40, select these lines and press gq:
Before:
This is a very long line that goes way beyond the configured text width and needs to be broken up into multiple shorter lines.
After:
This is a very long line that goes
way beyond the configured text width
and needs to be broken up into
multiple shorter lines.
Tips
gqap(reformat around paragraph) is one of the most useful combinations — memorize it- Set
formatoptions+=afor automatic reformatting as you type - The
formatprgoption lets you use an external program likeparorfmtfor more sophisticated formatting - Use
gwinstead ofgqto keep your cursor position unchanged after reformatting