将vim变量插入文本以注释快捷方式

时间:2010-10-06 05:33:28

标签: vim variables comments autocmd

我有一个简单的目标:映射Ctrl-C,这个命令我不认为我曾经用来杀死vim,在一行的开头自动插入正确的字符以注释掉该行根据文件的文件类型。

我想我可以使用自动命令识别文件类型,并在文件打开时将vim变量设置为正确的注释字符。所以我尝试了类似的东西:

" Control C, which is NEVER used. Now comments out lines!
autocmd BufNewFile,BufRead *.c let CommentChar = "//"
autocmd BufNewFile,BufRead *.py let CommentChar = "#"
map <C-C> mwI:echo &CommentChar<Esc>`wll

该地图标记我当前的位置,在插入模式下转到行的开头,在此处回显注释字符,进入命令模式,返回到设置标记,并使用两个字符来弥补插入的注释字符(假设C样式注释)。

斜体部分是我遇到麻烦的部分;它只是作为一个占位符来代表我想做的事情。你能帮我弄清楚如何实现这个目标吗?如果您使用strlen(CommentChar)向右移动正确数量的空格,则可获得奖励积分! vim-master的额外奖励积分包括如果您处于视觉模式时如何进行块式评论!!

我在vim脚本方面还是比较新的;我的.vimrc是98行长,所以如果你能解释你提供的任何答案,请帮助我!感谢。

2 个答案:

答案 0 :(得分:5)

您可以在此处使用<C-r>

noremap <C-c> mwI<C-r>=g:CommentChar<CR><Esc>`wll

请参阅:h i_CTRL-R

另请查看NERDCommenter插件,其映射将如下所示:

" By default, NERDCommenter uses /* ... */ comments for c code.
" Make it use // instead
let NERD_c_alt_style=1
noremap <C-c> :call NERDComment(0, "norm")<CR>

您不必自己定义评论字符。

答案 1 :(得分:2)

我在某些时候从vim提示维基上取下它并自己使用它。唯一的缺点是它出于某种原因在线的末端添加了一个空格,可能是我忽略的一小部分。

" Set comment characters for common languages
autocmd FileType python,sh,bash,zsh,ruby,perl,muttrc let StartComment="#" | let EndComment=""
autocmd FileType html let StartComment="<!--" | let EndComment="-->"
autocmd FileType php,cpp,javascript let StartComment="//" | let EndComment=""
autocmd FileType c,css let StartComment="/*" | let EndComment="*/"
autocmd FileType vim let StartComment="\"" | let EndComment=""
autocmd FileType ini let StartComment=";" | let EndComment=""

" Toggle comments on a visual block
function! CommentLines()
    try
        execute ":s@^".g:StartComment." @\@g"
        execute ":s@ ".g:EndComment."$@@g"
    catch
        execute ":s@^@".g:StartComment." @g"
        execute ":s@$@ ".g:EndComment."@g"
    endtry
endfunction

" Comment conveniently
vmap <Leader>c :call CommentLines()<CR>
相关问题