Tip #470: Map to quickly swap/exchange arbitrary text
tip karma |
Rating 47/22, Viewed by 1322
|
created: |
|
May 5, 2003 10:31 |
|
complexity: |
|
intermediate |
author: |
|
Piet Delport |
|
as of Vim: |
|
5.7 |
When editing text, it's not uncommon to need to swap two bits of text. In
Vim, it's easy to swap adjacent characters, words and lines (see vimtip #47),
but to swap non-adjacent text (such as comma-separated words, variable
assignments, and function parameters), you usually have to resort to a tedious
delete/move/put/delete/move/put sequence.
Mappings such as the one in vimtip #329 can help in some cases, but for a more
general solution, try this mapping:
vnoremap <C-X> <Esc>`.``gvP``P
To use it: First, delete some text (using any normal Vim command, such as
daw, {Visual}x, or dt,). Then, visually select some other text, and press
CTRL-X. The two pieces of text should now be swapped.
For example, to swap "apple" and "orange" in the line below:
int apple, lemon, orange;
1. Delete "apple", using (for example) diw or <double-click>d
2. Visually select "orange"
3. Press CTRL-X
The mapping is not limited to single words, though, and will work with
anything you can delete/select (even lines and blockwise selections).
<<The use of %< instead of % |
Bridging the worlds: putting your rodent to work for vim in xterms >>
Additional Notes
|