Vim logo vim online Vim Book Ad

 Tip #329: A map for swapping words

 tip karma   Rating 22/9, Viewed by 622 

created:   September 20, 2002 9:27      complexity:   intermediate
author:   Chip Campbell, Arun Easi, Benji Fisher      as of Vim:   6.0

Put the following map into your <.vimrc>:

  nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l>

Then when you put the cursor on or in a word, press "gw", and
the word will be swapped with the next word.  The words may
even be separated by punctuation (such as "abc = def").

While we're talking swapping, here's a map for swapping characters:

  nmap <silent> gc    xph

This hint was formed in a collaboration between
Chip Campbell - Arun Easi - Benji Fisher

 rate this tip  Life Changing Helpful Unfulfilling 

<<Vim in Microsoft Visual Foxpro | how to stop auto indenting >>

Additional Notes

[email protected], September 20, 2002 11:08
Thought I'd mention some of the reasoning behind the gw-map above.  Sequences such as  dawelp suffer from one or more problems:

* fencepost problems: they don't work correctly either at the beginning of a line
  or at the end of a line

* single-character-word problems: mappings using b, e, or variants don't handle
  single-character words properly.
jean upfrontsystems co za, October 5, 2002 11:03
Looks like this doesn't swap "this" and "that" when line 2 starts with "that", and line 1 ends on "this";
that is a problem for another day :)

Just possibly Vim's newline-matching regexps will be able to cope with this .. but it's probably going
too far.
[email protected], December 2, 2002 7:42
Making vim handle word swapping across a newline is
fairly straightforward:

nmap <silent> gw    "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l>

Just one extra underscore (at a suitable location, of course :) .
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
SourceForge Logo