If you want to add a newline without the cursor jumping around you can:
(Written in Lua for Neovim, but you could convert it to Vim script.)
vim.keymap.set("n", "<CR>", "mao<esc>0<S-d>`a<cmd>delmarks a<cr>", { desc = "Add new line below" })
vim.keymap.set("n", "<S-CR>", "maO<esc>0<S-d>`a<cmd>delmarks a<cr>", { desc = "Add new line above" })
This uses marks to preserve your line and column position. And deletes any characters that are automatically added when opening a new line (such as comment characters).
ma
: mark current cursor position.
o
: open a new line and enter insert mode.
<esc>
: enter normal mode.
0<S-d>
: go to the beginning of the line and empty it.
`a
: go to the original marked cursor location.
<cmd>delmarks a<cr>
: delete the mark.
Note that if you want to avoid mapping the carriage return in non-normal windows (e.g. hitting enter in the quickfix list should still take you to the file) you can:
-- Set keymap for normal windows only (e.g. not quickfix)
local normal_window_keymap = function(mode, lhs, rhs, opts)
local merged_opts = vim.tbl_extend("force", { noremap = true, expr = true }, opts or {})
vim.keymap.set(mode, lhs, function()
local buftype = vim.fn.win_gettype()
return buftype == "" and rhs or lhs
end, merged_opts)
end
-- Open new line (like o/O) without moving the cursor, without entering insert mode and removing any characters
normal_window_keymap("n", "<CR>", "mao<esc>0<S-d>`a<cmd>delmarks a<cr>", { desc = "Add new line below" })
normal_window_keymap("n", "<S-CR>", "maO<esc>0<S-d>`a<cmd>delmarks a<cr>", { desc = "Add new line above" })
$TERM
(if *nix)? – Madsenecho $TERM
->xterm
Why? – Grasshoppermap <CR> o<Esc>
here. – Madsenmap <CR> o<Esc>
work. But, how mapO<Esc>
? . I'm sorry by my bad english – Grasshopper