diff --git a/src/index.js b/src/index.js index 3938c5c..ecacddd 100644 --- a/src/index.js +++ b/src/index.js @@ -24,7 +24,7 @@ function encodeAttr(str) { /** Parse Markdown into an HTML String. */ export default function parse(md, prevLinks) { - let tokenizer = /((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm, + let tokenizer = /((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^```[ \t]*(?:(\w+)[ \t]*)?\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm, context = [], out = '', links = prevLinks || {}, @@ -61,7 +61,7 @@ export default function parse(md, prevLinks) { } // Code/Indent blocks: else if (t = (token[3] || token[4])) { - chunk = '
'+outdent(encodeAttr(t).replace(/^\n+|\n+$/g, ''))+'
'; + chunk = '
'+outdent(encodeAttr(t).replace(/^\n+|\n+$/g, ''))+'
'; } // > Quotes, -* lists: else if (t = token[6]) { diff --git a/test/index.js b/test/index.js index 5262b16..f95b15a 100644 --- a/test/index.js +++ b/test/index.js @@ -119,10 +119,35 @@ describe('snarkdown()', () => { expect(snarkdown('```js\nfunction codeBlocks() {\n\treturn "Can be inserted";\n}\n```')).to.equal('
function codeBlocks() {\n\treturn "Can be inserted";\n}
'); }); + it('parses fenced code blocks with spaces around the language (fixes #62)', () => { + expect(snarkdown('```js \ncode\n```')).to.equal('
code
'); + expect(snarkdown('``` js \ncode\n```')).to.equal('
code
'); + expect(snarkdown('```js\t\ncode\n```')).to.equal('
code
'); + expect(snarkdown('``` \ncode\n```')).to.equal('
code
'); + }); + it('parses tabs as a code poetry block', () => { expect(snarkdown('\tvar a = 1')).to.equal('
var a = 1
'); }); + it('parses a language-less fence with mixed whitespace', () => { + expect(snarkdown('``` \t \t\ncode\n```')).to.equal('
code
'); + }); + + it('handles an unclosed language-less fence without excessive backtracking', () => { + // A missing closing fence must not retry every split of the opening whitespace. + const markdown = '```' + '\t'.repeat(200000) + '\nbody'; + expect(snarkdown(markdown)).to.equal(markdown); + }).timeout(2000); + + it('preserves a language name after leading tabs', () => { + expect(snarkdown('```\tJS \t\ncode\n```')).to.equal('
code
'); + }); + + it('preserves line breaks after an unclosed fence with spaces', () => { + expect(snarkdown('``` \nbody')).to.equal('```
body'); + }); + it('escapes code/quote blocks', () => { expect(snarkdown('```\n\n```')).to.equal('
<foo>
'); expect(snarkdown('\t')).to.equal('
<foo>
');