Skip to content

Instantly share code, notes, and snippets.

@PeterRincker PeterRincker/comment.vim
Last active Nov 25, 2019

Embed
What would you like to do?
SimpleComment
" Inspired by Tim Pope's commentary.vim
"
" Uses b:commentstring or 'commentstring' as the comment pattern
" example:
" let &commentstring = '/*%s*/'
nnoremap gcc :<c-u>.,.+<c-r>=v:count<cr>call <SID>toggleComment()<cr>
nnoremap gc :<c-u>set opfunc=<SID>commentOp<cr>g@
xnoremap gc :call <SID>toggleComment()<cr>
function! s:commentOp(...)
'[,']call s:toggleComment()
endfunction
function! s:toggleComment() range
let comment = substitute(get(b:, 'commentstring', &commentstring), '\s*\(%s\)\s*', '%s', '')
let pattern = '\V' . printf(escape(comment, '\'), '\(\s\{-}\)\s\(\S\.\{-}\)\s\=')
let replace = '\1\2'
if getline('.') !~ pattern
let indent = matchstr(getline('.'), '^\s*')
let pattern = '^' . indent . '\zs\(\s*\)\(\S.*\)'
let replace = printf(comment, '\1 \2' . (comment =~ '%s$' ? '' : ' '))
endif
for lnum in range(a:firstline, a:lastline)
call setline(lnum, substitute(getline(lnum), pattern, replace, ''))
endfor
endfunction
@esn89

This comment has been minimized.

Copy link

esn89 commented May 26, 2015

Thanks for this. I love it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.