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

前端 未结 5 1141
北荒
北荒 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:14

    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.

    0 讨论(0)
  • 2021-02-14 05:14

    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++).

    0 讨论(0)
  • 2021-02-14 05:22

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-14 05:36

    Transposing previous (Ctrl-t p) and next (Ctrl-t n) argument ... add the following into your .vimrc file:

    map <C-t>p ?,\\|(<CR>wd/,\\|)<CR>?,\\|(<CR>"_dw?,\\|(<CR>a, <C-c>?,<CR>P/,<CR>w
    map <C-t>n ?,\\|(<CR>wv/,<CR>d"_dw/\\,\\|)<CR>i, <C-r>"<C-c>?,<CR>?,\\|(<CR>w
    
    0 讨论(0)
提交回复
热议问题