Vim (vimscript) get exact character under the cursor

前端 未结 3 1241
盖世英雄少女心
盖世英雄少女心 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:18
    nr2char(strgetchar(getline('.')[col('.') - 1:], 0))
    

    or

    strcharpart(getline('.')[col('.') - 1:], 0, 1)
    
    0 讨论(0)
  • 2020-12-31 06:34

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题