在Vim中插入两行新的空行?

5

有没有可能用 Vim 命令完成这个操作?

[] = 光标普通模式

[ = 光标插入模式

修改前

Text []

之后

Text

[

之前

Text []

之后

[

Text

这与一个常见的问题有关:Vim命令在正常模式下插入空行 - Peter Rincker
3个回答

11

我已经改变了o/O[count]行为,并采用以下映射。我认为这样做可以实现你想要的效果:

" o/O                   Start insert mode with [count] blank lines.
"                       The default behavior repeats the insertion [count]
"                       times, which is not so useful.
function! s:NewLineInsertExpr( isUndoCount, command )
    if ! v:count
        return a:command
    endif

    let l:reverse = { 'o': 'O', 'O' : 'o' }
    " First insert a temporary '$' marker at the next line (which is necessary
    " to keep the indent from the current line), then insert <count> empty lines
    " in between. Finally, go back to the previously inserted temporary '$' and
    " enter insert mode by substituting this character.
    " Note: <C-\><C-n> prevents a move back into insert mode when triggered via
    " |i_CTRL-O|.
    return (a:isUndoCount && v:count ? "\<C-\>\<C-n>" : '') .
    \   a:command . "$\<Esc>m`" .
    \   v:count . l:reverse[a:command] . "\<Esc>" .
    \   'g``"_s'
endfunction
nnoremap <silent> <expr> o <SID>NewLineInsertExpr(1, 'o')
nnoremap <silent> <expr> O <SID>NewLineInsertExpr(1, 'O')

6
这两个映射有帮助吗?
nnoremap <leader>O O<ESC>O
nnoremap <leader>o o<cr>

通过按下<leader>O,第一个命令会在当前行上方添加两行空行,并将您带入插入模式。第二个命令通过按下<leader>o,会在当前行下方添加两行。


好的,谢谢。我只是好奇为什么Vim中没有像2o或2O这样的东西。 - alexchenco
3
@alexchenco,确实有2o和2O,但它们的作用不是你期望的那样。按下2o或2O,然后按<esc>键查看更改。 - Kent

0
如果有人想要在Neovim中使用Lua的解决方案:
local new_lines = function(command, opposite)
    if vim.v.count <= 1 then
        return command
    end

    return ":<C-u><CR>" .. command .. ".<Esc>m`" .. vim.v.count - 1 .. opposite .. "<Esc>g``s"
end

vim.api.nvim_set_keymap("n", "o", function() return new_lines("o", "O") end, { noremap = true, silent = true, expr = true })
vim.api.nvim_set_keymap("n", "O", function() return new_lines("O", "o") end, { noremap = true, silent = true, expr = true })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接