Vim Tips Wiki
Advertisement
Tip 1539 Printable Monobook Previous Next

created 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.

s/\v(<\k*%#\k*>)(\_.{-})(<\k+>)/\3\2\1/

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

s/\v(<\k+>)(.{-})(<\k*%#\k*>)/\3\2\1/

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

this->test

becomes

test->this

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".

References[]

Comments[]

Advertisement