VimL 獲取游標所在行前、後的字串(主要為了【相容漢字】)
阿新 • • 發佈:2021-08-25
因為漢字不是佔一個位元組位,而 VimL 對這塊處理,還是有不少細節要注意的。
比如 stridx 獲取的是位元組位置,而 strridx 是字元位置
strlen 是位元組數, strchars 是字元數
- 獲取游標前字串(不含游標)
strpart(getline('.'), 0, col('.')-1)
- 獲取游標前字串(含游標)
strpart(getline('.'), 0, col('.')-1) . strcharpart(strpart(str,col('.')-1),0,1)
- 獲取游標後字串(不含游標)
strcharpart(getline('.'),strchars(strpart(getline('.'),0,col('.')-1))+1)
- 獲取游標後字串(含游標)
strpart(getline('.'), col('.')-1)
- 獲取當前游標字元
strcharpart(strpart(getline('.'),col('.')-1),0,1)
為了方便以後獲取,我還寫了 ultisnips
本部落格的AutoHotkey版本是V2-a103,附下載地址和簡易使用方法snippet strbb "游標前字串(不含游標)" w strpart(${1:getline('.')}, 0, ${2:col('.')}-1) endsnippet snippet straa "游標後字串(不含游標)" w strcharpart(${1:getline('.')},strchars(strpart($1,0,${2:col('.')}-1))+1) endsnippet #考慮游標是漢字的情況 snippet charc "char at col" w strcharpart(strpart(${1:getline('.')},${2:col('.')}-1),0,1) endsnippet snippet strb "游標前字串(含游標)" w strpart(${1:getline('.')},0,${2:col('.')}-1) . strcharpart(strpart($1,$2-1),0,1) endsnippet snippet stra "游標後字串(含游標)" w strpart(${1:getline('.')}, ${2:col('.')-1}) endsnippet