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
118}) 118})
119``` 119```
120 120
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
121### Title and heading level 133### Title and heading level
122 134
123Two presentation knobs, both defaulting to how Hutch rendered: 135Two presentation knobs, both defaulting to how Hutch rendered:
Sources/OrgSwift/AST/OrgAttributedStringRenderer.swift +13
@@ -58,6 +58,11 @@ public struct OrgAttributedStringRenderer: Sendable {
58 case .lineBreak: 58 case .lineBreak:
59 result += AttributedString("\n") 59 result += AttributedString("\n")
60 60
61 case .math(let math):
62 var part = AttributedString(math.source)
63 part[OrgMathAttribute.self] = math
64 result += part
65
61 case .timestamp(let stamp): 66 case .timestamp(let stamp):
62 var part = AttributedString(stamp.displayValue) 67 var part = AttributedString(stamp.displayValue)
63 part.orgRole = .timestamp 68 part.orgRole = .timestamp
@@ -144,9 +149,17 @@ public enum OrgRoleAttribute: AttributedStringKey {
144 public static let name = "orgRole" 149 public static let name = "orgRole"
145} 150}
146 151
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
147public extension AttributeScopes { 159public extension AttributeScopes {
148 struct OrgAttributes: AttributeScope { 160 struct OrgAttributes: AttributeScope {
149 public let orgRole: OrgRoleAttribute 161 public let orgRole: OrgRoleAttribute
162 public let orgMath: OrgMathAttribute
150 } 163 }
151 var org: OrgAttributes.Type { OrgAttributes.self } 164 var org: OrgAttributes.Type { OrgAttributes.self }
152} 165}
Sources/OrgSwift/AST/OrgDocument.swift +19
@@ -51,6 +51,9 @@ public indirect enum OrgElement: Sendable, Equatable {
51 case captioned(name: String?, caption: [OrgObject]?, content: OrgElement) 51 case captioned(name: String?, caption: [OrgObject]?, content: OrgElement)
52 case horizontalRule 52 case horizontalRule
53 case footnoteDefinition(label: String, content: [OrgObject]) 53 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)
54} 57}
55 58
56public struct OrgHeading: Sendable, Equatable { 59public struct OrgHeading: Sendable, Equatable {
@@ -196,6 +199,22 @@ public indirect enum OrgObject: Sendable, Equatable {
196 case timestamp(OrgTimestamp) 199 case timestamp(OrgTimestamp)
197 case superscript([OrgObject]) 200 case superscript([OrgObject])
198 case lineBreak 201 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 }
199} 218}
200 219
201public struct OrgLink: Sendable, Equatable { 220public struct OrgLink: Sendable, Equatable {
Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift +5
@@ -131,6 +131,9 @@ public struct OrgHTMLTreeRenderer {
131 case .horizontalRule: 131 case .horizontalRule:
132 return "<hr>\n" 132 return "<hr>\n"
133 133
134 case .latexBlock(let raw):
135 return "<pre>\(escapeHTML(raw))</pre>\n"
136
134 case .footnoteDefinition: 137 case .footnoteDefinition:
135 return "" // collected and emitted in the notes section 138 return "" // collected and emitted in the notes section
136 } 139 }
@@ -238,6 +241,7 @@ public struct OrgHTMLTreeRenderer {
238 case .verbatim(let text), .code(let text): html += "<code>" + escapeHTML(text) + "</code>" 241 case .verbatim(let text), .code(let text): html += "<code>" + escapeHTML(text) + "</code>"
239 case .superscript(let children): html += "<sup>" + renderInline(children, &notes) + "</sup>" 242 case .superscript(let children): html += "<sup>" + renderInline(children, &notes) + "</sup>"
240 case .lineBreak: html += "<br>" 243 case .lineBreak: html += "<br>"
244 case .math(let math): html += escapeHTML(math.source)
241 case .image(let figure): 245 case .image(let figure):
242 html += imageTag(figure, caption: nil) ?? escapeHTML(figure.alt ?? figure.source) 246 html += imageTag(figure, caption: nil) ?? escapeHTML(figure.alt ?? figure.source)
243 case .timestamp(let stamp): 247 case .timestamp(let stamp):
@@ -278,6 +282,7 @@ public struct OrgHTMLTreeRenderer {
278 case .link(let link): return link.description.map { plainText($0) } ?? resolver.displayValue(link.target) 282 case .link(let link): return link.description.map { plainText($0) } ?? resolver.displayValue(link.target)
279 case .timestamp(let stamp): return stamp.displayValue 283 case .timestamp(let stamp): return stamp.displayValue
280 case .image(let figure): return figure.alt ?? "" 284 case .image(let figure): return figure.alt ?? ""
285 case .math(let math): return math.source
281 case .footnoteRef, .lineBreak: return "" 286 case .footnoteRef, .lineBreak: return ""
282 } 287 }
283 }.joined() 288 }.joined()
Sources/OrgSwift/AST/OrgInlineParser.swift +72
@@ -24,6 +24,7 @@ extension OrgParser {
24 } 24 }
25 case .image(let figure): return figure.alt ?? "" 25 case .image(let figure): return figure.alt ?? ""
26 case .timestamp(let stamp): return stamp.displayValue 26 case .timestamp(let stamp): return stamp.displayValue
27 case .math(let math): return math.source
27 case .footnoteRef, .lineBreak: return "" 28 case .footnoteRef, .lineBreak: return ""
28 } 29 }
29 }.joined() 30 }.joined()
@@ -35,6 +36,7 @@ extension OrgParser {
35 var plain = "" 36 var plain = ""
36 let chars = Array(text) 37 let chars = Array(text)
37 var i = 0 38 var i = 0
39 let lastEnd = lastEnvironmentEnd(text)
38 40
39 func flushPlain() { 41 func flushPlain() {
40 if !plain.isEmpty { objects.append(.text(plain)); plain = "" } 42 if !plain.isEmpty { objects.append(.text(plain)); plain = "" }
@@ -50,6 +52,18 @@ extension OrgParser {
50 continue 52 continue
51 } 53 }
52 54
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
53 // Footnote reference: [fn:label] or [fn:label:inline] 67 // Footnote reference: [fn:label] or [fn:label:inline]
54 if chars[i] == "[", let note = scanFootnote(chars, from: i) { 68 if chars[i] == "[", let note = scanFootnote(chars, from: i) {
55 flushPlain() 69 flushPlain()
@@ -320,6 +334,64 @@ extension OrgParser {
320 description: [.text(address)])), start + address.count) 334 description: [.text(address)])), start + address.count)
321 } 335 }
322 336
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
323 private static func scanSuperscript(_ chars: [Character], from start: Int) -> (body: String, next: Int)? { 395 private static func scanSuperscript(_ chars: [Character], from start: Int) -> (body: String, next: Int)? {
324 var j = start + 1 396 var j = start + 1
325 guard j < chars.count else { return nil } 397 guard j < chars.count else { return nil }
Sources/OrgSwift/AST/OrgParser.swift +33
@@ -133,6 +133,14 @@ public enum OrgParser {
133 continue 133 continue
134 } 134 }
135 135
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
136 // Paragraph: consume until a blank line or a line that starts another construct. 144 // Paragraph: consume until a blank line or a line that starts another construct.
137 var paragraph: [String] = [] 145 var paragraph: [String] = []
138 while index < lines.count { 146 while index < lines.count {
@@ -163,9 +171,34 @@ public enum OrgParser {
163 if isTableLine(trimmed) { return true } 171 if isTableLine(trimmed) { return true }
164 if orgFootnoteDefinition(in: trimmed) != nil { return true } 172 if orgFootnoteDefinition(in: trimmed) != nil { return true }
165 if isListMarkerLine(trimmed), !isIndentedContinuationLine(raw) { return true } 173 if isListMarkerLine(trimmed), !isIndentedContinuationLine(raw) { return true }
174 if latexBegin(trimmed) != nil { return true }
166 return false 175 return false
167 } 176 }
168 177
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
169 // MARK: - Heading 202 // MARK: - Heading
170 203
171 private static func parseHeading(stars: Int, rest: String) -> OrgHeading { 204 private static func parseHeading(stars: Int, rest: String) -> OrgHeading {
Sources/OrgSwiftUI/OrgBlockView.swift +9 −5
@@ -18,16 +18,17 @@ struct OrgBlockListView: View {
18 18
19struct OrgBlockView: View { 19struct OrgBlockView: View {
20 let block: OrgBlock 20 let block: OrgBlock
21 @Environment(\.orgMath) private var math
21 22
22 var body: some View { 23 var body: some View {
23 switch block { 24 switch block {
24 case .heading(let text, let level): 25 case .heading(let text, let level):
25 Text(text) 26 orgText(text, math: math)
26 .padding(.top, level <= 2 ? 8 : 2) 27 .padding(.top, level <= 2 ? 8 : 2)
27 .fixedSize(horizontal: false, vertical: true) 28 .fixedSize(horizontal: false, vertical: true)
28 29
29 case .paragraph(let text): 30 case .paragraph(let text):
30 Text(text) 31 orgText(text, math: math)
31 .fixedSize(horizontal: false, vertical: true) 32 .fixedSize(horizontal: false, vertical: true)
32 33
33 case .code(let code): 34 case .code(let code):
@@ -60,7 +61,7 @@ struct OrgBlockView: View {
60 // Verse keeps its line breaks; that is the whole point of the block. 61 // Verse keeps its line breaks; that is the whole point of the block.
61 VStack(alignment: .leading, spacing: 0) { 62 VStack(alignment: .leading, spacing: 0) {
62 ForEach(Array(lines.enumerated()), id: \.offset) { _, line in 63 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)
64 } 65 }
65 } 66 }
66 67
@@ -89,7 +90,7 @@ struct OrgBlockView: View {
89 } 90 }
90 .accessibilityLabel(alt) 91 .accessibilityLabel(alt)
91 if let caption { 92 if let caption {
92 Text(caption).foregroundStyle(.secondary) 93 orgText(caption, math: math).foregroundStyle(.secondary)
93 } 94 }
94 } 95 }
95 96
@@ -100,12 +101,15 @@ struct OrgBlockView: View {
100 VStack(alignment: .leading, spacing: 4) { 101 VStack(alignment: .leading, spacing: 4) {
101 OrgBlockListView(blocks: blocks) 102 OrgBlockListView(blocks: blocks)
102 if let caption { 103 if let caption {
103 Text(caption).foregroundStyle(.secondary) 104 orgText(caption, math: math).foregroundStyle(.secondary)
104 } 105 }
105 } 106 }
106 107
107 case .rule: 108 case .rule:
108 Divider() 109 Divider()
110
111 case .math(let expression):
112 OrgMathBlockView(math: expression)
109 } 113 }
110 } 114 }
111} 115}
Sources/OrgSwiftUI/OrgLayout.swift +2
@@ -35,6 +35,8 @@ indirect enum OrgBlock: Identifiable {
35 case badges([OrgBadge]) 35 case badges([OrgBadge])
36 case captioned(caption: AttributedString?, blocks: [OrgBlock]) 36 case captioned(caption: AttributedString?, blocks: [OrgBlock])
37 case rule 37 case rule
38 /// A LaTeX block, or a paragraph that is one display expression and nothing else.
39 case math(OrgMath)
38 40
39 /// Positional identity. Blocks are rebuilt wholesale when the source changes, so their 41 /// Positional identity. Blocks are rebuilt wholesale when the source changes, so their
40 /// index in the layout is stable for as long as the layout is. 42 /// index in the layout is stable for as long as the layout is.
Sources/OrgSwiftUI/OrgLayoutBuilder.swift +14
@@ -66,6 +66,7 @@ struct OrgLayoutBuilder {
66 66
67 case .paragraph(let objects): 67 case .paragraph(let objects):
68 if let badges = badgeRow(objects) { return [.badges(badges)] } 68 if let badges = badgeRow(objects) { return [.badges(badges)] }
69 if let math = displayMath(objects) { return [.math(math)] }
69 return [.paragraph(text(objects, &notes))] 70 return [.paragraph(text(objects, &notes))]
70 71
71 case .list(let list): 72 case .list(let list):
@@ -111,7 +112,20 @@ struct OrgLayoutBuilder {
111 112
112 case .footnoteDefinition: 113 case .footnoteDefinition:
113 return [] // collected into the notes section 114 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 }
114 } 126 }
127 guard content.count == 1, case .math(let math) = content[0], math.display else { return nil }
128 return math
115 } 129 }
116 130
117 /// A paragraph holding nothing but images and image links is the badge row a README 131 /// 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
7/// hangs beside it — wrapped lines line up under the text, not under the bullet. 7/// hangs beside it — wrapped lines line up under the text, not under the bullet.
8struct OrgListView: View { 8struct OrgListView: View {
9 let list: OrgListLayout 9 let list: OrgListLayout
10 @Environment(\.orgMath) private var math
10 /// Ordered numbering restarts at each nesting level, as in org. 11 /// Ordered numbering restarts at each nesting level, as in org.
11 var body: some View { 12 var body: some View {
12 VStack(alignment: .leading, spacing: 6) { 13 VStack(alignment: .leading, spacing: 6) {
@@ -46,7 +47,7 @@ struct OrgListView: View {
46 private func descriptionItem(_ item: OrgListLayout.Item) -> some View { 47 private func descriptionItem(_ item: OrgListLayout.Item) -> some View {
47 VStack(alignment: .leading, spacing: 2) { 48 VStack(alignment: .leading, spacing: 2) {
48 if let term = item.term { 49 if let term = item.term {
49 Text(term).fixedSize(horizontal: false, vertical: true) 50 orgText(term, math: math).fixedSize(horizontal: false, vertical: true)
50 } 51 }
51 body(item).padding(.leading, 16) 52 body(item).padding(.leading, 16)
52 } 53 }
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
7/// one cell per column, so it is set on the first row and inherited down. 7/// one cell per column, so it is set on the first row and inherited down.
8struct OrgTableView: View { 8struct OrgTableView: View {
9 let table: OrgTableLayout 9 let table: OrgTableLayout
10 @Environment(\.orgMath) private var math
10 11
11 var body: some View { 12 var body: some View {
12 ScrollView(.horizontal, showsIndicators: false) { 13 ScrollView(.horizontal, showsIndicators: false) {
@@ -31,7 +32,7 @@ struct OrgTableView: View {
31 private func cell(_ row: OrgTableLayout.Row, column: Int, isHeader: Bool) -> some View { 32 private func cell(_ row: OrgTableLayout.Row, column: Int, isHeader: Bool) -> some View {
32 // Org tolerates ragged rows; a missing cell is empty, not a crash. 33 // Org tolerates ragged rows; a missing cell is empty, not a crash.
33 let text = column < row.cells.count ? row.cells[column].text : AttributedString() 34 let text = column < row.cells.count ? row.cells[column].text : AttributedString()
34 Text(text) 35 orgText(text, math: math)
35 .fontWeight(isHeader ? .semibold : .regular) 36 .fontWeight(isHeader ? .semibold : .regular)
36 .multilineTextAlignment(Self.textAlignment(table.alignment(column: column))) 37 .multilineTextAlignment(Self.textAlignment(table.alignment(column: column)))
37 .fixedSize(horizontal: false, vertical: true) 38 .fixedSize(horizontal: false, vertical: true)
Sources/OrgSwiftUI/OrgView.swift +11 −3
@@ -19,6 +19,7 @@ public struct OrgView: View {
19 private let styler: OrgCodeStyler 19 private let styler: OrgCodeStyler
20 private let keywords: OrgKeywordStyle 20 private let keywords: OrgKeywordStyle
21 private let textTransform: ((inout AttributedString) -> Void)? 21 private let textTransform: ((inout AttributedString) -> Void)?
22 private let math: OrgMathRenderer?
22 23
23 @Environment(\.colorScheme) private var colorScheme 24 @Environment(\.colorScheme) private var colorScheme
24 @State private var layout = OrgLayout() 25 @State private var layout = OrgLayout()
@@ -27,19 +28,24 @@ public struct OrgView: View {
27 /// headings, list terms, table cells, verse, captions and footnotes, never a code 28 /// headings, list terms, table cells, verse, captions and footnotes, never a code
28 /// block. Code and verbatim runs carry the `.code` inline presentation intent and 29 /// block. Code and verbatim runs carry the `.code` inline presentation intent and
29 /// links carry `.link`, so a transform can leave them alone. It is not part of the 30 /// 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.
31 public init( 35 public init(
32 _ source: String, 36 _ source: String,
33 options: OrgRenderOptions = .init(), 37 options: OrgRenderOptions = .init(),
34 styler: OrgCodeStyler = PlainOrgCodeStyler(), 38 styler: OrgCodeStyler = PlainOrgCodeStyler(),
35 keywords: OrgKeywordStyle = .init(), 39 keywords: OrgKeywordStyle = .init(),
36 textTransform: ((inout AttributedString) -> Void)? = nil 40 textTransform: ((inout AttributedString) -> Void)? = nil,
41 math: OrgMathRenderer? = nil
37 ) { 42 ) {
38 self.source = source 43 self.source = source
39 self.options = options 44 self.options = options
40 self.styler = styler 45 self.styler = styler
41 self.keywords = keywords 46 self.keywords = keywords
42 self.textTransform = textTransform 47 self.textTransform = textTransform
48 self.math = math
43 } 49 }
44 50
45 public var body: some View { 51 public var body: some View {
@@ -50,6 +56,7 @@ public struct OrgView: View {
50 } 56 }
51 } 57 }
52 .frame(maxWidth: .infinity, alignment: .leading) 58 .frame(maxWidth: .infinity, alignment: .leading)
59 .environment(\.orgMath, math)
53 .textSelection(.enabled) 60 .textSelection(.enabled)
54 .task(id: LayoutKey(source: source, colorScheme: colorScheme)) { 61 .task(id: LayoutKey(source: source, colorScheme: colorScheme)) {
55 layout = OrgLayoutBuilder(options: options, styler: styler, keywords: keywords, 62 layout = OrgLayoutBuilder(options: options, styler: styler, keywords: keywords,
@@ -69,6 +76,7 @@ private struct LayoutKey: Equatable {
69/// The notes section org's exporter puts at the end of a document. 76/// The notes section org's exporter puts at the end of a document.
70struct OrgFootnotesView: View { 77struct OrgFootnotesView: View {
71 let footnotes: [OrgFootnote] 78 let footnotes: [OrgFootnote]
79 @Environment(\.orgMath) private var math
72 80
73 var body: some View { 81 var body: some View {
74 VStack(alignment: .leading, spacing: 6) { 82 VStack(alignment: .leading, spacing: 6) {
@@ -79,7 +87,7 @@ struct OrgFootnotesView: View {
79 .font(.footnote) 87 .font(.footnote)
80 .monospacedDigit() 88 .monospacedDigit()
81 .foregroundStyle(.secondary) 89 .foregroundStyle(.secondary)
82 Text(note.text) 90 orgText(note.text, math: math)
83 .fixedSize(horizontal: false, vertical: true) 91 .fixedSize(horizontal: false, vertical: true)
84 .frame(maxWidth: .infinity, alignment: .leading) 92 .frame(maxWidth: .infinity, alignment: .leading)
85 } 93 }
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}