我有一个简单的目标:Map Ctrl-C,一个我认为我从未杀死VIM的命令,可以在行的开头自动插入正确的字符,以根据该行评论该行文件的Filetype。

我认为我可以使用autoCommand识别文件类型,并在文件打开时将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行,因此,如果您可以通过解释您提供的任何答案,请帮助我!谢谢。

有帮助吗?

解决方案

您可以使用 <C-r> 这里:

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

:h i_CTRL-R.

也看 Nerdcommenter 插件,带有IT映射看起来像这样:

" 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>

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

其他提示

我在某个时候将其从VIM Tips Wiki中摘下来,然后自己使用。唯一的缺点是,由于某种原因,它在行末端增加了一个空间,可能是我忽略的小东西。

" 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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top