I am trying to get vim
to do block commenting and uncommenting of highlighted lines while keeping the correct indentation level. I am so frustratingly close.
let b:commentChar='//'
autocmd BufReadPost *.[ch] let b:commentChar='//'
autocmd BufReadPost *.cpp let b:commentChar='//'
autocmd BufReadPost *.py let b:commentChar='#'
autocmd BufReadPost *.*sh let b:commentChar='#'
function! Docomment ()
"make comments on all the lines we've grabbed
execute 's/^\s*/&'.escape(b:commentChar, '\/').' /e'
nohl
endfunction
function! Uncomment ()
"uncomment on all our lines
execute 's/\v(^\s*)\V'.escape(b:commentChar, '\/').'\v\s*/\1/e'
nohl
endfunction
function! Comment ()
"does the first line begin with a comment?
let l:line=getpos("'<")[1]
"if there's a match
if match(getline(l:line), '^\s*'.b:commentChar)>-1
echom "calling uncomment"
call Uncomment()
else
echom "calling docomment"
call Docomment()
endif
endfunction
vnoremap <silent> <C-r> :call Comment()<cr><cr>
Current behavior on highlighting the following sample lines and calling C-r
:
These are sample lines
What will vim do here?
Results in:
// These are sample lines
What will vim do here?
The output of :messages
is calling comment, calling uncomment
which tells me that vim is first commenting the first line, then going back to look at the first line, seeing that it starts with a comment, and then uncommenting the second line. However, when calling the Uncomment()
function, it works correctly:
// If I started with highlighting
// multiple commented lines
This will be correctly changed to:
If I started with highlighting
multiple commented lines
How do I get vim to only look at the first line once, and then stop re-checking it after it's changed the line?
execute '''<,''>s/^\s*/&'.escape(b:commentChar, '\/').' /e'
?n+1
comments on all lines, where n is the number of highlighted lines. I think I understand more about what it is doing from usingechom
statements; I've edited my post.vnoremap <silent> <C-r> :<c-u>call Comment()<cr>
Docomment()
andUncomment()
functions works perfectly. You are my hero =))). I will write my own answer tomorrow so others know this is solved, or you can write something and I will accept it.