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

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

  1. Select text with v, V, or <C-v>
  2. Press gq
  3. Vim reformats the selection to fit textwidth

Normal mode forms

  • gqq — reformat the current line
  • gq} — reformat to end of paragraph
  • gqip — reformat the inner paragraph
  • gqG — reformat from cursor to end of file
  • gwip — like gqip but 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=80 before formatting to control line length
  • gw is like gq but does not move the cursor — useful in mappings
  • gq respects comment leaders (e.g., //, #) when reformatting code comments
  • For prose, pair with :set formatoptions+=a for automatic re-wrapping as you type

Next

How do I run a search and replace only within a visually selected region?