Reputation: 1039
For example, Guess I have this block.
if( first > second)
{
}
And I want to swap these words with crossing one operator.
if( second > first)
{
}
How to do with vim command naturally?
Upvotes: 7
Views: 4019
Reputation: 131
" Swap two words
nmap <silent> gw :s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR>`'
Place your cursor at 1st letter f
of first
if( first > second)
then press gw
to swap between first
and second
You will get your desired output if( second > first)
Upvotes: 1
Reputation: 7657
This solution uses the following function:
function! Swap()
normal di)
let a=split(@")
let @b=a[2]." ".a[1]." ".a[0]
normal %"bp
endfunction
That can be mapped to gs
, for example:
nnoremap <silent> gs :call Swap()<cr>
A drawback of this approach is that it is more involved than solutions based on mappigs. Its advantage is that it works by placing the cursor anywhere inside the parenthesis (...)
.
Upvotes: 1
Reputation: 11840
I have vim-exchange plugin that allows me to change words in this way.
At the first word press cxiw
then jump to the second word and press .
Upvotes: 6
Reputation: 196926
If you wanted to do that manually you could do the following (with the cursor on first
):
yiw yank current word
ww move cursor to 'second'
viw visually select current word
p put from unnamed register (selected word goes to unnamed register)
bbb move cursor back to 'first'
viw visually select current word
p put from unnamed register
which is relatively intuitive but, admittedly, quite involving.
You could probably map that to some easy to type key-combination:
nnoremap <key> yiwwwviwpbbbviwp
but you may end up having to fight against corner case after corner case.
Or you could put this snippet (found here) in your vimrc
and simply press <key1>
to swap the current "word" with the previous and <key2>
to swap the current "word" with the next:
nnoremap <key1> "_yiw?\v\w+\_W+%#<CR>:s/\v(%#\w+)(\_W+)(\w+)/\3\2\1/<CR><C-o><C-l>
nnoremap <key2> "_yiw:s/\v(%#\w+)(\_W+)(\w+)/\3\2\1/<CR><C-o>/\v\w+\_W+<CR><C-l>
Upvotes: 7
Reputation: 1900
Pending a more natural way to do it, how about this?
:map <f7> <esc>dbwPwdwbbPl<esc>
Place the cursor on <
and press F7.
Upvotes: 1