LaTeX fragments and blocks !11

merged merged by cmc on 2026-10-16 02:03 UTC · krz/org-swift:latex-fragments into main

15 files changed, +484 −15

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 +98 −4
@@ -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,13 @@ extension OrgParser {
3536 var plain = ""
3637 let chars = Array(text)
3738 var i = 0
39 let lastEnd = lastEnvironmentEnd(text)
40 // A closer that is missing once is missing for every later opener of its kind.
41 var missing: Set<String> = []
42 func noteMissing<T>(_ closer: String) -> T? {
43 missing.insert(closer)
44 return nil
45 }
3846
3947 func flushPlain() {
4048 if !plain.isEmpty { objects.append(.text(plain)); plain = "" }
@@ -43,13 +51,25 @@ extension OrgParser {
4351 while i < chars.count {
4452 // Bracket links: [[target]] or [[target][description]]
4553 if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[",
46 let link = scanLink(chars, from: i) {
54 !missing.contains("]]"), let link = scanLink(chars, from: i) ?? noteMissing("]]") {
4755 flushPlain()
4856 objects.append(link.object)
4957 i = link.next
5058 continue
5159 }
5260
61 // LaTeX fragments: $…$, $$…$$, \(…\), \[…\], \begin{…}…\end{…}
62 if chars[i] == "$" || chars[i] == "\\", let math = scanMath(chars, from: i, lastEnd: lastEnd, missing: &missing) {
63 if case .text(let text) = math.object {
64 plain += text
65 } else {
66 flushPlain()
67 objects.append(math.object)
68 }
69 i = math.next
70 continue
71 }
72
5373 // Footnote reference: [fn:label] or [fn:label:inline]
5474 if chars[i] == "[", let note = scanFootnote(chars, from: i) {
5575 flushPlain()
@@ -246,6 +266,7 @@ extension OrgParser {
246266 }
247267
248268 private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
269 guard chars[start...].starts(with: "[fn:") else { return nil }
249270 let rest = String(chars[start...])
250271 guard let match = rest.firstMatch(of: /^\[fn:([A-Za-z0-9_-]+)(?::([^\]]*))?\]/) else { return nil }
251272 let label = String(match.1)
@@ -261,7 +282,8 @@ extension OrgParser {
261282 var j = start + 1
262283 var body = ""
263284 while j < chars.count, chars[j] != closing {
264 if chars[j] == "\n" { return nil }
285 // No timestamp is this long; stopping here keeps a run of brackets linear.
286 if chars[j] == "\n" || body.count > 64 { return nil }
265287 body.append(chars[j]); j += 1
266288 }
267289 guard j < chars.count else { return nil }
@@ -295,7 +317,10 @@ extension OrgParser {
295317 }
296318
297319 private static func scanBareURL(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
298 let rest = String(chars[start...])
320 // Matched on the word alone, after a cheap prefix test: copying the rest of the run
321 // at every `h` made long text quadratic.
322 guard chars[start...].starts(with: "http") else { return nil }
323 let rest = String(chars[start..<(chars[start...].firstIndex(where: \.isWhitespace) ?? chars.count)])
299324 guard let match = rest.firstMatch(of: /^https?:\/\/[^\s<>()\[\]]+/) else { return nil }
300325 var url = String(rest[match.range])
301326 while let last = url.last, ".,;:!?".contains(last) { url.removeLast() }
@@ -309,7 +334,11 @@ extension OrgParser {
309334 }
310335
311336 private static func scanEmail(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
312 let rest = String(chars[start...])
337 // An address needs its @ after a run of local-part characters; anything else is
338 // refused before the rest of the run is copied.
339 let local = chars[start...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || "._%+-".contains($0)) })
340 guard !local.isEmpty, start + local.count < chars.count, chars[start + local.count] == "@" else { return nil }
341 let rest = String(chars[start..<(chars[start...].firstIndex(where: \.isWhitespace) ?? chars.count)])
313342 guard let match = rest.firstMatch(of: /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/) else {
314343 return nil
315344 }
@@ -320,6 +349,71 @@ extension OrgParser {
320349 description: [.text(address)])), start + address.count)
321350 }
322351
352 /// A LaTeX fragment, found as go-org finds one: the first closing pair after the opener,
353 /// anywhere later in the run. A `$…$` whose body starts or ends with a space is consumed
354 /// but stays prose, org's rule for keeping "$5 and $10" a sentence.
355 private static func scanMath(
356 _ chars: [Character], from start: Int, lastEnd: (offset: Int, name: String)?,
357 missing: inout Set<String>
358 ) -> (object: OrgObject, next: Int)? {
359 guard start + 2 < chars.count else { return nil }
360 let opener: String
361 switch (chars[start], chars[start + 1]) {
362 case ("$", "$"): opener = "$$"
363 case ("$", _): opener = "$"
364 case ("\\", "("): opener = #"\("#
365 case ("\\", "["): opener = #"\["#
366 default: return scanEnvironment(chars, from: start, lastEnd: lastEnd)
367 }
368 let closer = ["$$": "$$", "$": "$", #"\("#: #"\)"#, #"\["#: #"\]"#][opener]!
369 let body = start + opener.count
370 guard !missing.contains(closer) else { return nil }
371 guard let close = firstIndex(of: Array(closer), in: chars, from: body) else {
372 missing.insert(closer)
373 return nil
374 }
375 let tex = String(chars[body..<close])
376 let source = opener + tex + closer
377 let next = close + closer.count
378 // The server's border test, which is ASCII space only: a no-break space is TeX.
379 let space: Set<Character> = [" ", "\t", "\n", "\r"]
380 if opener == "$", tex.first.map(space.contains) != false || tex.last.map(space.contains) != false {
381 return (.text(source), next)
382 }
383 let display = opener != "$" && opener != #"\("#
384 return (.math(OrgMath(tex: tex, display: display, source: source)), next)
385 }
386
387 /// `\begin{name}…\end{name}` inline. go-org matches the last `\end{…}` greedily and
388 /// requires its name to be the opener's, then ends the fragment at the first `\end{name}`.
389 private static func scanEnvironment(
390 _ chars: [Character], from start: Int, lastEnd: (offset: Int, name: String)?
391 ) -> (object: OrgObject, next: Int)? {
392 guard let lastEnd, lastEnd.offset > start,
393 Array(chars[start...].prefix(7)) == Array(#"\begin{"#) else { return nil }
394 let name = chars[(start + 7)...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber) || $0 == "_" })
395 guard !name.isEmpty, start + 7 + name.count < chars.count, chars[start + 7 + name.count] == "}",
396 String(name) == lastEnd.name else { return nil }
397 let closer = Array(#"\end{"# + String(name) + "}")
398 guard let close = firstIndex(of: closer, in: chars, from: start + 8 + name.count) else { return nil }
399 let source = String(chars[start..<(close + closer.count)])
400 return (.math(OrgMath(tex: source, display: true, source: source)), close + closer.count)
401 }
402
403 /// Where the run's last `\end{name}` starts, in characters, and its name.
404 private static func lastEnvironmentEnd(_ text: String) -> (offset: Int, name: String)? {
405 guard text.contains(#"\end{"#), let last = text.matches(of: /\\end\{(\w+)\}/).last else { return nil }
406 return (text.distance(from: text.startIndex, to: last.range.lowerBound), String(last.1))
407 }
408
409 private static func firstIndex(of needle: [Character], in chars: [Character], from start: Int) -> Int? {
410 guard !needle.isEmpty, chars.count >= needle.count, start <= chars.count - needle.count else { return nil }
411 for i in start...(chars.count - needle.count) where chars[i] == needle[0] {
412 if (1..<needle.count).allSatisfy({ chars[i + $0] == needle[$0] }) { return i }
413 }
414 return nil
415 }
416
323417 private static func scanSuperscript(_ chars: [Character], from start: Int) -> (body: String, next: Int)? {
324418 var j = start + 1
325419 guard j < chars.count else { return nil }
Sources/OrgSwift/AST/OrgParser.swift +58 −1
@@ -14,6 +14,7 @@ public enum OrgParser {
1414 .replacingOccurrences(of: "\r", with: "\n")
1515 .components(separatedBy: "\n")
1616 var index = 0
17 let latexEnds = latexEndLines(lines)
1718 var pendingCaption: String?
1819 var pendingName: String?
1920 var pendingAttrs: [(key: String, value: String)] = []
@@ -133,6 +134,14 @@ public enum OrgParser {
133134 continue
134135 }
135136
137 // A LaTeX block: \begin{name} alone on its line, through the matching \end{name}.
138 if let (raw, next) = parseLatexBlock(lines, from: index, ends: latexEnds) {
139 append(.latexBlock(raw))
140 index = next
141 flushPending()
142 continue
143 }
144
136145 // Paragraph: consume until a blank line or a line that starts another construct.
137146 var paragraph: [String] = []
138147 while index < lines.count {
@@ -141,7 +150,9 @@ public enum OrgParser {
141150 // The first line is always taken: nothing above claimed it, and
142151 // leaving it would parse the same line forever.
143152 if !paragraph.isEmpty,
144 candidateTrimmed.isEmpty || startsNewConstruct(candidateTrimmed, raw: candidate) { break }
153 candidateTrimmed.isEmpty || startsNewConstruct(candidateTrimmed, raw: candidate)
154 || latexEnd(candidateTrimmed) != nil
155 || latexBlockEnd(lines, from: index, ends: latexEnds) != nil { break }
145156 paragraph.append(candidateTrimmed)
146157 index += 1
147158 }
@@ -166,6 +177,52 @@ public enum OrgParser {
166177 return false
167178 }
168179
180 // MARK: - LaTeX block
181
182 /// The environment a `\begin{name}` line opens, as go-org's lexer reads it (any case).
183 private static func latexBegin(_ trimmed: String) -> String? {
184 guard trimmed.hasPrefix("\\") else { return nil }
185 return trimmed.firstMatch(of: /^\\begin\{([^}]+)\}$/.ignoresCase()).map { String($0.1).lowercased() }
186 }
187
188 /// The environment a `\end{name}` line closes. Like go-org's, it ends a paragraph
189 /// whether or not a block is open.
190 private static func latexEnd(_ trimmed: String) -> String? {
191 guard trimmed.hasPrefix("\\") else { return nil }
192 return trimmed.firstMatch(of: /^\\end\{([^}]+)\}$/.ignoresCase()).map { String($0.1).lowercased() }
193 }
194
195 /// Each environment's `\end{name}` lines, in order, found in one pass so an opener
196 /// looks its closer up rather than scanning to the end of the document.
197 private static func latexEndLines(_ lines: [String]) -> [String: [Int]] {
198 var ends: [String: [Int]] = [:]
199 for (index, line) in lines.enumerated() {
200 if let name = latexEnd(line.trimmingCharacters(in: .whitespaces)) { ends[name, default: []].append(index) }
201 }
202 return ends
203 }
204
205 /// The line closing the block a `\begin{name}` line at `start` opens, if one follows.
206 private static func latexBlockEnd(_ lines: [String], from start: Int, ends: [String: [Int]]) -> Int? {
207 guard let name = latexBegin(lines[start].trimmingCharacters(in: .whitespaces)),
208 let candidates = ends[name] else { return nil }
209 var low = 0, high = candidates.count
210 while low < high {
211 let mid = (low + high) / 2
212 if candidates[mid] <= start { low = mid + 1 } else { high = mid }
213 }
214 return low < candidates.count ? candidates[low] : nil
215 }
216
217 private static func parseLatexBlock(
218 _ lines: [String], from start: Int, ends: [String: [Int]]
219 ) -> (String, Int)? {
220 guard let end = latexBlockEnd(lines, from: start, ends: ends) else { return nil }
221 let indent = leadingWidth(lines[start])
222 let raw = lines[start...end].map { dropLeading($0, min(indent, leadingWidth($0))) }
223 return (raw.joined(separator: "\n"), end + 1)
224 }
225
169226 // MARK: - Heading
170227
171228 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 +64
@@ -0,0 +1,64 @@
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 expression drawn by `math` where it can be. Runs are taken
20/// by their math attribute alone, so an expression a `textTransform` split is still one;
21/// two identical expressions side by side share a range, so one holding its source k times
22/// draws k.
23@MainActor
24func orgText(_ string: AttributedString, math: OrgMathRenderer?) -> Text {
25 guard let math, string.runs.contains(where: { $0[OrgMathAttribute.self] != nil }) else {
26 return Text(string)
27 }
28 var result = Text(verbatim: "")
29 for (expression, range) in string.runs[OrgMathAttribute.self] {
30 let piece = AttributedString(string[range])
31 guard let expression, let drawn = math(expression) else {
32 result = Text("\(result)\(Text(piece))")
33 continue
34 }
35 let count = max(1, piece.characters.count / max(1, expression.source.count))
36 for _ in 0..<count { result = Text("\(result)\(drawn)") }
37 }
38 return result
39}
40
41/// Display math on its own: centred, scrolling sideways when wider than the column, or the
42/// source as a code block where nothing draws it.
43struct OrgMathBlockView: View {
44 let math: OrgMath
45 @Environment(\.orgMath) private var renderer
46
47 var body: some View {
48 if let drawn = renderer?(math) {
49 ViewThatFits(in: .horizontal) {
50 drawn.frame(maxWidth: .infinity)
51 ScrollView(.horizontal, showsIndicators: false) { drawn }
52 }
53 .padding(.vertical, 4)
54 } else {
55 ScrollView(.horizontal) {
56 Text(math.source)
57 .font(.system(.footnote, design: .monospaced))
58 .textSelection(.enabled)
59 .padding(10)
60 }
61 .background(Color.secondary.opacity(0.12), in: RoundedRectangle(cornerRadius: 4))
62 }
63 }
64}
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 +105
@@ -0,0 +1,105 @@
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(.timeLimit(.minutes(1)))
70 func unmatchedBeginLinesParseInLinearTime() {
71 let doc = OrgParser.parse(String(repeating: "\\begin{a}\n", count: 4000))
72 #expect(doc.elements.count == 1)
73 }
74
75 @Test(.timeLimit(.minutes(1)))
76 func unclosedOpenersScanInLinearTime() {
77 for opener in [#"\("#, #"\["#, "$$", "$x ", "[[", "[", "<"] {
78 let text = String(repeating: opener, count: 40_000)
79 let start = Date()
80 #expect(OrgParser.plain(objects(text)) == text.trimmingCharacters(in: .whitespaces), "\(opener)")
81 #expect(Date().timeIntervalSince(start) < 5, "\(opener) took \(Date().timeIntervalSince(start)) s")
82 }
83 }
84
85 @Test func onlyASCIISpaceKeepsDollarsProse() {
86 #expect(objects("$\u{00A0}x$") == [math("\u{00A0}x", false, "$\u{00A0}x$")])
87 }
88
89 @Test func environmentNamesAreASCIIWordCharacters() {
90 #expect(objects(#"\begin{aligné} x \end{aligné}"#) == [.text(#"\begin{aligné} x \end{aligné}"#)])
91 }
92
93 @Test func aStrayEndLineEndsAParagraph() {
94 #expect(OrgParser.parse("text\n\\end{equation}\nmore").elements.count == 2)
95 }
96
97 @Test func plainTextAndHTMLShowTheSource() {
98 let doc = OrgParser.parse("a $x$ b\n\n\\begin{align}\nx &< y\n\\end{align}")
99 #expect(OrgParser.plain(objects("a $x$ b")) == "a $x$ b")
100 let html = OrgHTMLTreeRenderer().render(doc)
101 #expect(html.contains("<p>a $x$ b</p>"))
102 #expect(html.contains("<pre>\\begin{align}\nx &amp;&lt; y\n\\end{align}</pre>"))
103 #expect(String(OrgAttributedStringRenderer().inline(objects("a $x$ b")).characters) == "a $x$ b")
104 }
105}
Tests/OrgSwiftUITests/OrgMathLayoutTests.swift added +70
@@ -0,0 +1,70 @@
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 anExpressionSplitByATransformDrawsOnce() {
43 let builder = OrgLayoutBuilder(options: .init(), styler: PlainOrgCodeStyler(), keywords: .init(),
44 textTransform: { text in
45 if let range = text.range(of: "#1") { text[range].link = URL(string: "https://x.test/1") }
46 })
47 guard case .paragraph(let text) = builder.layout(OrgParser.parse("a $x#1y$ b")).blocks.first else {
48 Issue.record("expected a paragraph"); return
49 }
50 var drawn = 0
51 _ = orgText(text) { _ in
52 drawn += 1
53 return Text(verbatim: "·")
54 }
55 #expect(drawn == 1)
56 }
57
58 @Test func orgTextDrawsEachExpression() {
59 guard case .paragraph(let text) = layout("$x$$x$ and $y$").blocks.first else {
60 Issue.record("expected a paragraph"); return
61 }
62 var drawn: [String] = []
63 _ = orgText(text) { math in
64 drawn.append(math.tex)
65 return Text(verbatim: "·")
66 }
67 #expect(drawn.sorted() == ["x", "y"])
68 _ = orgText(text, math: nil)
69 }
70}