I have the markdown file that uses # for headlines, like this one.#H1Text one one##h2more Text#more H1sEven more textNo 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.#H1Text one one##h2more Text#more H1sEven more textI thought I could write a function that gets executed when I write my changes to the file and I came up with this two functionsfunction! <SID>SurroundingNewLines()    execute normal! O\<esc>jo\<esc>endfuncfunction! <SID>AddEmptyLines()    1global/^#/execute normal! o\<esc>    2,$global/^#/call <SID>SurroundingNewLines()    %substitute/\n\{3,}/\r\r/eendfuncPlease 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?
How to surround all headlines with empty new lines in a markdown file?
vimscript;regular expression;global command
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\rNote 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 ...