在搜索和替换命令中使用变量和表达式

时间:2011-09-21 08:36:31

标签: vim vi

我正在尝试设置一些键映射/宏来注释/取消注释我的.vimrc中的文本块,但我无法使其工作。

我定义了一些变量:

let g:comment_id='~'
autocmd BufRead,BufNewFile *.c,*.cpp,*.cxx,*.h,*.hpp,*.hxx,*.ipp let b:comment_open='//'
autocmd BufRead,BufNewFile *.f90,*.F90 let b:comment_open='!'

然后我尝试使用不同的方法来使用它们,但每次失败时都会:

noremap <silent> ,cc :s/^/<C-R>=(b:comment_open.g:comment_id)/<CR>:nohlsearch<CR>
noremap <silent> ,uc :s/<C-R>=(b:comment_open.g:comment_id)//<CR>:nohlsearch<CR>

- &GT; E15:表达式无效:/, E15:表达式无效:(b:comment_open.g:comment_id)//

noremap <silent> ,cc :s/^/<C-R>=(b:comment_open.g:comment_id)<CR>/<CR>:nohlsearch<CR>
noremap <silent> ,uc :s/<C-R>=(b:comment_open.g:comment_id)<CR>//<CR>:nohlsearch<CR>

- &GT; E488:尾随字符

noremap <silent> ,cc :s/^/\=(b:comment_open.g:comment_id)/<CR>:nohlsearch<CR>
noremap <silent> ,uc :s/\=(b:comment_open.g:comment_id)//<CR>:nohlsearch<CR>

- &GT; cc:好的, UC: E64:\ =什么都没有, E476:无效命令

事实上,我无法理解'C-R'和\ =是如何工作和意味着......

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

使用:

nnoremap <silent> ,cc :s/^/\=b:comment_open.g:comment_id/<CR>:nohlsearch<CR>
nnoremap <silent> ,uc :s@\V<c-r>=escape(b:comment_open.g:comment_id,'\@')<cr>@@<cr>:nohlsearch<cr>

参考::help sub-replace-expression

在模式中有必要转为非常陌生以逃避所有特殊字符,即使你需要同时转义分隔符和反斜杠。