vim fu, swapping parameters for a method call

后端 未结 5 1143
礼貌的吻别
礼貌的吻别 2020-12-31 00:07

What is the most efficient way to swap two params for a method call in Vim?

For example, I want to change:

call \"hello mister 123\", 2343
<         


        
相关标签:
5条回答
  • 2020-12-31 00:29

    Here's a script designed to swap params in python scripts, you may be able to adapt it.

    0 讨论(0)
  • 2020-12-31 00:33

    Check out sideways.vim, a plugin by @AndrewRadev. It can handle moving parameters and other delimited list items around, with some nice features like moving nested lists as a single unit. It handles Ruby-style method calls without parentheses as well. Very handy.

    0 讨论(0)
  • 2020-12-31 00:37

    This regex will do it for your examples:

    :s/\vcall ("[^"]+"|[^,]+)\s*,\s*("[^"]+"|[^,]+)/call \2, \1/
    

    This regex will need to become progressively more nasty if you have escaped quotation marks and such things in one of your parameters.

    In reality, I'd just highlight one parameter (in visual mode), hit d, highlight the other parameter, and hit p; Vim will nicely paste what's in the register, overwriting what you have highlighted, and swap the deleted text into the register. Then move the cursor and hit p again. Highlight, d, highlight, p, move cursor, p is a common combination, in my vimming at least.

    So with the cursor at the start of the line, first example:

    wva"dlvawpF,P
    

    Meaning move past the word "call" (w), highlight a quoted string (va"), delete it (d), move one space to the right (l), highlight a word (vaw), paste (p), move backward to the comma (F,), paste before it (P).

    Second example:

    wva"dlva"p_f,P
    

    This isn't hard once you get used to the movement commands.

    0 讨论(0)
  • 2020-12-31 00:39
    :%s:call \(".*"\)\s\?,\(.*\):call \2,\1:g
    
    0 讨论(0)
  • 2020-12-31 00:48

    If your arguments are between parenthesis, like here:

    function ($argument1 = null, 'argument2') {
       ...
    }
    

    place your cursor anywhere inside the parenthesis and:

    va(:s/\\%V(\\@<=\\s*\\(.\\+\\),\\s*\\(.\\+\\)\\%V\\s*/\\2, \\1/g
    
    0 讨论(0)
提交回复
热议问题