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
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 +98 −4
@@ -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,13 @@ 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)
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 }
38 46
39 func flushPlain() { 47 func flushPlain() {
40 if !plain.isEmpty { objects.append(.text(plain)); plain = "" } 48 if !plain.isEmpty { objects.append(.text(plain)); plain = "" }
@@ -43,13 +51,25 @@ extension OrgParser {
43 while i < chars.count { 51 while i < chars.count {
44 // Bracket links: [[target]] or [[target][description]] 52 // Bracket links: [[target]] or [[target][description]]
45 if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[", 53 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("]]") {
47 flushPlain() 55 flushPlain()
48 objects.append(link.object) 56 objects.append(link.object)
49 i = link.next 57 i = link.next
50 continue 58 continue
51 } 59 }
52 60
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
53 // Footnote reference: [fn:label] or [fn:label:inline] 73 // Footnote reference: [fn:label] or [fn:label:inline]
54 if chars[i] == "[", let note = scanFootnote(chars, from: i) { 74 if chars[i] == "[", let note = scanFootnote(chars, from: i) {
55 flushPlain() 75 flushPlain()
@@ -246,6 +266,7 @@ extension OrgParser {
246 } 266 }
247 267
248 private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { 268 private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
269 guard chars[start...].starts(with: "[fn:") else { return nil }
249 let rest = String(chars[start...]) 270 let rest = String(chars[start...])
250 guard let match = rest.firstMatch(of: /^\[fn:([A-Za-z0-9_-]+)(?::([^\]]*))?\]/) else { return nil } 271 guard let match = rest.firstMatch(of: /^\[fn:([A-Za-z0-9_-]+)(?::([^\]]*))?\]/) else { return nil }
251 let label = String(match.1) 272 let label = String(match.1)
@@ -261,7 +282,8 @@ extension OrgParser {
261 var j = start + 1 282 var j = start + 1
262 var body = "" 283 var body = ""
263 while j < chars.count, chars[j] != closing { 284 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 }
265 body.append(chars[j]); j += 1 287 body.append(chars[j]); j += 1
266 } 288 }
267 guard j < chars.count else { return nil } 289 guard j < chars.count else { return nil }
@@ -295,7 +317,10 @@ extension OrgParser {
295 } 317 }
296 318
297 private static func scanBareURL(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { 319 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)])
299 guard let match = rest.firstMatch(of: /^https?:\/\/[^\s<>()\[\]]+/) else { return nil } 324 guard let match = rest.firstMatch(of: /^https?:\/\/[^\s<>()\[\]]+/) else { return nil }
300 var url = String(rest[match.range]) 325 var url = String(rest[match.range])
301 while let last = url.last, ".,;:!?".contains(last) { url.removeLast() } 326 while let last = url.last, ".,;:!?".contains(last) { url.removeLast() }
@@ -309,7 +334,11 @@ extension OrgParser {
309 } 334 }
310 335
311 private static func scanEmail(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { 336 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)])
313 guard let match = rest.firstMatch(of: /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/) else { 342 guard let match = rest.firstMatch(of: /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/) else {
314 return nil 343 return nil
315 } 344 }
@@ -320,6 +349,71 @@ extension OrgParser {
320 description: [.text(address)])), start + address.count) 349 description: [.text(address)])), start + address.count)
321 } 350 }
322 351
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
323 private static func scanSuperscript(_ chars: [Character], from start: Int) -> (body: String, next: Int)? { 417 private static func scanSuperscript(_ chars: [Character], from start: Int) -> (body: String, next: Int)? {
324 var j = start + 1 418 var j = start + 1
325 guard j < chars.count else { return nil } 419 guard j < chars.count else { return nil }
Sources/OrgSwift/AST/OrgParser.swift +58 −1
@@ -14,6 +14,7 @@ public enum OrgParser {
14 .replacingOccurrences(of: "\r", with: "\n") 14 .replacingOccurrences(of: "\r", with: "\n")
15 .components(separatedBy: "\n") 15 .components(separatedBy: "\n")
16 var index = 0 16 var index = 0
17 let latexEnds = latexEndLines(lines)
17 var pendingCaption: String? 18 var pendingCaption: String?
18 var pendingName: String? 19 var pendingName: String?
19 var pendingAttrs: [(key: String, value: String)] = [] 20 var pendingAttrs: [(key: String, value: String)] = []
@@ -133,6 +134,14 @@ public enum OrgParser {
133 continue 134 continue
134 } 135 }
135 136
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
136 // Paragraph: consume until a blank line or a line that starts another construct. 145 // Paragraph: consume until a blank line or a line that starts another construct.
137 var paragraph: [String] = [] 146 var paragraph: [String] = []
138 while index < lines.count { 147 while index < lines.count {
@@ -141,7 +150,9 @@ public enum OrgParser {
141 // The first line is always taken: nothing above claimed it, and 150 // The first line is always taken: nothing above claimed it, and
142 // leaving it would parse the same line forever. 151 // leaving it would parse the same line forever.
143 if !paragraph.isEmpty, 152 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 }
145 paragraph.append(candidateTrimmed) 156 paragraph.append(candidateTrimmed)
146 index += 1 157 index += 1
147 } 158 }
@@ -166,6 +177,52 @@ public enum OrgParser {
166 return false 177 return false
167 } 178 }
168 179
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
169 // MARK: - Heading 226 // MARK: - Heading
170 227
171 private static func parseHeading(stars: Int, rest: String) -> OrgHeading { 228 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 +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
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 +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}