Vim (vimscript) get exact character under the cursor

Though I cannot reproduce the problem you're describing, there's another problem with your code: Because of the string indexing (and this is one of the uglier sides of Vimscript), it only works with single-byte characters, but will fail to capture chars like Ä or 𠔻 (depending on the encoding used). This is a better way of capturing the character under the cursor:

:echo matchstr(getline('.'), '\%' . col('.') . 'c.')

Edit: Since about Vim 7.4.1742, Vim has new strgetchar() and strcharpart() functions that work with character indexes, not byte addressing. This is helpful in many circumstances, but not here, because you still can only get the byte-index position of the cursor (or the screen column with virtcol(), but that's not the same as character index).


nr2char(strgetchar(getline('.')[col('.') - 1:], 0))

or

strcharpart(getline('.')[col('.') - 1:], 0, 1)

Tags:

Vim