【问题标题】:Easily reformatting function arguments onto multiple lines in Vim在 Vim 中轻松将函数参数重新格式化为多行
【发布时间】:2012-10-04 18:53:11
【问题描述】:

特别是在编辑遗留 C++ 代码时,我经常发现自己手动重新格式化如下内容:

SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree);

到这样的事情:

SomeObject doSomething(firstType argumentOne,
                       secondType argumentTwo,
                       thirdType argumentThree);

是否有内置命令来执行此操作?如果没有,有人可以推荐一个插件或提供一些 VimScript 代码吗? (Jgq 可以很容易地逆转这个过程,所以不需要双向。)

【问题讨论】:

  • 这似乎是超级用户的问题
  • @Wug Vim 社区在站点之间分裂。这是一个关于 Vim 的特定编码使用的问题,因此非常适合这个网站,当然我也可以在那里问。

标签: vim formatting arguments


【解决方案1】:

这是我在.vimrc 中输入的内容。它比@rbernabe 的回答更灵活;它根据cinoptions 全局设置进行格式化,并简单地以逗号分隔(因此,如果需要,可以用于多个函数)。

function FoldArgumentsOntoMultipleLines()
    substitute@,\s*@,\r@ge
    normal v``="
endfunction

nnoremap <F2> :call FoldArgumentsOntoMultipleLines()<CR>
inoremap <F2> <Esc>:call FoldArgumentsOntoMultipleLines()<CR>a

这会将 F2 在正常和插入模式下映射到在当前行上进行搜索和替换,这会将所有逗号(每个逗号后面有 0 个或更多空格)转换为逗号,每个逗号后面都有一个回车符,然后选择整个组并使用 Vim 内置的 = 缩进它。

此解决方案的一个已知缺点是包含多个模板参数的行(它也会在逗号处中断,而不仅仅是普通参数的逗号)。

【讨论】:

    【解决方案2】:

    您可以使用splitjoin

    SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree);
    

    在括号内或括号上,键入gS 进行拆分。你得到:

    SomeObject doSomething(firstType argumentOne,
        secondType argumentTwo,
        thirdType argumentThree);
    

    你也可以使用vim-argwrap

    【讨论】:

    • 刚刚安装了 argwrap - 太棒了! :)
    • 两者都安装了。相比之下,即使 splitjoin 也有更多贡献,但 argwrap 更好,因为它适用于所有文件类型。 splitjoin 仅适用于少数文件类型,并且在许多情况下无法换行。它依赖于太多特定的功能。我将 argwrap 映射到 gaw。它有一些错误,如果解决会比 splitjoin 好得多。
    【解决方案3】:

    我会将寄存器设置为预设宏。经过一些测试,我得到了以下结果:

    let @x="/\\w\\+ \\w\\+(\nf(_:s­\\(\\w\\+\\)\\@<=,/,\\r            /g\n"
    

    使用 vimrc 中的这一行,您可以通过执行宏 x:@x 将光标置于要格式化的行上方来格式化方法。它为缩进添加了 12 个空格,如下所示:

    |
    SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree);
    

    执行宏后:@x你得到

    SomeObject doSomething(firstType argumentOne,
                 secondType argumentTwo,
                 thirdType argumentThree);
    

    如果你在函数定义的行中,你可以做一个替换:

    :s\(\w\+\)\@,<=,/,\r            /g
    

    这很容易放在映射中:

    nmap <F4> :s/\(\w\+\)\@<=,/,\r            /g<CR>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      相关资源
      最近更新 更多