A while back I posted a tip about how to quickly comment out a block of lines in vim. Since then I’ve gotten even more lazy and found an even quicker way that involves much less effort on my part. I think this originally came from a vim tip that I CBA to find now, so I’m reposting here to spread the love.
First, add a couple functions to do the work:
" Comment out a visual block function CommentLines() execute ":s@^@".g:StartComment." @g" "execute ":s@^\\(\\s*\\)@\\1".g:StartComment." @g" execute ":s@$@ ".g:EndComment."@g" endfunction " Uncomment a visual block function UncommentLines() execute ":s@^".g:StartComment." @\@g" "execute ":s@^\\(\\s*\\)".g:StartComment." @\\1@g" execute ":s@ ".g:EndComment."$@@g" endfunction
You’ll notice that there is a line commented out in each function. The default way to comment is to comment starting at the beginning of the line. By uncommenting this line and commenting out the one above it, you can change this behavior so that the comments start at the first non-whitespace character on the line instead. I find the configuration above to be less annoying.
Next you’ll need to set the comment characters for the language you’re working in. My preferred way is to use autocmds to set these based on the current filetype.
" Set comment characters for common languages autocmd FileType python,sh,bash,zsh,ruby,perl let StartComment="#" | let EndComment="" autocmd FileType html let StartComment="<!--" | let EndComment="-->" autocmd FileType php,c,javascript let StartComment="//" | let EndComment="" autocmd FileType cpp let StartComment="/*" | let EndComment="*/" autocmd FileType vim let StartComment="\"" | let EndComment=""
That’s it! Optionally (do this, really it’s stupid not to), you can add some keymaps to quickly call our functions.
vmap <Leader>c :call CommentLines()<cr> vmap <Leader>u :call UncommentLines()<cr>
Now to use the functions, just select a visual block and hit your keymap. Voila!
Note: If you need anything more complex than what this tip provides, check out the NERD Commenter. Everything I’ve read about it suggest that it’s excellent.
2006-2009 rsontech.net