krz/org-swift

A dependency-free Swift library that renders org-mode to sanitized HTML. html library org-mode swift

Commit 4e5394edba

4e5394edba09d77f07aa0ff603164920361d1165

parent: fa46c3f157

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-16 01:04 UTC

LaTeX fragments and blocks

$…$, $$…$$, \(…\), \[…\] and inline \begin{…}…\end{…} parse to
OrgObject.math, found as go-org finds them (the first closing pair later
in the run), with org's border rule keeping "$5 and $10" prose. A
\begin{name} line through its \end{name} line is OrgElement.latexBlock.
HTML and AttributedString show the source; the attributed run carries
OrgMathAttribute. OrgView(…, math:) draws each expression as a Text, or
keeps the source on nil; a paragraph that is one display expression and
a LaTeX block lay out centred as their own block.

Ref krz/gitbay-ios#40

Layout: unified · split

README.md +12
@@ -118,6 +118,18 @@ OrgView(orgSource, options: options, textTransform: { text in
118118})
119119```
120120
121LaTeX fragments (`$…$`, `$$…$$`, `\(…\)`, `\[…\]`, `\begin{…}…\end{…}`) and
122`\begin{…}` blocks parse to `.math` objects and `.latexBlock` elements, found by
123go-org's rules with org's border rule for `$…$`. The HTML and `AttributedString`
124renderers show their source. `OrgView` draws them through `math`, which returns a
125`Text` (an image from a typesetter, say) or nil to keep the source:
126
127```swift
128OrgView(orgSource, options: options, math: { math in
129 typeset(math.tex, display: math.display).map { Text($0) }
130})
131```
132
121133### Title and heading level
122134
123135Two presentation knobs, both defaulting to how Hutch rendered:
Sources/OrgSwift/AST/OrgAttributedStringRenderer.swift +13
@@ -58,6 +58,11 @@ public struct OrgAttributedStringRenderer: Sendable {
5858 case .lineBreak:
5959 result += AttributedString("\n")
6060
61 case .math(let math):
62 var part = AttributedString(math.source)
63 part[OrgMathAttribute.self] = math
64 result += part
65
6166 case .timestamp(let stamp):
6267 var part = AttributedString(stamp.displayValue)
6368 part.orgRole = .timestamp
@@ -144,9 +149,17 @@ public enum OrgRoleAttribute: AttributedStringKey {
144149 public static let name = "orgRole"
145150}
146151
152/// The expression a run's text is the source of. A UI layer with a typesetter draws it in
153/// place of the text.
154public enum OrgMathAttribute: AttributedStringKey {
155 public typealias Value = OrgMath
156 public static let name = "orgMath"
157}
158
147159public extension AttributeScopes {
148160 struct OrgAttributes: AttributeScope {
149161 public let orgRole: OrgRoleAttribute
162 public let orgMath: OrgMathAttribute
150163 }
151164 var org: OrgAttributes.Type { OrgAttributes.self }
152165}
Sources/OrgSwift/AST/OrgDocument.swift +19
@@ -51,6 +51,9 @@ public indirect enum OrgElement: Sendable, Equatable {
5151 case captioned(name: String?, caption: [OrgObject]?, content: OrgElement)
5252 case horizontalRule
5353 case footnoteDefinition(label: String, content: [OrgObject])
54 /// `\begin{…}` and its `\end{…}` on lines of their own, with everything between: display
55 /// math, as org's exporter reads it.
56 case latexBlock(String)
5457}
5558
5659public struct OrgHeading: Sendable, Equatable {
@@ -196,6 +199,22 @@ public indirect enum OrgObject: Sendable, Equatable {
196199 case timestamp(OrgTimestamp)
197200 case superscript([OrgObject])
198201 case lineBreak
202 /// A LaTeX fragment: `$…$`, `$$…$$`, `\(…\)`, `\[…\]` or an inline `\begin{…}…\end{…}`.
203 case math(OrgMath)
204}
205
206/// TeX to typeset. `source` is the fragment as written, delimiters included, for a renderer
207/// with no typesetter to show; an environment's `tex` is its whole source.
208public struct OrgMath: Sendable, Hashable {
209 public var tex: String
210 public var display: Bool
211 public var source: String
212
213 public init(tex: String, display: Bool, source: String) {
214 self.tex = tex
215 self.display = display
216 self.source = source
217 }
199218}
200219
201220public struct OrgLink: Sendable, Equatable {
Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift +5
@@ -131,6 +131,9 @@ public struct OrgHTMLTreeRenderer {
131131 case .horizontalRule:
132132 return "<hr>\n"
133133
134 case .latexBlock(let raw):
135 return "<pre>\(escapeHTML(raw))</pre>\n"
136
134137 case .footnoteDefinition:
135138 return "" // collected and emitted in the notes section
136139 }
@@ -238,6 +241,7 @@ public struct OrgHTMLTreeRenderer {
238241 case .verbatim(let text), .code(let text): html += "<code>" + escapeHTML(text) + "</code>"
239242 case .superscript(let children): html += "<sup>" + renderInline(children, &notes) + "</sup>"
240243 case .lineBreak: html += "<br>"
244 case .math(let math): html += escapeHTML(math.source)
241245 case .image(let figure):
242246 html += imageTag(figure, caption: nil) ?? escapeHTML(figure.alt ?? figure.source)
243247 case .timestamp(let stamp):
@@ -278,6 +282,7 @@ public struct OrgHTMLTreeRenderer {
278282 case .link(let link): return link.description.map { plainText($0) } ?? resolver.displayValue(link.target)
279283 case .timestamp(let stamp): return stamp.displayValue
280284 case .image(let figure): return figure.alt ?? ""
285 case .math(let math): return math.source
281286 case .footnoteRef, .lineBreak: return ""
282287 }
283288 }.joined()
Sources/OrgSwift/AST/OrgInlineParser.swift +72
@@ -24,6 +24,7 @@ extension OrgParser {
2424 }
2525 case .image(let figure): return figure.alt ?? ""
2626 case .timestamp(let stamp): return stamp.displayValue
27 case .math(let math): return math.source
2728 case .footnoteRef, .lineBreak: return ""
2829 }
2930 }.joined()
@@ -35,6 +36,7 @@ extension OrgParser {
3536 var plain = ""
3637 let chars = Array(text)
3738 var i = 0
39 let lastEnd = lastEnvironmentEnd(text)
3840
3941 func flushPlain() {
4042 if !plain.isEmpty { objects.append(.text(plain)); plain = "" }
@@ -50,6 +52,18 @@ extension OrgParser {
5052 continue
5153 }
5254
55 // LaTeX fragments: $…$, $$…$$, \(…\), \[…\], \begin{…}…\end{…}
56 if chars[i] == "$" || chars[i] == "\\", let math = scanMath(chars, from: i, lastEnd: lastEnd) {
57 if case .text(let text) = math.object {
58 plain += text
59 } else {
60 flushPlain()
61 objects.append(math.object)
62 }
63 i = math.next
64 continue
65 }
66
5367 // Footnote reference: [fn:label] or [fn:label:inline]
5468 if chars[i] == "[", let note = scanFootnote(chars, from: i) {
5569 flushPlain()
@@ -320,6 +334,64 @@ extension OrgParser {
320334 description: [.text(address)])), start + address.count)
321335 }
322336
337 /// A LaTeX fragment, found as go-org finds one: the first closing pair after the opener,
338 /// anywhere later in the run. A `$…$` whose body starts or ends with a space is consumed
339 /// but stays prose, org's rule for keeping "$5 and $10" a sentence.
340 private static func scanMath(
341 _ chars: [Character], from start: Int, lastEnd: (offset: Int, name: String)?
342 ) -> (object: OrgObject, next: Int)? {
343 guard start + 2 < chars.count else { return nil }
344 let opener: String
345 switch (chars[start], chars[start + 1]) {
346 case ("$", "$"): opener = "$$"
347 case ("$", _): opener = "$"
348 case ("\\", "("): opener = #"\("#
349 case ("\\", "["): opener = #"\["#
350 default: return scanEnvironment(chars, from: start, lastEnd: lastEnd)
351 }
352 let closer = ["$$": "$$", "$": "$", #"\("#: #"\)"#, #"\["#: #"\]"#][opener]!
353 let body = start + opener.count
354 guard let close = firstIndex(of: Array(closer), in: chars, from: body) else { return nil }
355 let tex = String(chars[body..<close])
356 let source = opener + tex + closer
357 let next = close + closer.count
358 if opener == "$", tex.first?.isWhitespace != false || tex.last?.isWhitespace != false {
359 return (.text(source), next)
360 }
361 let display = opener != "$" && opener != #"\("#
362 return (.math(OrgMath(tex: tex, display: display, source: source)), next)
363 }
364
365 /// `\begin{name}…\end{name}` inline. go-org matches the last `\end{…}` greedily and
366 /// requires its name to be the opener's, then ends the fragment at the first `\end{name}`.
367 private static func scanEnvironment(
368 _ chars: [Character], from start: Int, lastEnd: (offset: Int, name: String)?
369 ) -> (object: OrgObject, next: Int)? {
370 guard let lastEnd, lastEnd.offset > start,
371 Array(chars[start...].prefix(7)) == Array(#"\begin{"#) else { return nil }
372 let name = chars[(start + 7)...].prefix(while: { $0.isLetter || $0.isNumber || $0 == "_" })
373 guard !name.isEmpty, start + 7 + name.count < chars.count, chars[start + 7 + name.count] == "}",
374 String(name) == lastEnd.name else { return nil }
375 let closer = Array(#"\end{"# + String(name) + "}")
376 guard let close = firstIndex(of: closer, in: chars, from: start + 8 + name.count) else { return nil }
377 let source = String(chars[start..<(close + closer.count)])
378 return (.math(OrgMath(tex: source, display: true, source: source)), close + closer.count)
379 }
380
381 /// Where the run's last `\end{name}` starts, in characters, and its name.
382 private static func lastEnvironmentEnd(_ text: String) -> (offset: Int, name: String)? {
383 guard text.contains(#"\end{"#), let last = text.matches(of: /\\end\{(\w+)\}/).last else { return nil }
384 return (text.distance(from: text.startIndex, to: last.range.lowerBound), String(last.1))
385 }
386
387 private static func firstIndex(of needle: [Character], in chars: [Character], from start: Int) -> Int? {
388 guard !needle.isEmpty, chars.count >= needle.count, start <= chars.count - needle.count else { return nil }
389 for i in start...(chars.count - needle.count) where chars[i] == needle[0] {
390 if Array(chars[i..<(i + needle.count)]) == needle { return i }
391 }
392 return nil
393 }
394
323395 private static func scanSuperscript(_ chars: [Character], from start: Int) -> (body: String, next: Int)? {
324396 var j = start + 1
325397 guard j < chars.count else { return nil }
Sources/OrgSwift/AST/OrgParser.swift +33
@@ -133,6 +133,14 @@ public enum OrgParser {
133133 continue
134134 }
135135
136 // A LaTeX block: \begin{name} alone on its line, through the matching \end{name}.
137 if let (raw, next) = parseLatexBlock(lines, from: index) {
138 append(.latexBlock(raw))
139 index = next
140 flushPending()
141 continue
142 }
143
136144 // Paragraph: consume until a blank line or a line that starts another construct.
137145 var paragraph: [String] = []
138146 while index < lines.count {
@@ -163,9 +171,34 @@ public enum OrgParser {
163171 if isTableLine(trimmed) { return true }
164172 if orgFootnoteDefinition(in: trimmed) != nil { return true }
165173 if isListMarkerLine(trimmed), !isIndentedContinuationLine(raw) { return true }
174 if latexBegin(trimmed) != nil { return true }
166175 return false
167176 }
168177
178 // MARK: - LaTeX block
179
180 /// The environment a `\begin{name}` line opens, as go-org's lexer reads it (any case).
181 private static func latexBegin(_ trimmed: String) -> String? {
182 trimmed.firstMatch(of: /^\\begin\{([^}]+)\}$/.ignoresCase()).map { String($0.1).lowercased() }
183 }
184
185 private static func parseLatexBlock(_ lines: [String], from start: Int) -> (String, Int)? {
186 let opener = lines[start]
187 guard let name = latexBegin(opener.trimmingCharacters(in: .whitespaces)) else { return nil }
188 let indent = leadingWidth(opener)
189 var raw = [dropLeading(opener, indent)]
190 for index in (start + 1)..<lines.count {
191 let line = lines[index]
192 raw.append(dropLeading(line, min(indent, leadingWidth(line))))
193 let trimmed = line.trimmingCharacters(in: .whitespaces)
194 if let end = trimmed.firstMatch(of: /^\\end\{([^}]+)\}$/.ignoresCase()),
195 String(end.1).lowercased() == name {
196 return (raw.joined(separator: "\n"), index + 1)
197 }
198 }
199 return nil
200 }
201
169202 // MARK: - Heading
170203
171204 private static func parseHeading(stars: Int, rest: String) -> OrgHeading {
Sources/OrgSwiftUI/OrgBlockView.swift +9 −5
@@ -18,16 +18,17 @@ struct OrgBlockListView: View {
1818
1919struct OrgBlockView: View {
2020 let block: OrgBlock
21 @Environment(\.orgMath) private var math
2122
2223 var body: some View {
2324 switch block {
2425 case .heading(let text, let level):
25 Text(text)
26 orgText(text, math: math)
2627 .padding(.top, level <= 2 ? 8 : 2)
2728 .fixedSize(horizontal: false, vertical: true)
2829
2930 case .paragraph(let text):
30 Text(text)
31 orgText(text, math: math)
3132 .fixedSize(horizontal: false, vertical: true)
3233
3334 case .code(let code):
@@ -60,7 +61,7 @@ struct OrgBlockView: View {
6061 // Verse keeps its line breaks; that is the whole point of the block.
6162 VStack(alignment: .leading, spacing: 0) {
6263 ForEach(Array(lines.enumerated()), id: \.offset) { _, line in
63 Text(line).fixedSize(horizontal: false, vertical: true)
64 orgText(line, math: math).fixedSize(horizontal: false, vertical: true)
6465 }
6566 }
6667
@@ -89,7 +90,7 @@ struct OrgBlockView: View {
8990 }
9091 .accessibilityLabel(alt)
9192 if let caption {
92 Text(caption).foregroundStyle(.secondary)
93 orgText(caption, math: math).foregroundStyle(.secondary)
9394 }
9495 }
9596
@@ -100,12 +101,15 @@ struct OrgBlockView: View {
100101 VStack(alignment: .leading, spacing: 4) {
101102 OrgBlockListView(blocks: blocks)
102103 if let caption {
103 Text(caption).foregroundStyle(.secondary)
104 orgText(caption, math: math).foregroundStyle(.secondary)
104105 }
105106 }
106107
107108 case .rule:
108109 Divider()
110
111 case .math(let expression):
112 OrgMathBlockView(math: expression)
109113 }
110114 }
111115}
Sources/OrgSwiftUI/OrgLayout.swift +2
@@ -35,6 +35,8 @@ indirect enum OrgBlock: Identifiable {
3535 case badges([OrgBadge])
3636 case captioned(caption: AttributedString?, blocks: [OrgBlock])
3737 case rule
38 /// A LaTeX block, or a paragraph that is one display expression and nothing else.
39 case math(OrgMath)
3840
3941 /// Positional identity. Blocks are rebuilt wholesale when the source changes, so their
4042 /// index in the layout is stable for as long as the layout is.
Sources/OrgSwiftUI/OrgLayoutBuilder.swift +14
@@ -66,6 +66,7 @@ struct OrgLayoutBuilder {
6666
6767 case .paragraph(let objects):
6868 if let badges = badgeRow(objects) { return [.badges(badges)] }
69 if let math = displayMath(objects) { return [.math(math)] }
6970 return [.paragraph(text(objects, &notes))]
7071
7172 case .list(let list):
@@ -111,7 +112,20 @@ struct OrgLayoutBuilder {
111112
112113 case .footnoteDefinition:
113114 return [] // collected into the notes section
115
116 case .latexBlock(let raw):
117 return [.math(OrgMath(tex: raw, display: true, source: raw))]
118 }
119 }
120
121 /// The one display expression a paragraph holds, `\[…\]` on a line of its own being the
122 /// usual way to write a displayed equation.
123 private func displayMath(_ objects: [OrgObject]) -> OrgMath? {
124 let content = objects.filter {
125 if case .text(let text) = $0 { !text.trimmingCharacters(in: .whitespaces).isEmpty } else { true }
114126 }
127 guard content.count == 1, case .math(let math) = content[0], math.display else { return nil }
128 return math
115129 }
116130
117131 /// A paragraph holding nothing but images and image links is the badge row a README
Sources/OrgSwiftUI/OrgListView.swift +2 −1
@@ -7,6 +7,7 @@ import SwiftUI
77/// hangs beside it — wrapped lines line up under the text, not under the bullet.
88struct OrgListView: View {
99 let list: OrgListLayout
10 @Environment(\.orgMath) private var math
1011 /// Ordered numbering restarts at each nesting level, as in org.
1112 var body: some View {
1213 VStack(alignment: .leading, spacing: 6) {
@@ -46,7 +47,7 @@ struct OrgListView: View {
4647 private func descriptionItem(_ item: OrgListLayout.Item) -> some View {
4748 VStack(alignment: .leading, spacing: 2) {
4849 if let term = item.term {
49 Text(term).fixedSize(horizontal: false, vertical: true)
50 orgText(term, math: math).fixedSize(horizontal: false, vertical: true)
5051 }
5152 body(item).padding(.leading, 16)
5253 }
Sources/OrgSwiftUI/OrgMathText.swift added +62
@@ -0,0 +1,62 @@
1import OrgSwift
2import SwiftUI
3
4/// Draws one TeX expression for ``OrgView``: a `Text` holding it, typically an image set on
5/// the baseline, or nil to show the source as written.
6public typealias OrgMathRenderer = @MainActor (OrgMath) -> Text?
7
8private struct OrgMathKey: EnvironmentKey {
9 static let defaultValue: OrgMathRenderer? = nil
10}
11
12extension EnvironmentValues {
13 var orgMath: OrgMathRenderer? {
14 get { self[OrgMathKey.self] }
15 set { self[OrgMathKey.self] = newValue }
16 }
17}
18
19/// A styled run as `Text`, each math run drawn by `math` where it can be. Two identical
20/// expressions side by side share one run, so a run holding its source k times draws k.
21@MainActor
22func orgText(_ string: AttributedString, math: OrgMathRenderer?) -> Text {
23 guard let math, string.runs.contains(where: { $0[OrgMathAttribute.self] != nil }) else {
24 return Text(string)
25 }
26 var result = Text(verbatim: "")
27 for run in string.runs {
28 let piece = AttributedString(string[run.range])
29 guard let expression = run[OrgMathAttribute.self], let drawn = math(expression) else {
30 result = Text("\(result)\(Text(piece))")
31 continue
32 }
33 let count = max(1, piece.characters.count / max(1, expression.source.count))
34 for _ in 0..<count { result = Text("\(result)\(drawn)") }
35 }
36 return result
37}
38
39/// Display math on its own: centred, scrolling sideways when wider than the column, or the
40/// source as a code block where nothing draws it.
41struct OrgMathBlockView: View {
42 let math: OrgMath
43 @Environment(\.orgMath) private var renderer
44
45 var body: some View {
46 if let drawn = renderer?(math) {
47 ViewThatFits(in: .horizontal) {
48 drawn.frame(maxWidth: .infinity)
49 ScrollView(.horizontal, showsIndicators: false) { drawn }
50 }
51 .padding(.vertical, 4)
52 } else {
53 ScrollView(.horizontal) {
54 Text(math.source)
55 .font(.system(.footnote, design: .monospaced))
56 .textSelection(.enabled)
57 .padding(10)
58 }
59 .background(Color.secondary.opacity(0.12), in: RoundedRectangle(cornerRadius: 4))
60 }
61 }
62}
Sources/OrgSwiftUI/OrgTableView.swift +2 −1
@@ -7,6 +7,7 @@ import SwiftUI
77/// one cell per column, so it is set on the first row and inherited down.
88struct OrgTableView: View {
99 let table: OrgTableLayout
10 @Environment(\.orgMath) private var math
1011
1112 var body: some View {
1213 ScrollView(.horizontal, showsIndicators: false) {
@@ -31,7 +32,7 @@ struct OrgTableView: View {
3132 private func cell(_ row: OrgTableLayout.Row, column: Int, isHeader: Bool) -> some View {
3233 // Org tolerates ragged rows; a missing cell is empty, not a crash.
3334 let text = column < row.cells.count ? row.cells[column].text : AttributedString()
34 Text(text)
35 orgText(text, math: math)
3536 .fontWeight(isHeader ? .semibold : .regular)
3637 .multilineTextAlignment(Self.textAlignment(table.alignment(column: column)))
3738 .fixedSize(horizontal: false, vertical: true)
Sources/OrgSwiftUI/OrgView.swift +11 −3
@@ -19,6 +19,7 @@ public struct OrgView: View {
1919 private let styler: OrgCodeStyler
2020 private let keywords: OrgKeywordStyle
2121 private let textTransform: ((inout AttributedString) -> Void)?
22 private let math: OrgMathRenderer?
2223
2324 @Environment(\.colorScheme) private var colorScheme
2425 @State private var layout = OrgLayout()
@@ -27,19 +28,24 @@ public struct OrgView: View {
2728 /// headings, list terms, table cells, verse, captions and footnotes, never a code
2829 /// block. Code and verbatim runs carry the `.code` inline presentation intent and
2930 /// links carry `.link`, so a transform can leave them alone. It is not part of the
30 /// layout key; changing it alone does not re-render.
31 /// layout key; changing it alone does not re-render. A math run carries
32 /// ``OrgMathAttribute`` over its source text.
33 /// - Parameter math: draws each LaTeX fragment and block; nil, or a nil result, shows
34 /// the source as written.
3135 public init(
3236 _ source: String,
3337 options: OrgRenderOptions = .init(),
3438 styler: OrgCodeStyler = PlainOrgCodeStyler(),
3539 keywords: OrgKeywordStyle = .init(),
36 textTransform: ((inout AttributedString) -> Void)? = nil
40 textTransform: ((inout AttributedString) -> Void)? = nil,
41 math: OrgMathRenderer? = nil
3742 ) {
3843 self.source = source
3944 self.options = options
4045 self.styler = styler
4146 self.keywords = keywords
4247 self.textTransform = textTransform
48 self.math = math
4349 }
4450
4551 public var body: some View {
@@ -50,6 +56,7 @@ public struct OrgView: View {
5056 }
5157 }
5258 .frame(maxWidth: .infinity, alignment: .leading)
59 .environment(\.orgMath, math)
5360 .textSelection(.enabled)
5461 .task(id: LayoutKey(source: source, colorScheme: colorScheme)) {
5562 layout = OrgLayoutBuilder(options: options, styler: styler, keywords: keywords,
@@ -69,6 +76,7 @@ private struct LayoutKey: Equatable {
6976/// The notes section org's exporter puts at the end of a document.
7077struct OrgFootnotesView: View {
7178 let footnotes: [OrgFootnote]
79 @Environment(\.orgMath) private var math
7280
7381 var body: some View {
7482 VStack(alignment: .leading, spacing: 6) {
@@ -79,7 +87,7 @@ struct OrgFootnotesView: View {
7987 .font(.footnote)
8088 .monospacedDigit()
8189 .foregroundStyle(.secondary)
82 Text(note.text)
90 orgText(note.text, math: math)
8391 .fixedSize(horizontal: false, vertical: true)
8492 .frame(maxWidth: .infinity, alignment: .leading)
8593 }
Tests/OrgSwiftTests/MathTests.swift added +77
@@ -0,0 +1,77 @@
1import Foundation
2import Testing
3@testable import OrgSwift
4
5/// LaTeX fragments and blocks, read as go-org reads them, with org's
6/// border rule for `$…$` so "$5 and $10" stays prose.
7struct MathParseTests {
8
9 private func objects(_ source: String) -> [OrgObject] {
10 guard case .paragraph(let objects) = OrgParser.parse(source).elements.first else { return [] }
11 return objects
12 }
13
14 private func math(_ tex: String, _ display: Bool, _ source: String) -> OrgObject {
15 .math(OrgMath(tex: tex, display: display, source: source))
16 }
17
18 @Test func everyFragmentDelimiter() {
19 #expect(objects(#"a $x^2$ b"#) == [.text("a "), math("x^2", false, "$x^2$"), .text(" b")])
20 #expect(objects(#"a \(x\) b"#) == [.text("a "), math("x", false, #"\(x\)"#), .text(" b")])
21 #expect(objects(#"a \[x\] b"#) == [.text("a "), math("x", true, #"\[x\]"#), .text(" b")])
22 #expect(objects(#"a $$x$$ b"#) == [.text("a "), math("x", true, "$$x$$"), .text(" b")])
23 }
24
25 @Test func anInlineEnvironmentIsDisplayMathOfItsWholeSource() {
26 let source = #"\begin{matrix} a \end{matrix}"#
27 #expect(objects("so " + source + " ok") == [.text("so "), math(source, true, source), .text(" ok")])
28 }
29
30 @Test func anEnvironmentClosedByAnotherNameIsText() {
31 #expect(objects(#"\begin{a} x \end{b}"#) == [.text(#"\begin{a} x \end{b}"#)])
32 }
33
34 @Test func dollarsWithSpaceInsideTheirBordersAreProse() {
35 #expect(objects("$5 and $10") == [.text("$5 and $10")])
36 #expect(objects("$5 and $10 then $y$") == [.text("$5 and $10 then "), math("y", false, "$y$")])
37 }
38
39 @Test func anUnclosedDelimiterIsText() {
40 #expect(objects(#"cost $5"#) == [.text("cost $5")])
41 #expect(objects(#"a \( b"#) == [.text(#"a \( b"#)])
42 }
43
44 @Test func verbatimHoldsNoMath() {
45 #expect(objects("=$x$= and ~$y$~") == [.verbatim("$x$"), .text(" and "), .code("$y$")])
46 }
47
48 @Test func mathInsideEmphasis() {
49 #expect(objects("*bold $x$*") == [.bold([.text("bold "), math("x", false, "$x$")])])
50 }
51
52 @Test func aBeginLineToItsEndLineIsALatexBlock() {
53 let doc = OrgParser.parse("before\n\\begin{equation}\n x = 1\n\\end{equation}\nafter")
54 #expect(doc.elements == [
55 .paragraph([.text("before")]),
56 .latexBlock("\\begin{equation}\n x = 1\n\\end{equation}"),
57 .paragraph([.text("after")]),
58 ])
59 }
60
61 @Test func aBeginLineWithoutItsEndIsProse() {
62 let doc = OrgParser.parse("\\begin{equation}\nx = 1")
63 #expect(doc.elements.count == 1)
64 guard case .paragraph = doc.elements.first else {
65 Issue.record("expected a paragraph, got \(doc.elements)"); return
66 }
67 }
68
69 @Test func plainTextAndHTMLShowTheSource() {
70 let doc = OrgParser.parse("a $x$ b\n\n\\begin{align}\nx &< y\n\\end{align}")
71 #expect(OrgParser.plain(objects("a $x$ b")) == "a $x$ b")
72 let html = OrgHTMLTreeRenderer().render(doc)
73 #expect(html.contains("<p>a $x$ b</p>"))
74 #expect(html.contains("<pre>\\begin{align}\nx &amp;&lt; y\n\\end{align}</pre>"))
75 #expect(String(OrgAttributedStringRenderer().inline(objects("a $x$ b")).characters) == "a $x$ b")
76 }
77}
Tests/OrgSwiftUITests/OrgMathLayoutTests.swift added +54
@@ -0,0 +1,54 @@
1import Foundation
2import SwiftUI
3import Testing
4@testable import OrgSwift
5@testable import OrgSwiftUI
6
7@MainActor
8struct OrgMathLayoutTests {
9
10 private func layout(_ source: String) -> OrgLayout {
11 OrgLayoutBuilder(options: .init(), styler: PlainOrgCodeStyler(), keywords: .init())
12 .layout(OrgParser.parse(source))
13 }
14
15 @Test func aLatexBlockIsAMathBlock() {
16 let raw = "\\begin{align}\nx &= 1\n\\end{align}"
17 guard case .math(let math) = layout(raw).blocks.first else {
18 Issue.record("expected math, got \(layout(raw).blocks)"); return
19 }
20 #expect(math == OrgMath(tex: raw, display: true, source: raw))
21 }
22
23 @Test func aParagraphThatIsOneDisplayExpressionIsAMathBlock() {
24 guard case .math(let math) = layout(#"\[ x^2 \]"#).blocks.first else {
25 Issue.record("expected math"); return
26 }
27 #expect(math.tex == " x^2 ")
28 guard case .paragraph = layout(#"so \[ x^2 \]"#).blocks.first else {
29 Issue.record("prose around display math keeps the paragraph"); return
30 }
31 }
32
33 @Test func inlineMathIsItsSourceMarkedWithTheExpression() {
34 guard case .paragraph(let text) = layout("a $x$ b").blocks.first else {
35 Issue.record("expected a paragraph"); return
36 }
37 #expect(String(text.characters) == "a $x$ b")
38 let marked = text.runs.compactMap { $0[OrgMathAttribute.self] }
39 #expect(marked == [OrgMath(tex: "x", display: false, source: "$x$")])
40 }
41
42 @Test func orgTextDrawsEachExpression() {
43 guard case .paragraph(let text) = layout("$x$$x$ and $y$").blocks.first else {
44 Issue.record("expected a paragraph"); return
45 }
46 var drawn: [String] = []
47 _ = orgText(text) { math in
48 drawn.append(math.tex)
49 return Text(verbatim: "·")
50 }
51 #expect(drawn.sorted() == ["x", "y"])
52 _ = orgText(text, math: nil)
53 }
54}