From 9551f3ae1ec06551f5587d9f02ce66dd5bc26ed1 Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy <dmitriy@ideascup.me> Date: Sun, 12 Jun 2022 00:58:24 +0300 Subject: [PATCH] par(md): skip empty line... ... instead of clearing new line character --- par/md.test.ts | 6 +++--- par/md.ts | 20 +++++++++----------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/par/md.test.ts b/par/md.test.ts index 58ec179..45a24ba 100644 --- a/par/md.test.ts +++ b/par/md.test.ts @@ -7,12 +7,13 @@ const ren = new HtmlStrRenderer(); // Misc Deno.test({ - name: "should skip new line character", + name: "should skip empty line", fn: () => { const par = new MarkdownParser(); assertEquals(ren.render(par.parse("\n")), ""); assertEquals(ren.render(par.parse("\r\n")), ""); assertEquals(ren.render(par.parse("\n\r\n")), ""); + assertEquals(ren.render(par.parse("\n \n")), ""); }, }); @@ -51,13 +52,12 @@ Deno.test({ Deno.test({ name: "should parse ATX header if line contains additional spaces", + only: true, fn: () => { const par = new MarkdownParser(); assertEquals(ren.render(par.parse(" # hello")), "<h1>hello</h1>"); assertEquals(ren.render(par.parse(" # hello")), "<h1>hello</h1>"); assertEquals(ren.render(par.parse(" # hello")), "<h1>hello</h1>"); - assertEquals(ren.render(par.parse("\n # hello")), "<h1>hello</h1>"); - assertEquals(ren.render(par.parse("\r\n # hello")), "<h1>hello</h1>"); }, }); diff --git a/par/md.ts b/par/md.ts index 9fcc37e..0cc3e1c 100644 --- a/par/md.ts +++ b/par/md.ts @@ -2,7 +2,7 @@ import { AnyNode, Elem, Fragment, TextNode } from "../core/node.ts"; import { isNil } from "../core/utils.ts"; import { Parser } from "./types.ts"; -const RE_NEW_LINE = /^\r?\n/; +const RE_EMPTY_LINE = /^\s*$/; const RE_OPEN_ATX_HEADING = /^\s{0,3}(#{1,6})(\s|$)/; const RE_CLOSE_ATX_HEADING = /(^|\s+)#*\s*$/; @@ -12,17 +12,9 @@ export class MarkdownParser implements Parser { const astDoc: AstDocument = { kind: AstKind.Document, content: [] }; let readStr = input; - while (readStr.length) { - // 1. clear new line character - const match = RE_NEW_LINE.exec(readStr); - if (!isNil(match)) { - readStr = readStr.slice(match[0].length); - continue; - } - - // 2. try to find atx heading sequence - const newReadStr = parseAtxHeading(astDoc, readStr) ?? + const newReadStr = skipEmptyLine(readStr) ?? + parseAtxHeading(astDoc, readStr) ?? parseParagraph(astDoc, readStr); if (isNil(newReadStr)) break; readStr = newReadStr; @@ -55,6 +47,12 @@ function Text(ast: AstText): TextNode { // parse utils +function skipEmptyLine(readStr: string): string | null { + const match = RE_EMPTY_LINE.exec(readStr); + if (isNil(match)) return null; + return readStr.slice(match[0].length); +} + function parseAtxHeading(ast: AstDocument, readStr: string): string | null { const match = RE_OPEN_ATX_HEADING.exec(readStr); if (isNil(match)) return null;