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

How do I reformat a paragraph to fit a specific line width?

Answer

gqip

Explanation

The gqip command reformats the current paragraph to fit within the configured textwidth. It reflows the text by breaking long lines and joining short ones, making it ideal for wrapping prose, comments, and documentation to a consistent width.

How it works

  • gq is the format operator
  • ip is the "inner paragraph" text object — all contiguous non-blank lines around the cursor
  • Together they reformat the paragraph so that no line exceeds the textwidth setting

Example

With :set textwidth=40, given the text:

This is a very long line that definitely exceeds forty characters and needs to be wrapped properly.

Pressing gqip reformats it to:

This is a very long line that
definitely exceeds forty characters
and needs to be wrapped properly.

Setting the text width

Before using gq, set your desired line width:

:set textwidth=80

If textwidth is 0, Vim uses the value of columns or 79, whichever is smaller.

Tips

  • Use gqq to reformat just the current line
  • Use gq} to reformat from the cursor to the end of the paragraph
  • Use gqap to reformat the paragraph including one trailing blank line
  • In visual mode, select lines and press gq to reformat the selection
  • Use gw instead of gq to reformat without moving the cursor
  • Use gqG to reformat from the current line to the end of the file
  • Use :set formatoptions+=a to enable automatic reformatting as you type — the paragraph reflows in real time
  • For code comments, Vim respects comment leaders (like // or #) when reformatting if formatoptions includes c and r

Next

How do I edit multiple lines at once using multiple cursors in Vim?