This post really stuck with me lol, I read it on my way home and have been thinking about it the back of my head all evening.
I really wanted to replicate this using a regex search, cause I really thought I could lol and here's what I got!
:%s/\([^\_^]\)\n\([^\n]\)/\1 \2/ | %y | u
So now it's my turn to break it down! So we have that commands here, first we do a regex substitution on all the lines, then we yank all the lines, and finally we undo the substitution. Lets look at each bit!
I use % twice here and that means to do the command on all the lines in the file! This is nifty for both the substitution and the yanking
Here is the substitution on it's own
and even farther here is the regex we are using to search. This is slightly altertered from the real vim syntax above. I replace \( and \) with just ( and ). In vim substitutions you need to escape the parens you are using as capture groups. I replaced them down below cause I find it more readable like this
We are actually actually going to ignore that first capture group right now and start with
This is where I started, and this matches a new line, and then captures the next character which must NOT be a new line. Now I was able to replace the new line with a space! I noticed however that this did NOT preserve blank lines, which I didn’t like (and didn’t match your implementation).
This is where that first capture group comes in! ([^\_^]). This captures a single charactur and makes sure it is NOT a \_^ which is a VIM special character that means ‘beggining of line’. In practice what this does is make sure there is some character proceeding our newline. This allows blank lines to not be captured, and therefor not be altered by the substitution!
And then so stitch that all together we then stitch our first and second capture group together seperated by a space (where there used to be a newline).
The rest of the command is much simpler!
is gonna yank the whole file for us, and then
is gonna undo our substitution!
What do you think? Any edge cases that I missed that yours catches?
(Oh and I'm excited for your second dev.to post now too! 😉)
Hah nice! And shorter! and with regex! This is super elegant.
Not sure about edge cases but I'll give it a go and let you know. On a first look, your undo gets rid of one of my annoyances, which is that my solution was reformatting code blocks too, which you might want to leave untouched.
It also doesn't rely on where you are on the file. Mine was breaking if I was on the bottom line.
So far yours def wins in my book. Making it more worth having shared my solution. Thanks!
Ahh I didn't think about code blocks really. Mine is gonna single line all codeblocks I think lol Which probably isn't the best!
So that's at least one edge case to think about!
Thanks again for the fun post, I enjoyed it haha
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.