Tip #355: Comment Lines according to a given filetype
tip karma |
Rating 4/5, Viewed by 1744
|
created: |
|
October 30, 2002 8:12 |
|
complexity: |
|
intermediate |
author: |
|
Luis Mondesi |
|
as of Vim: |
|
6.0 |
There is probably an easier way to do this, but, if I cannot find an easy solution for a given problem, I just device 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 this lines in your .vimrc file:
" -------- vimrc ---------
" 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>
" ------- end vimrc -------
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 ... again if you don't already have one. Vim needs to be compiled with filetype detection
support for this to work. You have been warned.):
-------- filetype.vim ---------
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
------ end filetype.vim -------
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.
<<Find in files - recursively (NOT :grep!). Only for unix clones. |
Quick yank and paste >>
Additional Notes
|