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
gwis the "format" operator — likegq, it wraps lines to fittextwidthipis the "inner paragraph" text object, selecting the current paragraph without surrounding blank lines- The key difference:
gqmoves the cursor to the last line that was changed;gwreturns the cursor to where it was before the operation - Both operators respect
textwidth,formatexpr, andformatprg
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
gwwto format only the current line gwaccepts any motion:gw3jreformats the current and next 3 lines- In visual mode,
gwreformats the selected text - If you have
formatprgset (e.g.,parorfmt), bothgwandgqinvoke it — but onlygwkeeps cursor position - Prefer
gwin mappings where cursor stability matters, such as an auto-format-on-save mapping