Selecting newlines before certain keywords

I am creating a multiplexing mode inside CodeMirror. Here is how it will look like:

KEYWORD1
blah
stuff

KEYWORD2
morethings
some

more

ANOTHER
morestuff
things

++++++++++++++++++++

KEYWORD2
morethings
some
config

ANOTHER
morestuff
things

++++++++++++++++++++
...

I want the inner syntax highlighting to start on each keyword and end on each newline before a keyword. I tried the following:

        var keywords = ['KEYWORD1', 'KEYWORD2', 'ANOTHER']
        CodeMirror.defineMode("entireConfig", function (config) {
          return CodeMirror.multiplexingMode(
            CodeMirror.getMode({}, "outerConfig"),
            {
              open: RegExp('(' + keywords.join("|") + ')'),
              close: '\n', // 1
              mode: CodeMirror.getMode({}, "innerConfig"),
              delimStyle: "delimit",
            }
          );
        });

Of course the above won’t work because we don’t want to close the inner mode on a newline. This is because in the first part underneath there is a newline underneath the KEYWORD2, there is a newline before the more and the more won’t get into the inner mode because of this. I want to select the newline above the ANOTHER. This means that the close at 1 will need to be changed. What RegExp would select the newlines before the keywords and the ++++++++++++++++++++ ? You can use the keywords array when constructing the RegExp. Just in case here is what I want to get selected (the red parts):


Notice how I don’t want to select the newline between the KEYWORD2 and +++++++++++++++++++++, I don’t know if that will do anything since there is no opening for that newline.