ThG
ThG

Reputation: 2401

Word-selection swapping

I have found in vim.wikia a very useful tip (Tip 47) which suggests a visual-mode swapping.

To use this mapping: first, delete some text (using a command such as daw or dt in normal mode, or x in visual mode). Then, use visual mode to select some other text, and press Ctrl-X. The two pieces of text should then be swapped.

:vnoremap <C-X> <Esc>`.``gvP``P

I did as indicated, and it worked fine, except for one glitch (very minor, I must admit) : if I want to swap the two following texts :

[some text not to be swapped] London and Barcelona
...
[some other text not to be swapped] New York and Buenos Aires

I end up with :

[some text not to be swapped]New York and Buenos Aires
...
[some other text not to be swapped] London and Barcelona 

There is no space between ] and New York.

This is probably due to the fact that I do not fully understand (to say the least) the above :vnoremap, and do not know how to insert a space in it.

Your help (and explanation) would be welcome

Upvotes: 0

Views: 148

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172590

If you don't mind installing a plugin, there are several that provide this and more: My SwapText plugin among them. (The plugin page has links to alternative plugins.)

Upvotes: 1

romainl
romainl

Reputation: 196576

The problem is due to the P at the end pasting before the cursor: because the cursor is on a space, pasting pushes it to the end of the line (yes, you should have a trailing space, now).

Using p would fix your mapping for this specific use case ,"text at the end of the line", but it would mess with what I guess was the general case for which that mapping was created, "text somewhere in the line".

edit

This quick and dirty function checks if the cursor is at the end of the line before deciding if it does p or P but… you might as well use one of the plugins listed in that tip.

function! Swap()
    normal `.``gvP``
    if col('.') == len(getline('.'))
        normal p
    else
        normal P
    endif
endfunction

xnoremap <F7> <Esc>:call Swap()<CR>

Upvotes: 1

Related Questions