Tests/OrgCoreTests/MarkdownTests.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Tests/OrgCoreTests/MarkdownTests.swift

134 lines · 7085 bytes

15 symbols in this file
  1import Foundation
  2import OrgCore
  3import Testing
  4
  5struct MarkdownStructureTests {
  6    @Test func headingsSkipFencesAndFrontMatter() {
  7        let text = "---\ntitle: Notes\n# not a heading\n---\n# One\n```swift\n# comment\n```\n## Two ##\n####### seven\n#tag\n   ### Three\n"
  8        let structure = Markdown.structure(text)
  9        #expect(structure.frontMatter?.format == .yaml)
 10        #expect(structure.frontMatter?.range == 0..<37)
 11        #expect(structure.fences.count == 1)
 12        #expect(structure.fences[0].language == "swift")
 13        #expect(structure.headings.map(\.title) == ["One", "Two", "Three"])
 14        #expect(structure.headings.map(\.level) == [1, 2, 3])
 15        #expect(structure.headings[0].start == 37)
 16        #expect(structure.headings[0].lineEnd == 43)
 17    }
 18
 19    @Test func fences() {
 20        let structure = Markdown.structure("~~~ {.python}\nx\n```\n~~~~\nafter\n````\nopen to the end\n```\n")
 21        #expect(structure.fences.count == 2)
 22        #expect(structure.fences[0].language == "python")
 23        #expect(structure.fences[0].range == 0..<25)
 24        #expect(structure.fences[0].body == 14..<20)
 25        // Unclosed, and a shorter run doesn't close it.
 26        #expect(structure.fences[1].closing == nil)
 27        #expect(structure.fences[1].range.upperBound == 56)
 28        // Backticks in a backtick fence's info string make it inline code.
 29        #expect(Markdown.structure("``` a`b\n").fences.isEmpty)
 30    }
 31
 32    @Test func closingHashesAndEmptyHeadings() {
 33        let headings = Markdown.structure("# a # b ##\n#\n## #\n# c#\n").headings
 34        #expect(headings.map(\.title) == ["a # b", "", "", "c#"])
 35    }
 36
 37    @Test func titles() {
 38        #expect(Markdown.title("---\ntitle: \"A note\"\n---\n# Heading\n") == "A note")
 39        #expect(Markdown.title("+++\ntitle      = 'TOML note'\n+++\n") == "TOML note")
 40        #expect(Markdown.title("Intro\n\n## First\n") == "First")
 41        #expect(Markdown.title("---\ndate: 2026\n---\n# From the heading\n") == "From the heading")
 42        #expect(Markdown.title("no headings") == nil)
 43        // A `---` line alone isn't front matter.
 44        #expect(Markdown.structure("---\ntext\n").frontMatter == nil)
 45    }
 46
 47    /// Updating the structure through an edit gives what reading the new text does.
 48    @Test func editsMatchAFreshRead() {
 49        let pieces = ["# A\n", "## B\n", "text\n", "```\n", "~~~ py\n", "# in fence?\n", "---\n", "+++\n", "\n", "#", "x", "`", " ", "\n"]
 50        var generator = SeededGenerator(state: testSeed(159))
 51        var text = "Intro\n# One\nbody\n```\n# code\n```\n## Two\nmore\n"
 52        var structure = Markdown.structure(text)
 53        for _ in 0..<2_000 {
 54            let old = Array(text.utf16)
 55            let lower = Int.random(in: 0...old.count, using: &generator)
 56            let upper = min(old.count, lower + Int.random(in: 0...6, using: &generator))
 57            let replacement = Int.random(in: 0...2, using: &generator) == 0 ? "" : pieces.randomElement(using: &generator)!
 58            var new = old
 59            new.replaceSubrange(lower..<upper, with: Array(replacement.utf16))
 60            let edit = TextEdit(range: lower..<upper, replacement: replacement)
 61            structure = Markdown.structure(structure, old: old, new: new, after: edit) ?? Markdown.structure(new)
 62            text = String(decoding: new, as: UTF16.self)
 63            #expect(structure == Markdown.structure(new), "\(text.debugDescription) after \(edit)")
 64            if structure != Markdown.structure(new) { return }
 65        }
 66    }
 67
 68    @Test func paths() {
 69        #expect(Markdown.isPath("/a/b.md") && Markdown.isPath("x.MARKDOWN") && !Markdown.isPath("x.org"))
 70        #expect(Markdown.isPlainTextPath("notes.txt") && !Markdown.isPlainTextPath("notes.md"))
 71    }
 72}
 73
 74struct MarkdownSpanTests {
 75    func spans(_ line: String) -> [String] {
 76        let u = Array(line.utf16)
 77        return Markdown.lineSpans(u, 0, u.count).map { span in
 78            "\(span.kind):" + String(decoding: u[span.range], as: UTF16.self)
 79        }
 80    }
 81
 82    @Test func emphasis() {
 83        #expect(spans("a **b** _c_ ~~d~~") == [
 84            "bold:**b**", "marker:**", "marker:**", "italic:_c_", "marker:_", "marker:_", "strikeThrough:~~d~~", "marker:~~", "marker:~~",
 85        ])
 86        #expect(spans("***both***") == ["italic:***both***", "marker:*", "bold:**both**", "marker:**", "marker:**", "marker:*"])
 87        // Intraword underscores and spaced stars aren't emphasis.
 88        #expect(spans("snake_case_name and 2 * 3 * 4").isEmpty)
 89    }
 90
 91    @Test func codeHidesMarkup() {
 92        #expect(spans("`*not*` and ``a ` b``") == ["code:`*not*`", "marker:`", "marker:`", "code:``a ` b``", "marker:``", "marker:``"])
 93        #expect(spans("an `unclosed *span*").contains("italic:*span*"))
 94    }
 95
 96    @Test func links() {
 97        #expect(spans("[a *b*](http://x.y/(z)) ![img](p.png)") == [
 98            "linkMarkup:[", "link:a *b*", "italic:*b*", "marker:*", "marker:*", "linkMarkup:](http://x.y/(z))",
 99            "linkMarkup:![", "link:img", "linkMarkup:](p.png)",
100        ])
101        #expect(spans("<https://example.com> and https://a.b/c_d_e.") == [
102            "linkMarkup:<", "link:https://example.com", "linkMarkup:>", "link:https://a.b/c_d_e",
103        ])
104        #expect(spans("[ref]: https://example.com \"Title\"") == ["linkMarkup:[ref]: ", "link:https://example.com"])
105        #expect(spans("[text][ref]") == ["linkMarkup:[", "link:text", "linkMarkup:][ref]"])
106    }
107
108    @Test func lines() {
109        #expect(spans("## Title with `code`") == ["heading(level: 2):## Title with `code`", "code:`code`", "marker:`", "marker:`"])
110        #expect(spans("- [x] done") == ["marker:-", "checkbox:[x]"])
111        #expect(spans("  12. item") == ["marker:12."])
112        #expect(spans("> > quoted *text*") == ["marker:>", "marker:>", "quote:quoted *text*", "italic:*text*", "marker:*", "marker:*"])
113        #expect(spans("* * *") == ["rule:* * *"])
114        #expect(spans("| a | b |") == ["table:| a | b |"])
115        #expect(spans("<!-- note --> after") == ["comment:<!-- note -->"])
116    }
117}
118
119struct OrgOnlyCommandTests {
120    @Test func refusedOutsideOrg() {
121        for id in ["org.todo.cycle", "org.meta-return", "org.link.insert", "app.refile", "app.archive", "app.attach.attach", "app.export.html",
122                   "app.table-import", "app.clock.in", "app.node.insert", "app.crypt.encrypt-entry", "app.export-dialog"] {
123            #expect(OrgOnlyCommands.refuses(id, markdown: true), "\(id)")
124            #expect(OrgOnlyCommands.refuses(id, markdown: false), "\(id)")
125        }
126        for id in ["org.cycle", "org.cycle-global", "org.fold.toggle", "org.fold.close-all"] {
127            #expect(!OrgOnlyCommands.refuses(id, markdown: true), "\(id)")
128            #expect(OrgOnlyCommands.refuses(id, markdown: false), "\(id)")
129        }
130        for id in ["app.save", "app.agenda", "app.capture", "app.search", "app.word-count", "app.export.icalendar-agenda", "edit.undo", "editor.toggle-truncate-lines"] {
131            #expect(!OrgOnlyCommands.refuses(id, markdown: true), "\(id)")
132        }
133    }
134}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form