function! FortranCommentSelection() range
let commentString = "!"
let cl = a:firstline
let ind = 1000 " I hope nobody use so long lines! :)
" Look for smallest indent
while (cl <= a:lastline)
if strlen(getline(cl))
let cind = indent(cl)
let ind = ((ind < cind) ? ind : cind)
endif
let cl = cl + 1
endwhile
if (ind == 1000)
let ind = 1
else
let ind = ind + 1
endif
let cl = a:firstline
execute ":".cl
" Insert commentString in each non-empty line, in column ind
while (cl <= a:lastline)
if strlen(getline(cl))
execute "normal ".ind."|i".commentString
endif
execute "normal <Down>"
let cl = cl + 1
endwhile
endfunction
function! FortranUncommentSelection() range
" commentString could be different than the one from CommentSelection()
" For example, this could be "# \="
let commentString = "!"
let commentString1 = "C"
let commentString2 = "c"
let cl = a:firstline
while (cl <= a:lastline)
let ul = substitute(getline(cl),
"\(\s*\)".commentString."\(.*\)$", "\1\2", "")
let ul1 = substitute(getline(cl),
"^".commentString1."\(.*\)$", "\1", "")
let ul2 = substitute(getline(cl1),
"^".commentString2."\(.*\)$", "\1", "")
call setline(cl, ul2)
let cl = cl + 1
endwhile
endfunction
map ]C :call FortranCommentSelection()<CR>
vmap ]C :call FortranCommentSelection()<CR>
map ]U :call FortranUncommentSelection()<CR>
vmap ]U :call FortranUncommentSelection()<CR>
这样,按]C给选择的行增加注释,按]U给选择的行去掉注释
==========================================================================
后来又发现其实用NERD_commenter更好。只需要在.vimrc里面设置
filetype plugin on
filetype plugin indent on
之后,按,cc设置注释,按,cu取消注释