vim缩写和正则表达式

时间:2013-01-16 14:16:47

标签: regex vim abbreviation

在vim中,是否可以在缩写中使用正则表达式?例如,像

:iab \([0-9]\{-}\)nm \\SI{\1}{\\nano\\meter}

会将每个实例(例如'50nm')扩展为'\ SI {50} {\ nano \ meter}'。

2 个答案:

答案 0 :(得分:2)

你最好的选择是为自己写一个小帮手功能。点击全向完成或用户定义的完成(C-x C-u,请参阅:help 'cfu')是一个不错的选择。我在一把钥匙上勾画了一个常规函数给imap:

function! ExpandNanometers()
    let items = matchlist(expand('<cword>'), '\v(\d+)nm')
    if len(items) == 0
        return 
    endif
    let modified = '\SI{' . items[1] . '}{\nano\meter}'
    exec "normal! ciw" . modified
endf
imap <C-l> <C-o>:call ExpandNanometers()<CR>

也许不是最好的代码。在插入模式C-l上绑定,如果光标位于单词上或直接位于单词后面,它会将50nm等单词替换为所需单词。

答案 1 :(得分:0)

我想将此添加为对前一个答案的评论,但显然我不能直到50个代表。我也知道这种方式太晚了,但仅供参考:

如果键映射是可接受的(按照前面的答案),肯定会像

那样
imap <silent> <leader>obscure-key-of-choice <Esc>:%s/\v(\d+)nm/\\SI{\1}{\\nano\\meter}/g<CR>``i

(即具有所需模式的整个文件的全局替换) 会更容易维护吗?我喜欢避免vimscript以便于.vimrc的可读性/维护!显然,你用你选择的模糊键替换obscure-key-of-choice。您只需要在输入所有文本后再执行一次,因此最好将其他键保存为更常规的有用绑定!

快捷方式取代了

之类的内容
50nm blabla 73nm your-interesting-science-here 89nm
... some new lines...
we love nanometers nm! 34nm and finally 18nm

类似

\SI{50}{\nano\meter} blabla \SI{73}{\nano\meter} your-interesting-science-here \SI{89}{\nano\meter}
... some new lines...
we love nanometers nm! \SI{34}{\nano\meter} and finally \SI{18}{\nano\meter}