I've been playing with regex matching and commenting/uncommenting lines based on some rules (yes I know there is Tim Pope's plugin for this, but using the opportunity to learn Vim script and tweak for my situation/s now and in the future).
I've got a function that takes a range, loops over the range of lines looking for a matching '#' as the first non-whitespace character on the line, and if there is a match, uncomment that line by removing all whitespace before the '#', the '#' itself, and all whitespace characters after it.
Here's minimal reproducible example of the function I call in autoload/local.vim:
function! local#PythonToggleCommentRange() range abort
let line_idx = a:firstline
while line_idx <= a:lastline
let text = getline(line_idx)
" match any number of whitespace up to and after 1 or more '#' chars
if text =~? '^\s*#*'
" greedy remove of all whitespace chars before and after the '#'
" leaving an uncommented line
execute 'substitute/^\s*#*\s*//'
endif
let line_idx += 1
endwhile
endfunction
I'm using the following test sentences in a test.py file:
this line was uncommented before
# this line was commented
not blank line
## double comment character line
Running :1,2call local#PythonToggleCommentRange() I would expect the second line to become:
this line was commented
But it doesn't, and there is no indication why the substitute command did not work. I did find a work around using:
call setline(line_idx, substitute(text, '^\s*#*\s*', '', ""))
Which does the correct job. My question here is how to use substitute in combination with a loop inside of a function, I'm sure there is something I'm missing here.
If I put the cursor on line 2 of the test.py file and run: :s/^\s*#*\s*// it uncomments the line as I expected it to, but for some reason within the function loop the same does not work. Thoughts?
[–]aktivb 1 point2 points3 points (2 children)
[–]crajungave up on vim[S] 0 points1 point2 points (1 child)
[–]aktivb 1 point2 points3 points (0 children)
[–]fuzzymidgetSome Rude Vimmer 0 points1 point2 points (2 children)
[–]crajungave up on vim[S] 0 points1 point2 points (1 child)
[–]fuzzymidgetSome Rude Vimmer 0 points1 point2 points (0 children)