Comment Lines according to a given filetype
From Vim Tips Wiki
Tip 355 Previous Tip • Next Tip
Created: October 30, 2002 Complexity: intermediate Author: Luis Mondesi Minimum version: 6.0 Karma: 8/6 Imported from: Tip#355
There is probably an easier way to do this, but, if I cannot find an easy solution for a given problem, I just devise one that works for the meantime -- which usually becomes permanent.
This function comments out lines according to file type. So if a file is .sh, it uses # to comment lines. And if a file is type .c it will start the comments with /* and end them with */.
Put these lines in your vimrc file:
" comment out highlighted lines according to file type " put a line like the following in your ~/.vim/filetype.vim file " and remember to turn on filetype detection: filetype on " au! BufRead,BufNewFile *.sh,*.tcl,*.php,*.pl let Comment="#" " if the comment character for a given filetype happens to be @ " then use let Comment="\@" to avoid problems... fun CommentLines() "let Comment="#" " shell, tcl, php, perl exe ":s@^@".g:Comment."@g" exe ":s@$@".g:EndComment."@g" endfun " map visual mode keycombo 'co' to this function vmap co :call CommentLines()<CR>
Now create a ~/.vim/filetype.vim file if you don't have one and add things like these to it Remember to put a line
:filetype on
in your vimrc file, if you don't already have one. Vim needs to be compiled with filetype detection support for this to work.
if exists("did_load_filetypes")
finish
endif
augroup filetypedetect
au! BufRead,BufNewFile *.inc,*.ihtml,*.html,*.tpl,*.class set filetype=php
\ | let Comment="<!-- " | let EndComment=" -->"
au! BufRead,BufNewFile *.sh,*.pl,*.tcl let Comment="#" | let EndComment=""
au! BufRead,BufNewFile *.js set filetype=html | let Comment="//" | let EndComment=""
au! BufRead,BufNewFile *.cc,*.php,*.cxx let Comment="//" | let EndComment=""
au! BufRead,BufNewFile *.c,*.h let Comment="/*" | let EndComment="*/"
augroup END
All set, now whenever you are editing a file of those you have defined in your filetype.vim script, you can just go into Visual mode, highlight what you want to comment out, and type "co". Simple.
[edit] See also
- EnhancedCommentify: script#23
- ToggleCommentify: script#4
- .... -> Search Vim Scripts
[edit] Comments
I was used to using 'boxes' as an external filter to comment/decomment, but pushing to the program and back is more 'expensive' then using a simple script, but boxes really is better then EnhancedCommentify.vim (at least I haven't found a way yet to make it behave just like I want it to.).
But I would prefer a maintained thing any day.
