vimtricks.wiki Concise Vim tricks, one at a time.

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 format
  • gq — apply the format operator to the selection
  • Vim uses the current textwidth setting (:set textwidth=80) as the column limit
  • If textwidth is 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
  • gqq formats just the current line
  • Vim respects comment leaders (--, //, #) when formatoptions includes q; it only reformats the comment content, not the leaders
  • Set textwidth per filetype in your config: autocmd FileType markdown setlocal textwidth=80
  • If the results are wrong, check :set formatoptions? — the a flag (auto-wrap) or a formatexpr can override gq behavior

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?