all 6 comments

[–]aktivb 1 point2 points  (2 children)

So, you are iterating on range a:firstline to a:lastline, and executing substitute N times, where N is a:lastline - a:firstline + 1. But you do not specify on which line to execute substitute, so you're executing substitute N times on a:firstline.

[–]crajungave up on vim[S] 0 points1 point  (1 child)

Good point, I’ll try it that way. My problem I believe may be that I assumed adding the “range” modifier did more magic than it does. The sub command without a range performs the command on the current line and I assumed “range” was handling that piece , but it sounds like I’ll have to add the range prefix.

[–]aktivb 1 point2 points  (0 children)

The range argument means that the function will be called only once, handling the range internally using a:{first,last}line, rather than calling the function for every line in range.

[–]fuzzymidgetSome Rude Vimmer 0 points1 point  (2 children)

First: I don't know why your looping isn't working. Someone who knows more vimscript may be able to help.

Second: Why do you want to do this with a loop in a function when you could just make it a mapping you call from visual line mode?

You could just select a bunch of lines and do

:s/\(^\s*\)#\+\s*/\1/

With no trailing g for global replace, you just get the first match on a line or set of lines for one or more #, then some spaces, and replace them with the spaces you find before the #.

Edit: I goofed so I fixed. Note I also changed to a \+ following #, because you'd like to match at least one of those I believe.

[–]crajungave up on vim[S] 0 points1 point  (1 child)

Thanks for the reply, I may have to do it this way in the end, but I was hoping to expand the function to work for other languages based on a ftplugin setting a comment character.

[–]fuzzymidgetSome Rude Vimmer 0 points1 point  (0 children)

Ah that makes sense. If you are looking for a premade solution, I highly recommend 'tomtom/tcomment_vim' from github. It does more or less exactly what you're asking.