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

How do I reformat text to fit the line width without moving the cursor?

Answer

gwip

Explanation

The gw operator reformats text just like gq, but leaves the cursor in its original position after reformatting. This makes it preferable when you want to reformat a block of text without losing your place in the file.

How it works

  • gw is the "format" operator — like gq, it wraps lines to fit textwidth
  • ip is the "inner paragraph" text object, selecting the current paragraph without surrounding blank lines
  • The key difference: gq moves the cursor to the last line that was changed; gw returns the cursor to where it was before the operation
  • Both operators respect textwidth, formatexpr, and formatprg

Example

With textwidth=40, given a long paragraph:

This is a very long line that exceeds the configured text width and needs to be reformatted.

After gwip, the paragraph is wrapped:

This is a very long line that exceeds
the configured text width and needs
to be reformatted.

The cursor stays on the word it was on before the reformat.

Tips

  • Use gww to format only the current line
  • gw accepts any motion: gw3j reformats the current and next 3 lines
  • In visual mode, gw reformats the selected text
  • If you have formatprg set (e.g., par or fmt), both gw and gq invoke it — but only gw keeps cursor position
  • Prefer gw in mappings where cursor stability matters, such as an auto-format-on-save mapping

Next

How do I pipe a visual selection through an external shell command and replace it with the output?