Yuri Ghensev
Yuri Ghensev

Reputation: 2545

Vim: Invert function's parameter order?

Suppose I got this function call:

cook("rice", kitchen->pot);

After writing that, I notice parameter order is wrong, I should have done

cook(kitchen->pot, "rice");

To fix that, I could do:

    1: move cursor over "rice": $b
    2: delete a ": da"
    3: move to (: %
    4: paste "rice": p
    5: insert new ,: a, 
    6: find and delete spare ,: f,x

But im using VIM! We edit code faster with vim, any ideas?

Upvotes: 2

Views: 1483

Answers (5)

Luc Hermitte
Luc Hermitte

Reputation: 32966

With omap-param (from lh-cpp) + a stuff swapping plugin, I would have typed f(ldi,lvi,g". Where di, says delete inner param, vi, says select inner param, and g" says swap selection with the thing we have just deleted.

This approach may seem overkill, however unlike naive approaches it will still work with parameters like kitchen->getPot(medium, blue).

Upvotes: 2

joeytwiddle
joeytwiddle

Reputation: 31285

There is an attempt (which actually calls out to Ruby) here: https://github.com/vim-scripts/reorder.vim

It can be invoked by: :Reorder 3,2,1

Personally I think we can do better! I may try to write a plugin for this... Thinking the keybinds could be mcl and mch for Move Clause Right / Left.

As well as function arguments, I also find myself wanting to change the order of clauses in English sentences. "I also find myself wanting to change the order of clauses in English sentences, as well as function arguments."

Another use case is items in lists which are line-separated, but for which the last argument alone should omit a trailing comma.

Upvotes: 0

bentsai
bentsai

Reputation: 3133

:map <F9> "qdt,dwep"qp

No plugins required. Based on soulemerge's answer, I found that this works a little better when you're dealing with code. In other words, the iw wasn't working well for me in the case of:

Assert.AreEqual(myProp.ToString(), 0xcccc);

If I started at myProp, it would only capture up to the .. This code just takes you up to the comma, which is particularly useful if you are swapping parameters.

Upvotes: 2

Yuri Ghensev
Yuri Ghensev

Reputation: 2545

Your answers are really helpful, but I just found a solution by myself:

:s/\v(\w+\()([^,]+)(,\s*)([^\),]+)/\1\4\3\2

That will work with most kinds of parameters, and specially for my php-like function calls.

Upvotes: 2

Xavier T.
Xavier T.

Reputation: 42238

There is a similar question here which is Ruby specific but which should work for you:

What is the fastest way to reverse a comma-separated list in vim?

Apparently there is no silver bullet.

Personally, I quite like soulemerge's solution.

Upvotes: 2

Related Questions