Tests/OrgCoreTests/MarkdownToOrgTests.swift
234 lines · 9958 bytes
28 symbols in this file
MarkdownToOrgTestsorgnodestokensatxAndSetextHeadingsemphasisAndCodeintrawordUnderscoreStaysTextlinksAndImagesimageAloneGetsAltAttributenestedOrderedAndTaskListslistItemWithParagraphsAndCodeblockQuotecodeFencesBecomeSourceBlockstablesBecomeOrgTablesfootnotesfrontMattermathRuleHTMLAndCommentshardBreaksAndEntitiesparagraphLinesThatOrgWouldReadAsElementsheadingInsideListIsBoldwikilinksAndEmbedsembeddedImageWidthtagsGoToHeadingsAndFilecalloutsBecomeSpecialBlockstaskDateshighlightCommentAndBlockIDfileNameIsTheFallbackTitleheadingFragments
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// Markdown to org, one construct at a time; each output is read back with orgstar's parser.
6struct MarkdownToOrgTests {
7 func org(_ markdown: String, obsidian: Bool = false, title: String? = nil) -> (text: String, tree: OrgTree, model: DocumentModel, result: MarkdownToOrg.Result) {
8 let result = MarkdownToOrg.convert(markdown, obsidian: obsidian, title: title)
9 let tree = OrgParser.parse(result.text)
10 return (result.text, tree, DocumentModel(tree: tree), result)
11 }
12
13 func nodes(_ tree: OrgTree, _ kind: SyntaxKind) -> [SyntaxNode] {
14 tree.root.descendants().filter { $0.kind == kind }
15 }
16
17 func tokens(_ tree: OrgTree, _ kind: SyntaxKind) -> [SyntaxToken] {
18 tree.root.descendants().flatMap(\.tokens).filter { $0.kind == kind }
19 }
20
21 @Test func atxAndSetextHeadings() {
22 let out = org("# One\ntext\n## Two ##\nSetext\n======\nUnder\n---\n")
23 #expect(out.model.headings.map(\.level) == [1, 2, 1, 2])
24 #expect(out.model.headings.map(\.title) == ["One", "Two", "Setext", "Under"])
25 #expect(out.result.headings == 4)
26 }
27
28 @Test func emphasisAndCode() {
29 let out = org("Some **bold**, __strong__, *it*, _em_, ***both***, `co~de`, `x` and ~~gone~~.\n")
30 #expect(out.text == "Some *bold*, *strong*, /it/, /em/, */both/*, =co~de=, ~x~ and +gone+.\n")
31 #expect(nodes(out.tree, .bold).count == 3)
32 #expect(nodes(out.tree, .italic).count == 3)
33 #expect(nodes(out.tree, .verbatim).count == 1)
34 #expect(nodes(out.tree, .code).count == 1)
35 #expect(nodes(out.tree, .strikeThrough).count == 1)
36 }
37
38 @Test func intrawordUnderscoreStaysText() {
39 #expect(org("snake_case_name\n").text == "snake_case_name\n")
40 }
41
42 @Test func linksAndImages() {
43 let out = org("""
44 A [site](https://example.com "Title"), <https://auto.example>, <me@example.com>,
45  and [ref] and [label][ref].
46
47 [ref]: https://ref.example
48
49 """)
50 #expect(out.model.links == ["https://example.com", "https://auto.example", "mailto:me@example.com", "file:pics/a b.png", "https://ref.example", "https://ref.example"])
51 #expect(out.text.contains("[[https://example.com][site]]"))
52 #expect(out.result.links == 6)
53 }
54
55 @Test func imageAloneGetsAltAttribute() {
56 let out = org("\n")
57 #expect(out.text == "#+attr_html: :alt A cat\n[[file:cat.png]]\n")
58 #expect(nodes(out.tree, .affiliatedKeyword).count + nodes(out.tree, .keyword).count >= 1)
59 }
60
61 @Test func nestedOrderedAndTaskLists() {
62 let out = org("""
63 - one
64 - nested *a*
65 - [ ] open
66 - [x] done
67 - two
68
69 3. three
70 4. four
71
72 """)
73 #expect(out.text == """
74 - one
75 - nested /a/
76 - [ ] open
77 - [X] done
78 - two
79
80
81 3. [@3] three
82 4. four
83
84 """)
85 #expect(nodes(out.tree, .plainList).count == 3)
86 #expect(nodes(out.tree, .item).count == 7)
87 #expect(tokens(out.tree, .checkbox).count == 2)
88 #expect(tokens(out.tree, .counter).count == 1)
89 }
90
91 @Test func listItemWithParagraphsAndCode() {
92 let out = org("1. First\n\n More text.\n\n ```sh\n ls\n ```\n2. Second\n")
93 #expect(out.text == "1. First\n\n More text.\n #+begin_src sh\n ls\n #+end_src\n2. Second\n")
94 #expect(nodes(out.tree, .item).count == 2)
95 #expect(out.model.srcBlocks.map(\.language) == ["sh"])
96 }
97
98 @Test func blockQuote() {
99 let out = org("> quoted *text*\n> more\n>\n> - item\n")
100 #expect(out.text == "#+begin_quote\nquoted /text/\nmore\n\n- item\n#+end_quote\n")
101 #expect(nodes(out.tree, .block).count == 1)
102 }
103
104 @Test func codeFencesBecomeSourceBlocks() {
105 let out = org("```python\n* star\n#+keyword\nprint(1)\n```\n\n```\nplain\n```\n\n indented\n")
106 #expect(out.text == "#+begin_src python\n,* star\n,#+keyword\nprint(1)\n#+end_src\n\n#+begin_example\nplain\n#+end_example\n\n#+begin_example\nindented\n#+end_example\n")
107 #expect(out.model.srcBlocks.count == 1)
108 #expect(out.model.headings.isEmpty)
109 }
110
111 @Test func tablesBecomeOrgTables() {
112 let out = org("| A | B \\| C |\n|:--|--:|\n| `x` | **y** |\n| z |\n")
113 #expect(out.model.tables.count == 1)
114 #expect(out.model.tables[0].rows == [.cells(["A", "B \\vert{} C"]), .rule, .cells(["~x~", "*y*"]), .cells(["z", ""])])
115 }
116
117 @Test func footnotes() {
118 let out = org("Text[^1] and more[^note].\n\n[^1]: First.\n[^note]: Second\n continued.\n")
119 #expect(nodes(out.tree, .footnoteReference).count == 2)
120 #expect(nodes(out.tree, .footnoteDefinition).count == 2)
121 #expect(out.text.hasSuffix("[fn:1] First.\n\n[fn:note] Second\ncontinued.\n"))
122 }
123
124 @Test func frontMatter() {
125 let out = org("""
126 ---
127 title: "A Note"
128 date: 2024-01-05
129 tags: [one, two/three]
130 aliases:
131 - First alias
132 - second
133 status: draft
134 nested:
135 a: 1
136 ---
137 Body.
138
139 """)
140 #expect(out.text == """
141 :PROPERTIES:
142 :ROAM_ALIASES: "First alias" second
143 :status: draft
144 :END:
145 #+title: A Note
146 #+date: 2024-01-05
147 #+filetags: :one:two_three:
148
149 Body.
150
151 """)
152 #expect(out.model.fileTags == ["one", "two_three"])
153 #expect(nodes(out.tree, .propertyDrawer).count == 1)
154 #expect(out.result.issues == [.frontMatter("nested")])
155 }
156
157 @Test func mathRuleHTMLAndComments() {
158 let out = org("$$\nE = mc^2\n$$\n\nInline $x^2$, not $5 or $6.\n\n***\n\n<!-- hidden -->\n\n<div>\n<b>x</b>\n</div>\n")
159 #expect(out.text == "\\[\nE = mc^2\n\\]\n\nInline \\(x^2\\), not $5 or $6.\n\n-----\n\n#+begin_comment\nhidden\n#+end_comment\n\n#+begin_export html\n<div>\n<b>x</b>\n</div>\n#+end_export\n")
160 #expect(nodes(out.tree, .latexFragment).count >= 1)
161 #expect(nodes(out.tree, .horizontalRule).count == 1)
162 }
163
164 @Test func hardBreaksAndEntities() {
165 let out = org("one \ntwo\\\nthree & —\n")
166 #expect(out.text == "one \\\\\ntwo \\\\\nthree & —\n")
167 #expect(nodes(out.tree, .lineBreak).count == 2)
168 }
169
170 @Test func paragraphLinesThatOrgWouldReadAsElements() {
171 // A continuation line can't start a list or a table in org; it joins the line above.
172 let out = org("Item count:\n2. is not a list\n| not a table\n")
173 #expect(out.text == "Item count: 2. is not a list | not a table\n")
174 #expect(nodes(out.tree, .plainList).isEmpty)
175 #expect(nodes(out.tree, .table).isEmpty)
176 }
177
178 @Test func headingInsideListIsBold() {
179 let out = org("- # Title\n")
180 #expect(out.text == "- *Title*\n")
181 #expect(out.model.headings.isEmpty)
182 }
183
184 // MARK: - Obsidian
185
186 @Test func wikilinksAndEmbeds() {
187 let out = org("See [[Other note]], [[Other note#Part|alias]], [[#Local]] and ![[pic.png|300]].\n", obsidian: true)
188 #expect(out.text == "See [[file:Other note.org][Other note]], [[file:Other note.org][alias]], #Local and [[file:pic.png]].\n")
189 #expect(out.result.issues == [.unresolvedLink("#Local")])
190 }
191
192 @Test func embeddedImageWidth() {
193 let out = org("![[pic.png|300]]\n", obsidian: true)
194 #expect(out.text == "#+attr_org: :width 300\n[[file:pic.png]]\n")
195 }
196
197 @Test func tagsGoToHeadingsAndFile() {
198 let out = org("#inbox note\n\n# Meeting #work #2024\nTalked about #project/alpha.\n", obsidian: true)
199 #expect(out.model.fileTags == ["inbox"])
200 #expect(out.model.headings.first?.localTags == ["work", "project_alpha"])
201 #expect(out.model.headings.first?.title == "Meeting #work #2024")
202 }
203
204 @Test func calloutsBecomeSpecialBlocks() {
205 let out = org("> [!warning]- Careful\n> Inside **it**.\n\n> [!example]\n> e.g.\n", obsidian: true)
206 #expect(out.text == "#+begin_warning\n*Careful*\n\nInside *it*.\n#+end_warning\n\n#+begin_callout-example\ne.g.\n#+end_callout-example\n")
207 #expect(nodes(out.tree, .block).count == 2)
208 }
209
210 @Test func taskDates() {
211 let out = org("- [ ] Pay 📅 2024-01-10 ⏳ 2024-01-08\n- [x] Paid ✅ 2024-01-09\n- [>] Moved\n- [ ] Weekly 🔁 every week\n", obsidian: true)
212 #expect(out.text == "- [ ] Pay DEADLINE: <2024-01-10 Wed> SCHEDULED: <2024-01-08 Mon>\n- [X] Paid CLOSED: [2024-01-09 Tue]\n- [ ] Moved\n- [ ] Weekly 🔁 every week\n")
213 #expect(nodes(out.tree, .timestamp).count == 3)
214 #expect(Set(out.result.issues) == [.taskStatus(">"), .recurrence])
215 }
216
217 @Test func highlightCommentAndBlockID() {
218 let out = org("A ==marked== word.\nLast line ^block-1\n\n%%\nhidden\n%%\n", obsidian: true)
219 #expect(out.text == "A *marked* word.\nLast line <<block-1>>\n\n#+begin_comment\nhidden\n#+end_comment\n")
220 #expect(nodes(out.tree, .target).count == 1)
221 }
222
223 @Test func fileNameIsTheFallbackTitle() {
224 #expect(org("Body\n", obsidian: true, title: "Note").text == "#+title: Note\n\nBody\n")
225 #expect(org("---\ntitle: Own\n---\nBody\n", obsidian: true, title: "Note").text == "#+title: Own\n\nBody\n")
226 }
227
228 @Test func headingFragments() {
229 let headings = MarkdownToOrg.parse("# Some *Heading*\n## Other: part\n", obsidian: false).headings
230 #expect(MarkdownToOrg.heading("some-heading", in: headings) == "Some /Heading/")
231 #expect(MarkdownToOrg.heading("Other: part", in: headings) == "Other: part")
232 #expect(MarkdownToOrg.heading("missing", in: headings) == nil)
233 }
234}