Vim Tips Wiki

Exchanging adjacent words

Revision as of 08:38, May 11, 2008 by JohnBot (Talk | contribs)

1,619pages on
this wiki
Tip 1539 Printable Monobook Previous Next

created December 6, 2007 · complexity basic · author Michael Geddes · version 6.0

Map a key combination to this regular expression: this transposes the keyword under the cursor with the next keyword, including skipping line breaks.


To replace the keyword under the cursor with the previous keyword (no line breaks), use:


I'm sure that a "previous word" version to handle line breaks can be done, especially if you relax the requirement of using \k to match keyword characters.

The traditional way to swap words is something like dawwp (see VimTip47) or such movements. However these aren't a generic solution and only work where the delimiters are whitespace.

This approach is cleaner about leaving the surrounding non-keyword characters where they are, and works cleanly at the end of lines and over line breaks.

For example




It can also be used with other atoms such as [a-zA-Z0-9] which in some ways is simpler as it can be negated more easily (aiding with the 'reverse' case).

The trick for this tip is the %# atom, which matches the cursor position. This atom can easily be used in cases like this for acting on text under the cursor. Note the use of \v, "very magic" and of \_., "any character including newline".



Around Wikia's network

Random Wiki