views:

201

answers:

4

For example if I have some code like:

foo = bar("abc", "def", true, callback);

Is there a nice command to move true to the 1st or 2nd position leaving the commas intact?

P.S as a bonus my friend want to know if this works in Emacs too.

+14  A: 

I don't know the answer for vi, but in Emacs, transpose-sexps (C-M-t) will swap two arguments either side of the cursor. Actually transpose-words (M-t) was my first guess, but that leaves the quotes behind.

JSON
transpose-sexps will also work for arguments like bar((1+2), "hi"), but still cannot handle bar(1+2, "hi"). Of course I doubt that anything simple could solve the general case for arbitrarily complex arguments lists.
Ivan Andrus
A: 

You need a transpose emacs command. But its limited to not guessing that its transposing in lists, it only considers text (it can't guess the 1st, 2nd word of list). Try this.

Keep your cursor at after comma of true. Use M-x transpose-words. By default it will transpose with next word from the point. Shortcut is M-t.

You can use C-u 2 M-t for transpose with next second word.

Now coming to your question. If you want to move true, to backward 1 word, use C-u -1 M-t, and for backward 2 words C-u -2 M-t.

Am not a VIM guy. So sorry bout that.

simplyharsh
+12  A: 

In Vim if you place the cursor at the start of the first word and do dWWP then it will have the desired effect. Here is a breakdown:

dW   delete the current word, including the comma and the following whitespace
W    move to the start of the next word
P    insert the deleted text before the cursor

This will work if there are further parameters after the pair to be swapped - it will need to be modified if there are only two parameters or you want to swap the last two parameters, since it will paste the text after the closing bracket.

Alternatively you could use a regex substitution:

:%s/(\([^,]\+\),\s*\([^,)]\+\)/(\2, \1/ 

This will find the first two arguments after the open bracket and swap them.

update:

A search of vim.org found the swap parameters plugin, which should do exactly what you want and can handle situations that either of the above methods cannot.

Dave Kirby
Very nice, but this won't work on the 2nd last to argument.
carl
A: 

If you want to do this as a refactoring, not just as text manipulation, I'd suggest looking into Xrefactory, a refactoring tool for Emacsen (free for C/Java, commercial for C++).

Thomas Nilsson