From be66c61d729fe642e3dd3ed2214990f9f2273c5e Mon Sep 17 00:00:00 2001 From: Linnea Gräf Date: Sun, 24 Mar 2024 15:24:05 +0100 Subject: Fix whitespace trimming --- src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt | 34 +++++++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) (limited to 'src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt') diff --git a/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt b/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt index 86b92d2..f8095ad 100644 --- a/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt +++ b/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt @@ -71,11 +71,39 @@ class MarkdownParser(source: String) { lastToken = tok remaining = next } - return collapseInlineFormat(seq) + return collapseInlineFormat(seq, true) } - fun collapseInlineFormat(sequence: List): MarkdownFormat { - return FormatSequence(sequence) + private fun expandMarkdownFormats(sequence: List): List { + val elongated = mutableListOf() + for (markdownFormat in sequence) { + if (markdownFormat is FormatSequence) { + elongated.addAll(expandMarkdownFormats(markdownFormat.list)) + } else { + elongated.add(markdownFormat) + } + } + return elongated + } + + private fun collapseMarkdownFormats( + sequence: List, + trimWhitespace: Boolean + ): MutableList { + val shortened = mutableListOf() + var last: MarkdownFormat = if (trimWhitespace) Whitespace() else Begin() + for (format in sequence) { + if (format is Whitespace && last is Whitespace) { + continue + } + last = format + shortened.add(format) + } + return shortened + } + + fun collapseInlineFormat(sequence: List, trimWhitespace: Boolean): MarkdownFormat { + return FormatSequence(collapseMarkdownFormats(expandMarkdownFormats(sequence), trimWhitespace)) } fun readDocument(): Document { -- cgit