Vim Tips Wiki
Register
Advertisement

Duplicate tip

This tip is very similar to the following:

These tips need to be merged – see the merge guidelines.

Tip 660 Printable Monobook Previous Next

created 2004 · complexity intermediate · author SmartDen/Firelex · version 5.7


This code snippet is a part of a vimrc file to set comments in various filetypes. The function CommentIt() decides itself, according to the current file's type which variant of comments to use.

This function should be called with autocmd BufEnter * call CommentIt() somewhere after its declaration to be invoked every time the user enters a new buffer.

function CommentIt ()
  if &filetype == "vim"
    vmap +# :s/^/"/<CR>
    vmap -# :s/^"//<CR>
  elseif &filetype == "tcl"
    vmap +# :s/^/#/<CR>
    vmap -# :s/^#//<CR>
  elseif &filetype == "c"
    vmap +# I/*<Esc>gv<End><Esc>a*/<Esc>
    vmap -# I<Esc>2xgv$<Esc>h2x<Esc>
  elseif &filetype == "cpp"
    vmap +# A<End><CR><Esc>gv:s/^/ *<CR>gvI<Esc>ko<Home>/*<Esc>gvA<Esc>ji */
    vmap -# :s/^..//<CR>gvI<Esc>ddgvA<Esc>dd
  elseif &filetype == "dosbatch"
    vmap +# :s/^/rem /<CR>
    vmap -# :s/^rem //<CR>
  endif
endfunction
"...
autocmd BufEnter * call CommentIt ()

Comments[]

Better yet, try script#23.


You can also put filetyp depending stuff in your local syntax files, e.g.

$HOME/vimfiles/after/syntax/tcl.vim (on Windows)

Not {rtp}/after/syntax/, use {rtp}/ftplugin/. This have nothing to do with syntax files.

I (also) recommend EnhancedCommentify.


Advertisement