3

I have the markdown file that uses # for headlines, like this one.

#H1
Text one one
##h2
more Text
#more H1s
Even more text

No I have the problem that some interpreters of markdown don't accept a headline when it isn't surrounded by empty lines. So the upper file needs to look like this.

#H1

Text one one

##h2

more Text

#more H1s

Even more text

I thought I could write a function that gets executed when I write my changes to the file and I came up with this two functions

function! <SID>SurroundingNewLines()
    execute "normal! O\<esc>jo\<esc>"
endfunc

function! <SID>AddEmptyLines()
    1global/^#/execute "normal! o\<esc>"
    2,$global/^#/call <SID>SurroundingNewLines()
    %substitute/\n\{3,}/\r\r/e
endfunc

Please note that this is my first experience with VimScript.

The function AddEmptyLines searches for lines that start with a # and surrounds those with new lines and then the substitute command removes all duplicate empty lines.

This works but it is rather inefficient since it always adds the lines and then removes all unnecessarily added lines.

So is there a better way of doing this, for example find all headers that are not surrounded by empty lines?

7

Well, you can have perhaps more cases than you account for in your description: a header line can be preceded by 0, 1 or many empty lines, and can be followed by 0, 1 or many empty lines. In all these cases, you want to achieve a header line preceded and followed by exactly 1 line (if I got that right). With this description, the problem can be solved with something like (I'm sure it can be improved):

:%s/\(^\s*\n\)*\(^#.*\)\(\n\s*\)*/\r\2\r\r/

or (similar, with more symmetry and slightly simpler):

:%s/\v^(\s*\n)*(#.*\n)(\s*\n)*/\r\2\r

Note that two headers following one right after the other will have 2 lines between them, but in a way this is a feature: in this way you can see that you still have to add some text there ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.