我想到了一个简单的方法,可以在我的 .vimrc 文件中添加一些内容,这个方法非常有效,并且可以轻松地进行扩展。你只需要将新的文件类型添加到 comment_map 中,并设置它的注释标识符。
我已经为 normal 和 visual 模式添加了映射,但你可以将其重新映射到任何你喜欢的键位上。我更喜欢使用“切换”样式的函数,而不是多个映射等复杂的方式。
let s:comment_map = {
\ "c": '\/\/',
\ "cpp": '\/\/',
\ "go": '\/\/',
\ "java": '\/\/',
\ "javascript": '\/\/',
\ "lua": '--',
\ "scala": '\/\/',
\ "php": '\/\/',
\ "python": '#',
\ "ruby": '#',
\ "rust": '\/\/',
\ "sh": '#',
\ "desktop": '#',
\ "fstab": '#',
\ "conf": '#',
\ "profile": '#',
\ "bashrc": '#',
\ "bash_profile": '#',
\ "mail": '>',
\ "eml": '>',
\ "bat": 'REM',
\ "ahk": ';',
\ "vim": '"',
\ "tex": '%',
\ }
function! ToggleComment()
if has_key(s:comment_map, &filetype)
let comment_leader = s:comment_map[&filetype]
if getline('.') =~ "^\\s*" . comment_leader . " "
" Uncomment the line
execute "silent s/^\\(\\s*\\)" . comment_leader . " /\\1/"
else
if getline('.') =~ "^\\s*" . comment_leader
" Uncomment the line
execute "silent s/^\\(\\s*\\)" . comment_leader . "/\\1/"
else
" Comment the line
execute "silent s/^\\(\\s*\\)/\\1" . comment_leader . " /"
end
end
else
echo "No comment leader found for filetype"
end
endfunction
nnoremap <leader><Space> :call ToggleComment()<cr>
vnoremap <leader><Space> :call ToggleComment()<cr>
注意:
我没有使用任何回调或挂钩到文件类型/加载,因为我发现它们会比
.vimrc
静态函数/映射慢下Vim的启动,但这只是我的个人偏好。我还试图保持简单和高效。如果您使用自动命令,您需要确保将它们放在自动命令组中,否则回调会被添加到每个文件类型多次加载,并导致大量性能降低。