1

The following is a set of autocommands used to prevent the cursor from move when you exit from Insert mode:

let CursorColumnI = 0
autocmd! InsertEnter  * let CursorColumnI = col('.')
autocmd! CursorMovedI * let CursorColumnI = col('.')
autocmd! InsertLeave  *
  \ if col('.') != CursorColumnI | call cursor(0, col('.')+1) | endif

(taken from Vim Wiki, edited by me)

I don't like that lines 2 and 3 are almost the same, so I would prefer to write the whole snippet like this:

let CursorColumnI = 0
autocmd! (InsertEnter || CursorMovedI) * let CursorColumnI = col('.')
autocmd! InsertLeave *
  \ if col('.') != CursorColumnI | call cursor(0, col('.')+1) | endif

... but this doesn't work.

Another thing that doesn't work is a comma:

let CursorColumnI = 0
autocmd! InsertEnter,CursorMovedI * let CursorColumnI = col('.')
autocmd! InsertLeave *
  \ if col('.') != CursorColumnI | call cursor(0, col('.')+1) | endif

(When you exit from Insert mode in which you entered by using a, the cursor still moves.)

Do autocommand events support ||, or maybe there is some workaround that works?

8
  • 2
    The expected syntax for events is indeed a comma-separated list. I think your last snippet should be good.
    – Biggybi
    Sep 12 at 9:30
  • @Biggybi I tested it. No, it doesn't work properly.
    – jsv
    Sep 12 at 9:33
  • 2
    Looks like you fight with vim "inconsistencies". Hopefully in a couple of years you change your mind. :)
    – Maxim Kim
    Sep 12 at 10:38
  • Do you get any error messages? If so, what are they?
    – Heptite
    Sep 12 at 19:17
  • @Heptite No, there are no error messages. The only error is that cursor moves.
    – jsv
    Sep 12 at 21:17
3

The answer is, basically you're going to have either "cursor crawl" to the left when using i then esc,which is Vim's default behavior, or "cursor crawl" to the right with a then esc with this script.

The reason for one or the other is that, while in insert mode, the cursor is considered to be "between" two characters (which is illustrated by the vertical bar the cursor becomes in gVim), but while in normal mode the cursor must be "on" a character. This is why Vi/Vim has both the i and a methods of entering insert mode.

With time most people get used to this and instinctively use i most of the time and a mostly in scenarios where the cursor is at the end of the line and the user wants to add to the end of the line instead of between the last and second to last characters of the line.

And, in fact, there's I to jump to the beginning of the line and enter insert mode, and A to jump to the end and append.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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