FIX: remove empty lines but keep whitespace on first line in code blocks

This commit is contained in:
Régis Hanol 2015-03-17 17:27:16 +01:00
parent 8fcbea0c2c
commit aa41a9ce70
2 changed files with 9 additions and 6 deletions

View file

@ -167,6 +167,11 @@ function outdent(t) {
return t.replace(/^([ ]{4}|\t)/gm, ""); return t.replace(/^([ ]{4}|\t)/gm, "");
} }
function removeEmptyLines(t) {
return t.replace(/^\n+/, "")
.replace(/\s+$/, "");
}
function hideBackslashEscapedCharacters(t) { function hideBackslashEscapedCharacters(t) {
return t.replace(/\\\\/g, "\u1E800") return t.replace(/\\\\/g, "\u1E800")
.replace(/\\`/g, "\u1E8001"); .replace(/\\`/g, "\u1E8001");
@ -186,14 +191,14 @@ function hoistCodeBlocksAndSpans(text) {
// <pre>...</pre> code blocks // <pre>...</pre> code blocks
text = text.replace(/(^\n*|\n\n)<pre>([\s\S]*?)<\/pre>/ig, function(_, before, content) { text = text.replace(/(^\n*|\n\n)<pre>([\s\S]*?)<\/pre>/ig, function(_, before, content) {
var hash = md5(content); var hash = md5(content);
hoisted[hash] = escape(showBackslashEscapedCharacters(content.trim())); hoisted[hash] = escape(showBackslashEscapedCharacters(removeEmptyLines(content)));
return before + "<pre>" + hash + "</pre>"; return before + "<pre>" + hash + "</pre>";
}); });
// fenced code blocks (AKA GitHub code blocks) // fenced code blocks (AKA GitHub code blocks)
text = text.replace(/(^\n*|\n\n)```([a-z0-9\-]*)\n([\s\S]*?)\n```/g, function(_, before, language, content) { text = text.replace(/(^\n*|\n\n)```([a-z0-9\-]*)\n([\s\S]*?)\n```/g, function(_, before, language, content) {
var hash = md5(content); var hash = md5(content);
hoisted[hash] = escape(showBackslashEscapedCharacters(content.trim())); hoisted[hash] = escape(showBackslashEscapedCharacters(removeEmptyLines(content)));
return before + "```" + language + "\n" + hash + "\n```"; return before + "```" + language + "\n" + hash + "\n```";
}); });
@ -209,9 +214,7 @@ function hoistCodeBlocksAndSpans(text) {
} }
// we can safely hoist the code block // we can safely hoist the code block
var hash = md5(content); var hash = md5(content);
// only remove trailing whitespace hoisted[hash] = escape(outdent(showBackslashEscapedCharacters(removeEmptyLines(content))));
content = content.replace(/\s+$/, "");
hoisted[hash] = escape(outdent(showBackslashEscapedCharacters(content)));
return before + " " + hash + "\n"; return before + " " + hash + "\n";
}); });

View file

@ -529,6 +529,6 @@ test("censoring", function() {
test("code blocks/spans hoisting", function() { test("code blocks/spans hoisting", function() {
cooked("```\n\n some code\n```", cooked("```\n\n some code\n```",
"<p><pre><code class=\"lang-auto\">some code</code></pre></p>", "<p><pre><code class=\"lang-auto\"> some code</code></pre></p>",
"it works when nesting standard markdown code blocks within a fenced code block"); "it works when nesting standard markdown code blocks within a fenced code block");
}); });