[parsing/mfm] Rework codeblock node parsing & serialization

This commit is contained in:
Laura Hausmann 2024-09-26 01:09:43 +02:00
parent 5b3dec0a08
commit c02af726e1
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
3 changed files with 27 additions and 13 deletions

View file

@ -17,7 +17,7 @@ public static class MfmSerializer
{ {
result.Append($"\n```{mfmCodeBlockNode.Language?.Value ?? ""}\n"); result.Append($"\n```{mfmCodeBlockNode.Language?.Value ?? ""}\n");
result.Append(mfmCodeBlockNode.Code); result.Append(mfmCodeBlockNode.Code);
result.Append("\n```\n\n"); result.Append("\n```\n");
break; break;
} }
case MfmMathBlockNode mfmMathBlockNode: case MfmMathBlockNode mfmMathBlockNode:

View file

@ -202,13 +202,15 @@ module private MfmParser =
|>> fun v -> MfmInlineCodeNode(v) :> MfmNode |>> fun v -> MfmInlineCodeNode(v) :> MfmNode
let codeBlockNode = let codeBlockNode =
opt (previousCharSatisfies isNewline >>. skipNewline) opt skipNewline
>>. opt skipNewline
>>. previousCharSatisfiesNot isNotNewline >>. previousCharSatisfiesNot isNotNewline
>>. skipString "```" >>. skipString "```"
>>. opt (many1CharsTill asciiLetter (lookAhead newline)) >>. opt (many1CharsTill asciiLetter (lookAhead newline))
.>>. (skipNewline .>>. (skipNewline
>>. manyCharsTill anyChar (attempt (skipNewline >>. skipString "```"))) >>. manyCharsTill anyChar (attempt (skipNewline >>. skipString "```")))
.>> (opt <| attempt (skipNewline >>. skipNewline)) .>> (skipNewline <|> eof)
.>> opt skipNewline
|>> fun (lang: string option, code: string) -> MfmCodeBlockNode(code, lang) :> MfmNode |>> fun (lang: string option, code: string) -> MfmCodeBlockNode(code, lang) :> MfmNode
let mathNode = let mathNode =

View file

@ -140,7 +140,15 @@ public class MfmTests
[TestMethod] [TestMethod]
public void TestCodeBlock() public void TestCodeBlock()
{ {
const string input = """ const string canonical = """
test 123
```
this is a code block
```
test 123
""";
const string alt = """
test 123 test 123
``` ```
@ -149,17 +157,21 @@ public class MfmTests
test 123 test 123
"""; """;
List<MfmNode> expected = List<MfmNode> expected =
[ [
new MfmTextNode("test 123\n"), new MfmTextNode("test 123"),
new MfmCodeBlockNode("this is a code block", null), new MfmCodeBlockNode("this is a code block", null),
new MfmTextNode("test 123") new MfmTextNode("test 123")
]; ];
var res = Mfm.parse(input); var res = Mfm.parse(canonical);
var res2 = Mfm.parse(alt);
AssertionOptions.FormattingOptions.MaxDepth = 100; AssertionOptions.FormattingOptions.MaxDepth = 100;
res.ToList().Should().Equal(expected, MfmNodeEqual); res.ToList().Should().Equal(expected, MfmNodeEqual);
MfmSerializer.Serialize(res).Should().BeEquivalentTo(input); res2.ToList().Should().Equal(expected, MfmNodeEqual);
MfmSerializer.Serialize(res).Should().BeEquivalentTo(canonical);
MfmSerializer.Serialize(res2).Should().BeEquivalentTo(canonical);
} }
[TestMethod] [TestMethod]