Skip to content

Instantly share code, notes, and snippets.

@voyeg3r
Last active March 24, 2018 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voyeg3r/1c589b685e9568125038d4d4035af656 to your computer and use it in GitHub Desktop.
Save voyeg3r/1c589b685e9568125038d4d4035af656 to your computer and use it in GitHub Desktop.
" Reference: https://stackoverflow.com/a/24652257/2571881
" TODO: Reselect visual mode
" OBS: I was using --> exec 'normal! _"_2x'
" How to know if I have the optional space after the comment '[ ]?' ?
" because this influences the cursor position
" Now all comments are added at the beginning of line because other people want
" to uncomment and comment using visual block
" after that I should give some suggestions to [mike](https://stackoverflow.com/users/2839380/mike) at stackoverflow
" his post on this question [here](https://stackoverflow.com/a/24652257/2571881)
" idea to avoid many ifs
" let l:space = ( &ft =~ "\v(c|cpp|java|arduino)" ? "3" : "2" )
autocmd FileType c,cpp,java let b:comment_leader = '//'
autocmd FileType arduino let b:comment_leader = '//'
autocmd FileType sh,ruby,python let b:comment_leader = '#'
autocmd FileType zsh let b:comment_leader = '#'
autocmd FileType conf,fstab let b:comment_leader = '#'
autocmd FileType matlab,tex let b:comment_leader = '%'
autocmd FileType vim let b:comment_leader = '"'
function! ToggleComment()
if exists('b:comment_leader')
let l:pos = col('.')
let l:space = ( &ft =~ '\v(c|cpp|java|arduino)' ? '3' : '2' )
if getline('.') =~ '\v(\s*|\t*)' .b:comment_leader
let l:space -= ( getline('.') =~ '\v.*\zs' . b:comment_leader . '(\s+|\t+)@!' ? 1 : 0 )
execute 'silent s,\v^(\s*|\t*)\zs' .b:comment_leader.'[ ]?,,g'
let l:pos -= l:space
else
exec 'normal! 0i' .b:comment_leader .' '
let l:pos += l:space
endif
call cursor(line("."), l:pos)
else
echo 'no comment leader found for filetype'
end
endfunction
nnoremap <Leader>t :call ToggleComment()<CR>
inoremap <Leader>t <C-o>:call ToggleComment()<CR>
xnoremap <Leader>t :'<,'>call ToggleComment()<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment