comment-dwim

Emacs の comment-dwim もどきを作ってみた。
何年も前からこれが欲しかったのだ。
AppendComment.vim と違って noet ならタブを入れる。
http://vimwiki.net/?scripts%2F8

" Emacs comment-dwim like commenging plugin
"

nnoremap <Esc>; :call <SID>CommentDwim()<CR>
inoremap <Esc>; <Esc>:call <SID>CommentDwim()<CR>

function! s:CommentDwim()
  if exists("b:CommentDwim_level")
    let level = b:CommentDwim_level
  elseif exists("g:CommentDwim_level")
    let level = g:CommentDwim_level
  else
    let level = 8
  endif

  if exists("b:commentSymbol")
    let symbol = b:commentSymbol
    let endSymbol = ""
  elseif &ft ==? "c" || &ft ==? "cpp" || &ft ==? "java" || &ft ==? "php"
    let symbol = "/*"
    let endSymbol = " */"
  elseif &ft ==? "lisp" || &ft ==? "scheme"
    let symbol = ";"
    let endSymbol = ""
  else
    let symbol = "#"
    let endSymbol = ""
  endif

  let line = getline(".")
  " blank line
  if line =~ '^\s*$'
    exe "normal! a".symbol."\<space>".endSymbol
    normal! ==$
    if endSymbol != ""
      exe "normal! ".(strlen(endSymbol)-1)."h"
      startinsert
    else
      startinsert!
    endif
    return
  endif

  let sts_save = &sts
  let &sts = &ts
  let idx = stridx(line, symbol)
  if idx < 0
    exe "normal! A".symbol."\<space>".endSymbol
  endif
  let line = getline(".")
  let idx = stridx(line, symbol)
  if idx - 1 > 0
    exe "normal! 0".(idx-1)."l"
  elseif idx == 0
    exe "normal! 0i\<tab>"
  else
    normal! 0
  endif

  if virtcol(".") < level * &tabstop
    while virtcol(".") < level * &tabstop
      exe "normal! a\<tab>"
    endwhile
  else
    while virtcol(".") > level * &tabstop && strpart(getline("."), col(".")-2, 1) =~ '\s'
      normal! xh
    endwhile
  endif

  let &sts = sts_save

  if endSymbol == ""
    startinsert!
  else
    exe "normal! ".(strlen(symbol)+2)."l"
    startinsert
  endif
endfunction