Skip to content

Instantly share code, notes, and snippets.

@danchoi
Created September 20, 2016 20:14
Show Gist options
  • Save danchoi/46b4ca4e2881d584ac66440801344393 to your computer and use it in GitHub Desktop.
Save danchoi/46b4ca4e2881d584ac66440801344393 to your computer and use it in GitHub Desktop.
Comment uncomment
" Home-brewed commenter and uncommenter
" :Comment and :Uncomment will comment out a given range of lines
" or visual selection.
" Comment marks will be placed at beginning of line, and only comment
" marks at the beginning of lines will be uncommented.
" Comment mark will dynamically determined to be '#', '//' or '--' depending
" on file extension of the file in buffer, and '#' if none can be detected.
func! CommentMarker()
let ext = expand('%:e')
if ext == 'js'
return '//'
elseif ext == 'hs' || ext == 'elm'
return '--'
elseif ext == 'html'
return '<!-- '
else
return '#'
endif
endfunc
func! Comment() range
let lnum = a:firstline
while lnum <= a:lastline
let line = getline(lnum)
let newline = substitute(line, '^', CommentMarker() . ' ', '') " comment out
call setline(lnum, newline)
let lnum += 1
endwhile
endfunc
func! Uncomment() range
let lnum = a:firstline
while lnum <= a:lastline
let line = getline(lnum)
let newline = substitute(line, '^'.CommentMarker().'\s\?', '', '') " uncomment
call setline(lnum, newline)
let lnum += 1
endwhile
endfunc
command! -bar -range Comment :<line1>,<line2>call Comment()
command! -bar -range Uncomment :<line1>,<line2>call Uncomment()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment