1

The default behaviour of the o and O when prepended with a count is to keep the cursor always at the bottom.

I'm wondering if there's a native way to get the cursor at the top.

The way I'm doing this for this example is:

5O<Esc>4ki

Example:

Starting from this:

line 1 qux [here is the cursor in `normal` mode]
line 2 foo
line 3 bar

Get to this (added 5 lines above):

line 1 [here is the cursor in `insert` mode]
line 2
line 3
line 4
line 5 
line 6 qux
line 7 foo
line 8 bar

1 Answer 1

3

Counting is not fun, so an immediate improvement would be to use :help '[ instead of 4k. I am not sure if you can do better without some kind of mapping:

:nnoremap gO O<Esc>'[i

where gO does the full dance for you.

--- Rest of the original answer ---

:nnoremap <expr> gO '<Cmd>normal ' .. v:count1 .. 'O<CR>`[i'
  • :help <expr> makes Vim evaluate the RHS of the mapping at runtime.
  • :help <Cmd> is the new :help c_ctrl-u.
  • :help v:count1 is the count we gave to our mapping, how many empty lines we want to add.
  • normal 5O<CR>`[i is the actual command executed for a count of 5.
  • 5O<CR> opens 5 lines above the current line, leaving the cursor on the last line inserted.
  • `[ moves the cursor to the first line of the last change, therefore on the first inserted line.
  • i, well… enters insert mode.

I can think of at least three other sequences of intermediate steps to obtain the same result but it always ends with a custom mapping so, there.

3
  • Why the need for <Cmd>normal (without bang?)? Wouldn't nnoremap <expr> gO v:count1 .. 'O<esc>''[i' work too? (Change quoted apostrophe to backtick for marks as desired; getting nested backticks in a comment is hard.)
    – D. Ben Knoble
    Commented Jun 27, 2023 at 13:33
  • It wouldn't, but :nnoremap gO O<Esc>`[i would, actually, which is much simpler than my over-engineered solution.
    – romainl
    Commented Jun 27, 2023 at 14:17
  • Huh, not sure why it wouldn't work, but glad it simplified :)
    – D. Ben Knoble
    Commented Jun 27, 2023 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.