How do I reflow and hard-wrap a paragraph or selected lines to a fixed width in Vim?
Answer
gq (visual mode)
Explanation
Pressing gq on a visual selection reformats the selected lines to hard-wrap at textwidth columns. Vim re-joins lines that are too short and wraps lines that are too long, producing neatly formatted paragraphs. This is invaluable for wrapping comment blocks, prose, and commit messages.
How it works
v/V/vip— enter visual mode and select lines to formatgq— apply the format operator to the selection- Vim uses the current
textwidthsetting (:set textwidth=80) as the column limit - If
textwidthis 0, it defaults to 79
Example
Original (with textwidth=50):
-- This is a very long comment that goes far past the desired line width and needs reformatting.
After selecting the line with V and pressing gq:
-- This is a very long comment that goes far
-- past the desired line width and needs
-- reformatting.
Tips
- Use
gqip(no visual selection) to reformat the inner paragraph the cursor is in—no selection needed gqqformats just the current line- Vim respects comment leaders (
--,//,#) whenformatoptionsincludesq; it only reformats the comment content, not the leaders - Set
textwidthper filetype in your config:autocmd FileType markdown setlocal textwidth=80 - If the results are wrong, check
:set formatoptions?— theaflag (auto-wrap) or aformatexprcan overridegqbehavior