Created
March 3, 2014 05:07
-
-
Save sooop/9318742 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" toggle comment line | |
function! SetCommentPrefix() | |
let s:comment_prefix = "#" | |
if &filetype == "vim" | |
" for vim, inline comment start with \" | |
let s:comment_prefix = "\"" | |
elseif &filetype ==? "c" || &filetype ==? "objc" || &filetype ==? "cpp" | |
let s:comment_prefix = "//" | |
endif | |
endfunction | |
function! CommentLine(line_number) | |
call SetCommentPrefix() | |
" remember current cursor position | |
let cpos = getpos(".") | |
" move to seletced line | |
call setpos(".", [0, a:line_number, 0, 0]) | |
" just insert comment prefix character at the front of given line | |
exec "normal! I".s:comment_prefix | |
"restore cursor position | |
call setpos(".", cpos) | |
endfunction | |
function! UncommentLine(line_number) | |
call SetCommentPrefix() | |
" remember current cursor position | |
let cpos = getpos(".") | |
"move to selected line | |
call setpos(".", [0, a:line_number, 0, 0]) | |
" remove comment prefix charactor | |
exec ".s/".escape(s:comment_prefix, s:comment_prefix[0])."//" | |
" restore cursor position | |
call setpos(".", cpos) | |
endfunction | |
function! CheckIsComment(line_number) | |
call SetCommentPrefix() | |
" check the line for given line number is comment | |
let sl = getline(a:line_number) | |
let c = 0 | |
while c < strlen(sl) | |
let d = c + strlen(s:comment_prefix) - 1 | |
"sl[c] is space or tabe? | |
if " \t" =~ sl[c] | |
" ignore indentation | |
" pass | |
elseif sl[(c):(d)] == s:comment_prefix | |
return 1 | |
else | |
return 0 | |
endif | |
let c += 1 | |
endwhile | |
return 0 | |
endfunction | |
function! ToggleCommentLine() | |
let cl = line(".") | |
if CheckIsComment(cl) | |
call UncommentLine(cl) | |
else | |
call CommentLine(cl) | |
endif | |
endfunction | |
function! ToggleCommentRange() | |
let line_begin = line("'<") | |
let line_end = line("'>") | |
" decide mode with first line in selection | |
let mode_ = CheckIsComment(line_begin) | |
let cpos = getpos(".") | |
let i = line_begin | |
while i < line_end + 1 | |
if mode_ | |
call UncommentLine(i) | |
else | |
call CommentLine(i) | |
endif | |
let i+=1 | |
endwhile | |
endfunction | |
nnoremap <leader>\ :call ToggleCommentLine()<cr> | |
vnoremap <leader>\ <esc> :call ToggleCommentRange()<cr> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment