Skip to content

Instantly share code, notes, and snippets.

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

What would you like to do?
" 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()
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$' ? '' : ' '))
for lnum in range(a:firstline, a:lastline)
call setline(lnum, substitute(getline(lnum), pattern, replace, ''))

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.