summaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt
blob: 5ee984fa5140ede129827380ffb70e01e55bd8f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package moe.nea.blog.md

import moe.nea.blog.util.indentSize
import java.util.*


class MarkdownParser(source: String) {
    private val lines = source.lines()
    private var lineIndex = 0
    private var blockIndents = 0
    private val indentStack = Stack<Int>()

    private val blockParsers = mutableListOf<BlockParser>()
    private val inlineParsers = mutableListOf<InlineParser>()
    private val preprocessors = Stack<LinePreProcessor>()
    private var peekedLine: String? = null

    fun findParserFor(line: String): BlockParser? {
        return blockParsers.filter { it.detect(line) }
            .maxByOrNull { it.prio }
    }

    fun readChildBlock(): MarkdownBlock? {
        val peek = peekLine() ?: return null
        val blockParser = findParserFor(peek) ?: ParagraphParser
        return blockParser.parse(this)
    }

    fun pushPreProcessor(preProcessor: LinePreProcessor) {
        peekedLine = null
        preprocessors.push(preProcessor)
    }

    fun popPreProcessor() {
        peekedLine = null
        preprocessors.pop()
    }

    fun preProcessLine(string: String): String? {
        var acc = string
        for (processor in preprocessors) {
            acc = processor.preprocess(lineIndex, acc) ?: return null
        }
        return acc
    }

    fun pushIndent(newIndent: Int) {
        indentStack.push(blockIndents)
        blockIndents += newIndent
        peekedLine = null
    }

    fun popIndent() {
        blockIndents = indentStack.pop()
        peekedLine = null
    }

    fun unpeekLine() {
        peekedLine = null
    }

    fun consumeLine(): String? {
        val line = peekLine()
        if (line != null) {
            peekedLine = null
            lineIndex++
        }
        return line
    }

    fun peekLine(): String? {
        if (lineIndex !in lines.indices) return null
        val line = peekedLine ?: preProcessLine(lines[lineIndex]) ?: return null
        peekedLine = line
        val indent = line.indentSize()
        if (indent != null && indent < blockIndents) {
            peekedLine = null
            return null
        }
        return line.drop(blockIndents)
    }

    fun parseInlineTextUntil(
        text: String,
        initialLookback: MarkdownFormat,
        breakout: (lookback: MarkdownFormat, remaining: String) -> Boolean
    ): Pair<List<MarkdownFormat>, String> {
        val seq = mutableListOf<MarkdownFormat>()
        var remaining = text
        var lastToken: MarkdownFormat = initialLookback
        while (remaining.isNotEmpty()) {
            if (breakout(lastToken, remaining))
                break
            val (tok, next) = parseInlineTextOnce(lastToken, remaining)
            seq.add(tok)
            lastToken = tok
            remaining = next
        }
        return seq to remaining
    }

    fun parseInlineTextOnce(lookback: MarkdownFormat, text: String): Pair<MarkdownFormat, String> {
        require(text.isNotEmpty()) // TODO handle empty string
        val parser = inlineParsers.find { it.detect(lookback, text) }
        if (parser != null) {
            return parser.parse(this, text)
        }
        if (text[0] == ' ') {
            return Pair(Whitespace(), text.substring(1))
        }
        val nextSpecial = text.indexOfFirst { it in inlineParsers.flatMap { it.specialSyntax } || it == ' ' }
        if (nextSpecial == 0) {
            return Pair(Word(text.substring(0, 1)), text.substring(1))
        }
        if (nextSpecial == -1) {
            return Pair(Word(text), "")
        }
        return Pair(Word(text.substring(0, nextSpecial)), text.substring(nextSpecial))
    }

    fun parseInlineText(text: String): MarkdownFormat {
        val (tokens, rest) = parseInlineTextUntil(text, Begin()) { _, _ -> false }
        require(rest.isEmpty())
        return collapseInlineFormat(tokens, true)
    }

    private fun expandMarkdownFormats(sequence: List<MarkdownFormat>): List<MarkdownFormat> {
        val elongated = mutableListOf<MarkdownFormat>()
        for (markdownFormat in sequence) {
            if (markdownFormat is FormatSequence) {
                elongated.addAll(expandMarkdownFormats(markdownFormat.list))
            } else {
                elongated.add(markdownFormat)
            }
        }
        return elongated
    }

    private fun collapseMarkdownFormats(
        sequence: List<MarkdownFormat>,
        trimWhitespace: Boolean
    ): MutableList<MarkdownFormat> {
        val shortened = mutableListOf<MarkdownFormat>()
        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<MarkdownFormat>, trimWhitespace: Boolean): MarkdownFormat {
        val formats = collapseMarkdownFormats(expandMarkdownFormats(sequence), trimWhitespace)
        return formats.singleOrNull() ?: FormatSequence(formats)
    }

    fun readDocument(): Document {
        val list = mutableListOf<MarkdownBlock>()
        while (true) {
            val block = readChildBlock() ?: break
            list.add(block)
        }
        return Document(list)
    }

    fun addDefaultParsers() {
        blockParsers.add(CodeBlockParser)
        blockParsers.add(HeaderParser)
        blockParsers.add(ListParser)
        inlineParsers.add(ItalicsParser)
        inlineParsers.add(LinkParser)
        inlineParsers.add(ImageParser)
    }

    fun getLineIndex(): Int {
        return lineIndex
    }

    fun mergeBlocks(elements: List<MarkdownBlock>): MarkdownBlock {
        return elements.singleOrNull() ?: BlockList(elements)
    }

    fun getIndent(): Int {
        return blockIndents
    }
}