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

How do I reformat text to fit textwidth without moving the cursor from its current position?

Answer

gw{motion}

Explanation

The gw operator reformats text just like gq, but leaves the cursor exactly where it started. This makes it ideal for running inside macros, repeat operations, or whenever you want to reflow text without the distraction of the cursor jumping to the end of the formatted region.

How it works

  • gw — the format-without-move operator (pairs with any motion or text object)
  • {motion} — any motion or text object: ap (a paragraph), ip (inner paragraph), _ (current line), 5j (five lines down), etc.
  • Formatting respects 'textwidth', 'formatoptions', and 'formatexpr'

The key difference between gw and gq:

Command Cursor after format
gq Moves to the last formatted line
gw Stays at the original position

Example

Cursor is mid-paragraph on the word quickly:

The quick brown fox
jumped over the lazy dog and then quickly ran away to another place.

After gwip (format inner paragraph, textwidth=40):

The quick brown fox jumped over the
lazy dog and then quickly ran away
to another place.

With gq, the cursor would end up at the last line. With gw, it remains on quickly.

Tips

  • gww reformats only the current line (equivalent to gw_)
  • Use gw inside macros to avoid the cursor drift that gq introduces
  • Combine with gw} to format from the cursor to the end of the paragraph
  • Both operators accept a count: 3gwj formats three lines below the current one

Next

How do I prepend a value to the front of a comma-separated Vim option like path or runtimepath?