コメントアウトをトグルするvimスクリプトを書いた

これは何?
,cで選択行(or現在行)のコメントアウトをトグルするvimスクリプトです

2009/6/11追記
基本的に、NERD_commenterの下位互換です
vimscriptの練習用に書いたものでもあるので、消さずに残しておきますが、NERD_commenterの使用を推奨します

使い方
こんな場合に、上の2行を選択して、,c で

 123
 456



こんな風にコメントアウトされます(例はrubyの場合)

 # 123
 # 456



もう一度、,cを押せば、コメントが解除されます



NERD_commenterとどう違うの?


行コメントをトグルします(NERD_commenterは/* */)

2009/6/11追記NERD_commenterも行コメント対応してました…。



あと、デフォルトでNERD_commenterがサポートしてないファイルタイプを主に扱ってます

(今のところ、prel,ruby,sh,yami,javascript,htmlに対応してます)

2009/6/11追記:こっちも、NERD_commenterのでも、.vimrcに以下の設定で対応可能(HTML,XMLの場合)

:autocmd Filetype xml,html set commentstring=<!--%s-->



ソース


.vimrcの一番下にでもコピペしてください


"---------------------------------------------------------------------
" コメントトグル {{{
" 元ネタ:http://d.hatena.ne.jp/cooldaemon/20070126/1169795080
"---------------------------------------------------------------------
nmap ,c <Plug>CommentOut
nnoremap <Plug>CommentOut :<C-u>call CommentOut()<Return>

vmap ,c <Plug>CommentOutV
vnoremap <Plug>CommentOutV :call CommentOut()<Return>

function! CommentOut()
	" comment type # 
	if &l:filetype ==# 'perl' || &l:filetype ==# 'ruby' || &l:filetype ==# 'sh' || &l:filetype ==# 'yaml'
		if getline('.') =~ '^\s*#'
			s/^\(\s*\)#\+ \?/\1/
		else	
			s/^\s*/\0# /
		endif

	" comment type //
	elseif &l:filetype ==# 'javascript'
		if getline('.') =~ '^\s*\/\/'
			s/^\(\s*\)\/\/\+ \?/\1/
		else
			s/^\s*/\0\/\/ /
		endif

	" comment type "
	elseif &l:filetype ==# 'vim'
		if getline('.') =~ '^\s*"'
			s/^\(\s*\)"\+ \?/\1/
		else	
			s/^\s*/\0" /
		endif

	" comment type <!-- - ->
	elseif &l:filetype ==# 'html' || &l:filetype ==# 'xhtml' || &l:filetype ==# 'tt2html'
		if getline('.') =~ '<!--.*-->'
			s/^\(\s*\)<!--\s\(.*\)\s-->/\1\2/
		else
			s/^\(\s*\)\(.*\)$/\1<!-- \2 -->/
		endif

	" other
	else
		if getline('.') =~ '^\s*\/\/'
			s/^\(\s*\)\/\/\+ \?/\1/
		else
			s/^\s*/\0\/\/ /
		endif
	endif
	:nohlsearch
endf
"}}}




謝辞


以下のサイトを参考に作成しました。感謝!