Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm not good enough at vim to determine whether this was possible or not (which is why I came to superuser and not good) ~ is there a way in vim to easily switch two words?

for example in def function(param1, param2) is there a quick/easy way to change that to def function(param2, param1)???

share|improve this question
up vote 6 down vote accepted

I don't remember where I originally got this, but it's been in my ~/.vimrc for at least a few years:

" Swap the word the cursor is on with the next word (which can be on a
" newline, and punctuation is "skipped"):
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o>:noh<CR>

After you have this defined, all you need to do is put your cursor somewhere on "param1" in normal mode and type: gw

share|improve this answer
1  
I have it also, it comes from the vim wiki. – romainl May 30 '11 at 6:48

+1 for @Heptite's answer.

For more completeness, here is what I have in my .vimrc:

" push current line up or down
nnoremap <leader><Up> ddkP
nnoremap <leader><Down> ddp

" exchange character under cursor with the next character without moving the cursor
nnoremap gc xph

" exchange word under cursor with the next word without moving the cursor
nnoremap gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o><C-l>

" push word under cursor to the left
nnoremap <leader><Left> "_yiw?\w\+\_W\+\%#<CR>:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o><C-l>

" push word under cursor to the right
nnoremap <leader><Right> "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o>/\w\+\_W\+<CR><C-l>

Source: the vim wiki.

I see my (and the wiki's) gw is slightly different from Heptite's one. I'm not sure which one is better.

share|improve this answer

That long solution is ugly. Suppose your cursor is at the left the first letter of the first word, that is 'p'. Do this: dwlpldw%p. This fits in your special case. How about dealing with daily editing? Try dwwP, or dWWP. :D

Tips: Don't always write long regular expression, if you don't need to do this often. Otherwise your vimrc booms. All vim users shall be familiar with its builtin cursor movement.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .