Vim (vimscript) get exact character under the cursor

前端 未结 3 1242
盖世英雄少女心
盖世英雄少女心 2020-12-31 05:52

I am getting the character under the cursor in vimscript the following way:

getline(\'.\')[col(\'.\')-1] 

It works exactly like it should,

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 06:36

    Another way to get the character index under cursor that deal with both ASCII and non-ASCII characters is the like the following:

    function! CharAtIdx(str, idx) abort                                       
      " Get char at idx from str. Note that this is based on character index  
      " instead of the byte index.                                            
      return strcharpart(a:str, a:idx, 1)                                     
    endfunction
                                                                              
    function! CursorCharIdx() abort                                           
      " A more concise way to get character index under cursor.               
      let cursor_byte_idx = col('.')                                          
      if cursor_byte_idx == 1                        
        return 0                      
      endif                                                                   
                                 
      let pre_cursor_text = getline('.')[:col('.')-2]                         
      return strchars(pre_cursor_text)                                        
    endfunction                                                               
    

    Then if you want to get char under cursor, use the following command:

    let cur_char_idx = CursorCharIdx()
    let cur_char = CharAtIdx(getline('.'), cur_char_idx)
    

    See also this post on how to get pre-cursor char.

提交回复
热议问题