How do I reformat and rewrap a selected block of text to fit within a line width?
Answer
gq (in visual mode)
Explanation
gq is Vim's format operator. In Visual mode, gq reformats the selected text, joining and rewrapping it to fit within the textwidth setting (default 79 characters). It handles trailing spaces, joining lines that are too short, and breaking lines that are too long.
How it works
- Select text with
v,V, or<C-v> - Press
gq - Vim reformats the selection to fit
textwidth
Normal mode forms
gqq— reformat the current linegq}— reformat to end of paragraphgqip— reformat the inner paragraphgqG— reformat from cursor to end of filegwip— likegqipbut keeps cursor in place
Example
A paragraph hard-wrapped at 40 chars that you want at 80:
This is a long piece of text that
was wrapped too early because the
original author used a narrow
column.
Select all lines with vip, then gq (with textwidth=80) produces:
This is a long piece of text that was wrapped too early because the original
author used a narrow column.
Tips
:set textwidth=80before formatting to control line lengthgwis likegqbut does not move the cursor — useful in mappingsgqrespects comment leaders (e.g.,//,#) when reformatting code comments- For prose, pair with
:set formatoptions+=afor automatic re-wrapping as you type