I am trying to use wordcount().cursor_chars to determine the character offset of the cursor in the buffer – but I am getting off-by-one errors.

The docs for wordcount() say that cursor_chars is the "Number of chars before cursor position (not in Visual mode)".

However if you:

  • open a new buffer
  • :autocmd CursorMoved,CursorMovedI * echo wordcount()
  • insert abc
  • return to normal mode and place the cursor on the a

The echoed wordcount().cursor_chars is 1. However I would expect this to be 0 as there are no characters before the cursor. Is the documentation wrong?

Related, pressing A to go into insert mode with the cursor after the c gives a cursor offset of 4 in a file with unix EOLs and 5 in a file with dos EOLs. Is that because the cursor is actually on the last character of the EOL regardless of whether the EOL is one or two characters?

1 Answer 1


I think you are correct. The documentation is not very clear on that, but if you do start vim --clean -c ':set ls=2 stl=%{wordcount().cursor_chars}' you will see:

  • In an empty buffer, that statusline will be zero
  • as soon as you got to insert mode and a letter, the statusline will switch to 2 (note the cursor is technically after the letter)
  • if you go back into normal mode, the statusline will be 1

I think this means, that the cursor_chars returns the number of characters up to and including the position of the cursor.

If you press A from normal mode to append a character into a buffer with the single line abc, I think technically vim treats the current position as a new character at the cursor position, so it increments it already to 4. That would also explain, why you see a 1 after entering a.

Disclaimer: I have not verified it in the source, just how I would explain what you noticed.

  • It looks like we agree. Additionally, vim --clean -c ':set ff=dos ls=2 stl=%{wordcount().cursor_chars}' shows that when inserting/appending at the end of the line in a dos file, vim treats the current position as the end of the two-character EOL (\r\n). Sep 21, 2018 at 8: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.