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

How do I hard-wrap or reformat a paragraph to fit the current textwidth?

Answer

gq{motion}

Explanation

The gq{motion} operator reformats text to fit within Vim's textwidth setting, inserting hard line breaks where lines are too long. It's the go-to command for wrapping prose, doc comments, and commit messages to a consistent column limit without doing it manually.

How it works

  • gq — the format operator; it reformats the text covered by the motion or text object
  • {motion} — any Vim motion or text object: ap for a paragraph, j for the current and next line, G for everything to end of file
  • Vim uses the textwidth option to determine the target line length. Set it with :set textwidth=80
  • If textwidth is 0 (the default), lines are not wrapped — set it before using gq

Common combos:

Keys Effect
gqap Reformat the current paragraph
gqq Reformat the current line only
gq} Reformat from cursor to end of paragraph
gggqG Reformat the entire buffer

Example

With :set textwidth=40 and this text:

This is a sentence that is much too long to fit within forty characters comfortably.

After gqap:

This is a sentence that is much
too long to fit within forty
characters comfortably.

Tips

  • gw{motion} behaves identically but leaves the cursor at its original position instead of moving it to the end of the reformatted area — useful in mappings
  • Set formatprg to route gq through an external tool (e.g., prettier, par, fmt)
  • In visual mode, select a block then press gq to reformat only the selection
  • The fo-t flag in formatoptions enables automatic wrapping as you type; gq is the manual counterpart

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?