Exchanging adjacent words
From Vim Tips Wiki
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.
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".