如何在 Vim 中格式化 Ruby 参数/哈希?

jor*_*ver 0 vim ruby

我希望能够在 Vim 中轻松格式化 Ruby 代码。

如果我有一个带有哈希参数方法

foobar(foo: "FOO", bar: "BAR")
Run Code Online (Sandbox Code Playgroud)

我怎样才能把它变成

foobar(
    foo: "FOO",
    bar: "BAR"
)
Run Code Online (Sandbox Code Playgroud)

或者,如果我有一个正常的哈希

foobar = { foo: "FOO", bar: "BAR" }
Run Code Online (Sandbox Code Playgroud)

成这个

foobar = {
    foo: "FOO",
    bar: "BAR"
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能用 Vim 实现这一点?我需要某种插件吗?

rom*_*inl 6

以下宏适用于两种情况:

qq             " start recording in register q
$              " jump to the last character on the line, a ) or a }
v%             " select from here to the opening ( or {, inclusive
loh            " shrink the selection
c              " remove selection and enter insert mode
<CR><CR><Up>   " open the (){} and put the cursor in between
<C-r>"         " insert the content of default register
<Esc>          " go back to normal mode
:s/,/,\r/g<CR> " replace every , with itself followed by a newline
:'[,']norm ==  " format the whole thing
q              " stop recording
Run Code Online (Sandbox Code Playgroud)

@qfoobar(foo: "FOO", bar: "BAR")获得:

foobar(
    foo: "FOO",
    bar: "BAR"
)
Run Code Online (Sandbox Code Playgroud)

foobar = { foo: "FOO", bar: "BAR" }获得:

foobar = {
    foo: "FOO",
    bar: "BAR"
}
Run Code Online (Sandbox Code Playgroud)

编辑

虽然这个宏最有可能跨会话保存,但很容易覆盖它。幸运的是,很容易将其转换为映射并将其保存在您的~/.vimrc:

nnoremap <F6> $v%lohc<CR><CR><Up><C-r>"<Esc>:s/,/,\r/g<CR>:'[,']norm ==<CR>
Run Code Online (Sandbox Code Playgroud)