Is there a good Vi(m) command for transposing arguments in a function call? Bonus points for Emacs

前端 未结 5 1143
北荒
北荒 2021-02-14 05:09

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 posit

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-14 05:25

    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.

提交回复
热议问题