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

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

Answer

gq

Explanation

The gq operator reformats text to fit within your configured textwidth. When applied to a visual selection or combined with a motion, it reflows the text so that each line stays within the specified width, intelligently breaking at word boundaries. This is invaluable for writing prose, comments, commit messages, or any text that needs consistent line lengths.

How it works

  • gq{motion} in normal mode reformats from the cursor to the target of the motion. For example, gqap reformats the entire current paragraph, and gq} reformats to the end of the paragraph.
  • gq in visual mode reformats the selected lines.
  • gqq reformats the current line only.
  • The target width is controlled by the textwidth option: :set textwidth=80 sets it to 80 columns.
  • Vim breaks lines at spaces, respecting word boundaries. It merges short lines and splits long ones.
  • Use gw instead of gq if you want to reformat without moving the cursor.

Example

With :set textwidth=40, select these lines and press gq:

Before:
This is a very long line that goes way beyond the configured text width and needs to be broken up into multiple shorter lines.
After:
This is a very long line that goes
way beyond the configured text width
and needs to be broken up into
multiple shorter lines.

Tips

  • gqap (reformat around paragraph) is one of the most useful combinations — memorize it
  • Set formatoptions+=a for automatic reformatting as you type
  • The formatprg option lets you use an external program like par or fmt for more sophisticated formatting
  • Use gw instead of gq to keep your cursor position unchanged after reformatting

Next

How do I ignore whitespace changes when using Vim's diff mode?