<lambda>null1 package org.jetbrains.dokka
2
3 import org.intellij.markdown.IElementType
4 import org.intellij.markdown.MarkdownElementTypes
5 import org.intellij.markdown.ast.ASTNode
6 import org.intellij.markdown.ast.LeafASTNode
7 import org.intellij.markdown.ast.getTextInNode
8 import org.intellij.markdown.flavours.commonmark.CommonMarkFlavourDescriptor
9 import org.intellij.markdown.parser.MarkdownParser
10
11 class MarkdownNode(val node: ASTNode, val parent: MarkdownNode?, val markdown: String) {
12 val children: List<MarkdownNode> = node.children.map { MarkdownNode(it, this, markdown) }
13 val type: IElementType get() = node.type
14 val text: String get() = node.getTextInNode(markdown).toString()
15 fun child(type: IElementType): MarkdownNode? = children.firstOrNull { it.type == type }
16
17 val previous get() = parent?.children?.getOrNull(parent.children.indexOf(this) - 1)
18
19 override fun toString(): String = StringBuilder().apply { presentTo(this) }.toString()
20 }
21
MarkdownNodenull22 fun MarkdownNode.visit(action: (MarkdownNode, () -> Unit) -> Unit) {
23 action(this) {
24 for (child in children) {
25 child.visit(action)
26 }
27 }
28 }
29
MarkdownNodenull30 fun MarkdownNode.toTestString(): String {
31 val sb = StringBuilder()
32 var level = 0
33 visit { node, visitChildren ->
34 sb.append(" ".repeat(level * 2))
35 node.presentTo(sb)
36 sb.appendln()
37 level++
38 visitChildren()
39 level--
40 }
41 return sb.toString()
42 }
43
MarkdownNodenull44 private fun MarkdownNode.presentTo(sb: StringBuilder) {
45 sb.append(type.toString())
46 sb.append(":" + text.replace("\n", "\u23CE"))
47 }
48
parseMarkdownnull49 fun parseMarkdown(markdown: String): MarkdownNode {
50 if (markdown.isEmpty())
51 return MarkdownNode(LeafASTNode(MarkdownElementTypes.MARKDOWN_FILE, 0, 0), null, markdown)
52 return MarkdownNode(MarkdownParser(CommonMarkFlavourDescriptor()).buildMarkdownTreeFromString(markdown), null, markdown)
53 }
54