How do I get the character under the cursor from a Vim script?

You can use the getline() function and use string index [] to get the character:

    :echo getline(".")[col(".") - 1]

In the above command, getline(“.”) returns the text in the current line. The indexing of the string starts at zero, and you can get a single character in a string by its index with the “string[index]” notation. The col(“.”) returns the column of the cursor position; the adjustment is to get the right character of the string. However, this does NOT work with multibyte characters as this command only returns the byte index. Alternatively, you can use the following sequence of commands to get the character under the cursor:

    normal! vy

    let ch=@"

Note, that the above commands will change the ‘< and ‘> marks. For more information, read: getline() col() expr-[]

Comments (1)


Pepsh Pepshinsky

Let’s see you to :help viminfo-file-name (option -i) :set viminfofile=NONE


Speak Your Mind