Vim Tips Wiki
Advertisement

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created May 4, 2012 · complexity basic · author Baliganikhil · version 7.0

Commenting and uncommenting multiple lines in Vim can be a little tricky. Here is a small snippet of code to show how you can do this. I have done this for just a few of languages. But you can extend this to any number as per your choice.

Script

In this piece of code, we try to get the extension of the file, and based on that, decide what kind of comment is to be applied.

Save the following in a file named vcomments.vim.

function! Comment()
  let ext = tolower(expand('%:e'))
  if ext == 'php' || ext == 'rb' || ext == 'sh' || ext == 'py'
    silent s/^/\#/
  elseif ext == 'js'
    silent s:^:\/\/:g
  elseif ext == 'vim'
    silent s:^:\":g
  endif
endfunction

function! Uncomment()
  let ext = tolower(expand('%:e'))
  if ext == 'php' || ext == 'rb' || ext == 'sh' || ext == 'py'
    silent s/^\#//
  elseif ext == 'js'
    silent s:^\/\/::g
  elseif ext == 'vim'
    silent s:^\"::g
  endif
endfunction

Once this is done, put the following in your vimrc:

source ~/vcomments.vim
map <C-a> :call Comment()<CR>
map <C-b> :call Uncomment()<CR>

The mappings use Ctrl-A to comment and Ctrl-B to uncomment. Replace these with any convenient keys.

To use it, just select the lines to comment by pressing V then moving the cursor up or down to select lines. Then, press Ctrl-A to comment. Similarly, you can uncomment them.

Comments

Related tips:

Thanks for the new tip. The above list shows tips that may be useful, or which may need fixing or merging. JohnBeckett 09:43, May 5, 2012 (UTC)


Thanks alot for this 2 functions, but a better way to identify which type of comment should be used could be:

let ext = &filetype

since this improves recognition of filetypes without extention like Makefiles, shellscripts or even vim files!

so the functions i use are:

map gc :call Comment()<CR>
map gC :call Uncomment()<CR>

function! Comment()
	let ft = &filetype
	if ft == 'php' || ft == 'ruby' || ft == 'sh' || ft == 'make' || ft == 'python' || ft == 'perl'
		silent s/^/\#/
	elseif ft == 'javascript' || ft == 'c' || ft == 'cpp' || ft == 'java'
		silent s:^:\/\/:g
	elseif ft == 'tex'
		silent s:^:%:g
	elseif ft == 'vim'
		silent s:^:\":g
	endif
endfunction

function! Uncomment()
	let ft = &filetype
	if ft == 'php' || ft == 'ruby' || ft == 'sh' || ft == 'make' || ft == 'python' || ft == 'perl'
		silent s/^\#//
	elseif ft == 'javascript' || ft == 'c' || ft == 'cpp' || ft == 'java'
		silent s:^\/\/::g
	elseif ft == 'tex'
		silent s:^%::g
	elseif ft == 'vim'
		silent s:^\"::g
	endif
endfunction

Ilendir 14:42, August 1, 2012 (UTC)

Advertisement