krz/org-swift

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

Commit 76ed01cb1d

76ed01cb1d0597d54f92b9c5ab70bf943dbbafc3

parent: 799d4ba18e

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 20:52 UTC

Add Qlty config; split the parser, inline scanner, and renderers

OrgParser.parse walks a State struct; parseInline tries constructs in
scanObject; renderTable, attributeValue, and the SwiftUI styler move
their inner loops into helpers; the image and link resolvers share
repositoryResolver. HTML for the 39 conformance cases and 227 other org
files is unchanged; 116 tests pass.

Layout: unified · split

.qlty/.gitignore added +7
@@ -0,0 +1,7 @@
1*
2!configs
3!configs/**
4!hooks
5!hooks/**
6!qlty.toml
7!.gitignore
.qlty/qlty.toml added +44
@@ -0,0 +1,44 @@
1config_version = "0"
2
3exclude_patterns = [
4 "**/vendor/**",
5 "**/node_modules/**",
6 "**/testdata/**",
7 "**/dist/**",
8 "**/.build/**",
9 "**/build/**",
10 "**/*.min.*",
11 "**/generated/**",
12 ".claude/**",
13 "**/Pods/**",
14]
15
16test_patterns = [
17 "**/test/**",
18 "**/tests/**",
19 "**/Tests/**",
20 "**/*_test.*",
21 "**/test_*.*",
22 "**/*.test.*",
23 "**/*Tests.swift",
24 "e2e/**",
25]
26
27[[source]]
28name = "default"
29default = true
30
31[[plugin]]
32name = "osv-scanner"
33
34[[plugin]]
35name = "trufflehog"
36
37# Early returns are guard clauses, which keep the happy path unindented.
38[smells.return_statements]
39enabled = false
40
41# Total file complexity is the sum of its functions, which function_complexity
42# already checks.
43[smells.file_complexity]
44enabled = false
Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift +14 −8
@@ -201,20 +201,26 @@ public struct OrgHTMLTreeRenderer {
201201 let isHeader = headerCount > 0 && index < headerCount
202202 if isHeader, !wroteHeader { html += "<thead>\n"; wroteHeader = true }
203203 if !isHeader, !inBody { html += "<tbody>\n"; inBody = true }
204 html += "<tr>\n"
205 for (column, cell) in cells.enumerated() {
206 let tag = isHeader ? "th" : "td"
207 let alignment = column < table.alignments.count ? table.alignments[column] : nil
208 let style = alignment.map { #" style="text-align: \#($0.rawValue);""# } ?? ""
209 html += "<\(tag)\(style)>" + renderInline(cell, &notes) + "</\(tag)>\n"
210 }
211 html += "</tr>\n"
204 html += renderRow(cells, header: isHeader, alignments: table.alignments, &notes)
212205 }
213206 }
214207 if inBody { html += "</tbody>\n" }
215208 return html + "</table>\n"
216209 }
217210
211 private func renderRow(
212 _ cells: [[OrgObject]], header: Bool, alignments: [OrgAlignment?], _ notes: inout OrgFootnotes
213 ) -> String {
214 var html = "<tr>\n"
215 for (column, cell) in cells.enumerated() {
216 let tag = header ? "th" : "td"
217 let alignment = column < alignments.count ? alignments[column] : nil
218 let style = alignment.map { #" style="text-align: \#($0.rawValue);""# } ?? ""
219 html += "<\(tag)\(style)>" + renderInline(cell, &notes) + "</\(tag)>\n"
220 }
221 return html + "</tr>\n"
222 }
223
218224 /// The `<img>` for a figure, or nil when the source cannot be resolved to a safe URL —
219225 /// in which case the caller falls back to text rather than pointing at something unsafe.
220226 private func imageTag(_ figure: OrgFigure, caption: [OrgObject]?) -> String? {
Sources/OrgSwift/AST/OrgInlineParser.swift +74 −77
@@ -39,100 +39,97 @@ extension OrgParser {
3939 let lastEnd = lastEnvironmentEnd(text)
4040 // A closer that is missing once is missing for every later opener of its kind.
4141 var missing: Set<String> = []
42 func noteMissing<T>(_ closer: String) -> T? {
43 missing.insert(closer)
44 return nil
45 }
4642
4743 func flushPlain() {
4844 if !plain.isEmpty { objects.append(.text(plain)); plain = "" }
4945 }
5046
5147 while i < chars.count {
52 // Bracket links: [[target]] or [[target][description]]
53 if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[",
54 !missing.contains("]]"), let link = scanLink(chars, from: i) ?? noteMissing("]]") {
55 flushPlain()
56 objects.append(link.object)
57 i = link.next
58 continue
59 }
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
48 guard let hit = scanObject(chars, at: i, lastEnd: lastEnd, missing: &missing) else {
49 plain.append(chars[i])
50 i += 1
7051 continue
7152 }
72
73 // Footnote reference: [fn:label] or [fn:label:inline]
74 if chars[i] == "[", let note = scanFootnote(chars, from: i) {
53 if hit.mergesText, case .text(let text) = hit.object {
54 plain += text
55 } else {
7556 flushPlain()
76 objects.append(note.object)
77 i = note.next
78 continue
57 objects.append(hit.object)
7958 }
59 i = hit.next
60 }
61 flushPlain()
62 return objects
63 }
8064
81 // Timestamps: <2024-01-15 Mon 10:30> or [2024-01-15 Mon]
82 if chars[i] == "<" || chars[i] == "[", let stamp = scanTimestamp(chars, from: i) {
83 flushPlain()
84 objects.append(stamp.object)
85 i = stamp.next
86 continue
87 }
65 /// An inline object found at a position, and where scanning resumes.
66 private struct InlineHit {
67 let object: OrgObject
68 let next: Int
69 /// Plain text from a scanner (an unclosed LaTeX opener) that joins the
70 /// surrounding text run.
71 var mergesText = false
72 }
8873
89 // Bare URL autolink.
90 if chars[i] == "h", let url = scanBareURL(chars, from: i) {
91 flushPlain()
92 objects.append(url.object)
93 i = url.next
94 continue
95 }
74 /// The first inline object starting at `i`, trying each construct in priority order.
75 private static func scanObject(
76 _ chars: [Character], at i: Int, lastEnd: (offset: Int, name: String)?, missing: inout Set<String>
77 ) -> InlineHit? {
78 // Bracket links: [[target]] or [[target][description]]
79 if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[", !missing.contains("]]") {
80 if let link = scanLink(chars, from: i) { return InlineHit(object: link.object, next: link.next) }
81 missing.insert("]]")
82 }
9683
97 // Bare email autolink, at a word boundary so `a.b@c.d` is not matched mid-token.
98 if isWordCharacter(chars[i]), i == 0 || !isEmailBoundaryCharacter(chars[i - 1]),
99 let email = scanEmail(chars, from: i) {
100 flushPlain()
101 objects.append(email.object)
102 i = email.next
103 continue
104 }
84 // LaTeX fragments: $…$, $$…$$, \(…\), \[…\], \begin{…}…\end{…}
85 if chars[i] == "$" || chars[i] == "\\", let math = scanMath(chars, from: i, lastEnd: lastEnd, missing: &missing) {
86 return InlineHit(object: math.object, next: math.next, mergesText: true)
87 }
10588
106 // Emphasis: *bold* /italic/ _underline_ +strike+ =verbatim= ~code~
107 if let marker = emphasisMarker(chars[i]), boundaryBefore(chars, i),
108 let span = scanEmphasis(chars, from: i, marker: chars[i]) {
109 flushPlain()
110 switch marker {
111 case .bold: objects.append(.bold(parseInline(span.body)))
112 case .italic: objects.append(.italic(parseInline(span.body)))
113 case .underline: objects.append(.underline(parseInline(span.body)))
114 case .strike: objects.append(.strikeThrough(parseInline(span.body)))
115 case .verbatim: objects.append(.verbatim(span.body))
116 case .code: objects.append(.code(span.body))
117 }
118 i = span.next
119 continue
120 }
89 // Footnote reference: [fn:label] or [fn:label:inline]
90 if chars[i] == "[", let note = scanFootnote(chars, from: i) {
91 return InlineHit(object: note.object, next: note.next)
92 }
12193
122 // Superscript: x^2 or x^{group}
123 if chars[i] == "^", i > 0, isWordCharacter(chars[i - 1]),
124 let sup = scanSuperscript(chars, from: i) {
125 flushPlain()
126 objects.append(.superscript(parseInline(sup.body)))
127 i = sup.next
128 continue
129 }
94 // Timestamps: <2024-01-15 Mon 10:30> or [2024-01-15 Mon]
95 if chars[i] == "<" || chars[i] == "[", let stamp = scanTimestamp(chars, from: i) {
96 return InlineHit(object: stamp.object, next: stamp.next)
97 }
13098
131 plain.append(chars[i])
132 i += 1
99 // Bare URL autolink.
100 if chars[i] == "h", let url = scanBareURL(chars, from: i) {
101 return InlineHit(object: url.object, next: url.next)
102 }
103
104 // Bare email autolink, at a word boundary so `a.b@c.d` is not matched mid-token.
105 if isWordCharacter(chars[i]), i == 0 || !isEmailBoundaryCharacter(chars[i - 1]),
106 let email = scanEmail(chars, from: i) {
107 return InlineHit(object: email.object, next: email.next)
108 }
109
110 // Emphasis: *bold* /italic/ _underline_ +strike+ =verbatim= ~code~
111 if let marker = emphasisMarker(chars[i]), boundaryBefore(chars, i),
112 let span = scanEmphasis(chars, from: i, marker: chars[i]) {
113 return InlineHit(object: emphasisObject(marker, span.body), next: span.next)
114 }
115
116 // Superscript: x^2 or x^{group}
117 if chars[i] == "^", i > 0, isWordCharacter(chars[i - 1]),
118 let sup = scanSuperscript(chars, from: i) {
119 return InlineHit(object: .superscript(parseInline(sup.body)), next: sup.next)
120 }
121 return nil
122 }
123
124 private static func emphasisObject(_ marker: Emphasis, _ body: String) -> OrgObject {
125 switch marker {
126 case .bold: return .bold(parseInline(body))
127 case .italic: return .italic(parseInline(body))
128 case .underline: return .underline(parseInline(body))
129 case .strike: return .strikeThrough(parseInline(body))
130 case .verbatim: return .verbatim(body)
131 case .code: return .code(body)
133132 }
134 flushPlain()
135 return objects
136133 }
137134
138135 // MARK: - Scanners
Sources/OrgSwift/AST/OrgParser.swift +87 −78
@@ -8,18 +8,34 @@ import Foundation
88public enum OrgParser {
99
1010 public static func parse(_ source: String) -> OrgDocument {
11 var document = OrgDocument()
1211 let lines = source
1312 .replacingOccurrences(of: "\r\n", with: "\n")
1413 .replacingOccurrences(of: "\r", with: "\n")
1514 .components(separatedBy: "\n")
15 var state = State(lines: lines)
16 while state.index < lines.count {
17 state.step()
18 }
19 return state.document
20 }
21
22 /// The document so far, the current line, and any affiliated keywords
23 /// waiting for the block they apply to.
24 private struct State {
25 let lines: [String]
26 let latexEnds: [String: [Int]]
27 var document = OrgDocument()
1628 var index = 0
17 let latexEnds = latexEndLines(lines)
1829 var pendingCaption: String?
1930 var pendingName: String?
2031 var pendingAttrs: [(key: String, value: String)] = []
2132
22 func flushPending() {
33 init(lines: [String]) {
34 self.lines = lines
35 self.latexEnds = OrgParser.latexEndLines(lines)
36 }
37
38 mutating func flushPending() {
2339 pendingCaption = nil
2440 pendingName = nil
2541 pendingAttrs = []
@@ -27,11 +43,11 @@ public enum OrgParser {
2743
2844 /// Append a block, wrapping it in `.captioned` when an affiliated `#+CAPTION:` or
2945 /// `#+NAME:` precedes it — org's exporter turns that pairing into a `<figure>`.
30 func append(_ element: OrgElement) {
46 mutating func append(_ element: OrgElement) {
3147 if pendingCaption != nil || pendingName != nil {
3248 document.elements.append(.captioned(
3349 name: pendingName,
34 caption: pendingCaption.map(parseInline),
50 caption: pendingCaption.map(OrgParser.parseInline),
3551 content: element
3652 ))
3753 } else {
@@ -39,110 +55,106 @@ public enum OrgParser {
3955 }
4056 }
4157
42 while index < lines.count {
58 mutating func step() {
4359 let line = lines[index]
4460 let trimmed = line.trimmingCharacters(in: .whitespaces)
4561
46 if trimmed.isEmpty { index += 1; continue }
62 if trimmed.isEmpty { index += 1; return }
4763
4864 // Comments.
49 if trimmed == "#" || trimmed.hasPrefix("# ") { index += 1; continue }
65 if trimmed == "#" || trimmed.hasPrefix("# ") { index += 1; return }
5066
5167 // Property drawers are heading metadata; org's exporter drops them.
5268 if trimmed == ":PROPERTIES:" {
53 index += 1
54 while index < lines.count,
55 lines[index].trimmingCharacters(in: .whitespaces) != ":END:" {
56 index += 1
57 }
58 if index < lines.count { index += 1 }
59 continue
69 skipPropertyDrawer()
70 return
6071 }
6172
6273 // Affiliated keywords and document metadata.
6374 if let directive = orgKeywordDirective(in: trimmed) {
64 switch directive.keyword {
65 case "caption": pendingCaption = directive.value
66 case "name": pendingName = directive.value
67 case "attr_html": pendingAttrs = parseAttributes(directive.value)
68 default: document.keywords.append((directive.keyword, directive.value))
69 }
75 applyDirective(directive.keyword, directive.value)
7076 index += 1
71 continue
77 return
7278 }
7379
74 // Blocks: #+begin_… / #+end_…
75 if trimmed.lowercased().hasPrefix("#+begin_") {
76 let (element, next) = parseBlock(lines, from: index)
77 if let element { append(element) }
78 index = next
80 if parseSingleLine(trimmed) || parseMultiLine(line, trimmed) {
7981 flushPending()
80 continue
82 return
8183 }
8284
83 // Heading.
84 if let match = trimmed.firstMatch(of: /^(\*{1,6})\s+(.+)$/) {
85 document.elements.append(.heading(parseHeading(stars: match.1.count, rest: String(match.2))))
86 index += 1
87 flushPending()
88 continue
89 }
85 parseParagraph()
86 flushPending()
87 }
9088
91 // Horizontal rule.
92 if isOrgHorizontalRule(trimmed) {
93 document.elements.append(.horizontalRule)
89 mutating func skipPropertyDrawer() {
90 index += 1
91 while index < lines.count,
92 lines[index].trimmingCharacters(in: .whitespaces) != ":END:" {
9493 index += 1
95 flushPending()
96 continue
9794 }
95 if index < lines.count { index += 1 }
96 }
9897
99 // Footnote definition.
100 if let def = orgFootnoteDefinition(in: trimmed) {
101 document.elements.append(.footnoteDefinition(label: def.label, content: parseInline(def.text)))
102 index += 1
103 flushPending()
104 continue
98 mutating func applyDirective(_ keyword: String, _ value: String) {
99 switch keyword {
100 case "caption": pendingCaption = value
101 case "name": pendingName = value
102 case "attr_html": pendingAttrs = OrgParser.parseAttributes(value)
103 default: document.keywords.append((keyword, value))
105104 }
105 }
106106
107 // A standalone image link, promoted to a figure by an affiliated caption/attrs.
108 if let path = standaloneOrgImage(in: trimmed) {
107 /// A heading, horizontal rule, footnote definition, or standalone image on
108 /// this line. Returns false if the line is none of those.
109 mutating func parseSingleLine(_ trimmed: String) -> Bool {
110 if let match = trimmed.firstMatch(of: /^(\*{1,6})\s+(.+)$/) {
111 document.elements.append(.heading(OrgParser.parseHeading(stars: match.1.count, rest: String(match.2))))
112 } else if isOrgHorizontalRule(trimmed) {
113 document.elements.append(.horizontalRule)
114 } else if let def = orgFootnoteDefinition(in: trimmed) {
115 document.elements.append(.footnoteDefinition(label: def.label, content: OrgParser.parseInline(def.text)))
116 } else if let path = standaloneOrgImage(in: trimmed) {
117 // A standalone image link, promoted to a figure by an affiliated caption/attrs.
109118 document.elements.append(.figure(OrgFigure(
110119 source: path,
111 caption: pendingCaption.map(parseInline),
120 caption: pendingCaption.map(OrgParser.parseInline),
112121 attributes: pendingAttrs
113122 )))
114 index += 1
115 flushPending()
116 continue
123 } else {
124 return false
117125 }
126 index += 1
127 return true
128 }
118129
119 // Table.
120 if isTableLine(trimmed) {
121 let (table, next) = parseTable(lines, from: index)
130 /// A block, table, list, or LaTeX block starting on this line. Returns false
131 /// if the line starts none of those.
132 mutating func parseMultiLine(_ line: String, _ trimmed: String) -> Bool {
133 if trimmed.lowercased().hasPrefix("#+begin_") {
134 // Blocks: #+begin_… / #+end_…
135 let (element, next) = OrgParser.parseBlock(lines, from: index)
136 if let element { append(element) }
137 index = next
138 } else if isTableLine(trimmed) {
139 let (table, next) = OrgParser.parseTable(lines, from: index)
122140 append(.table(table))
123141 index = next
124 flushPending()
125 continue
126 }
127
128 // List.
129 if isListMarkerLine(trimmed), !isIndentedContinuationLine(line) {
130 let (list, next) = parseList(lines, from: index)
142 } else if isListMarkerLine(trimmed), !isIndentedContinuationLine(line) {
143 let (list, next) = OrgParser.parseList(lines, from: index)
131144 document.elements.append(.list(list))
132145 index = next
133 flushPending()
134 continue
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) {
146 } else if let (raw, next) = OrgParser.parseLatexBlock(lines, from: index, ends: latexEnds) {
147 // A LaTeX block: \begin{name} alone on its line, through the matching \end{name}.
139148 append(.latexBlock(raw))
140149 index = next
141 flushPending()
142 continue
150 } else {
151 return false
143152 }
153 return true
154 }
144155
145 // Paragraph: consume until a blank line or a line that starts another construct.
156 /// Consume until a blank line or a line that starts another construct.
157 mutating func parseParagraph() {
146158 var paragraph: [String] = []
147159 while index < lines.count {
148160 let candidate = lines[index]
@@ -150,19 +162,16 @@ public enum OrgParser {
150162 // The first line is always taken: nothing above claimed it, and
151163 // leaving it would parse the same line forever.
152164 if !paragraph.isEmpty,
153 candidateTrimmed.isEmpty || startsNewConstruct(candidateTrimmed, raw: candidate)
154 || latexEnd(candidateTrimmed) != nil
155 || latexBlockEnd(lines, from: index, ends: latexEnds) != nil { break }
165 candidateTrimmed.isEmpty || OrgParser.startsNewConstruct(candidateTrimmed, raw: candidate)
166 || OrgParser.latexEnd(candidateTrimmed) != nil
167 || OrgParser.latexBlockEnd(lines, from: index, ends: latexEnds) != nil { break }
156168 paragraph.append(candidateTrimmed)
157169 index += 1
158170 }
159171 if !paragraph.isEmpty {
160 document.elements.append(.paragraph(parseInline(paragraph.joined(separator: " "))))
172 document.elements.append(.paragraph(OrgParser.parseInline(paragraph.joined(separator: " "))))
161173 }
162 flushPending()
163174 }
164
165 return document
166175 }
167176
168177 /// Would this line begin a construct other than the paragraph currently being consumed?
Sources/OrgSwift/OrgRenderer.swift +13 −26
@@ -87,40 +87,27 @@ public struct OrgRenderOptions: Sendable {
8787 }
8888
8989 func imageURLResolver() -> ((String) -> String?)? {
90 guard let owner, let repositoryName else { return nil }
91 let host = host
92 let ref = ref
93 let readmePath = readmePath
94 let segment = imagePathSegment
95 return { source in
96 resolveRepositoryAssetURL(
97 source,
98 host: host,
99 owner: owner,
100 repositoryName: repositoryName,
101 ref: ref,
102 readmePath: readmePath,
103 pathSegment: segment
104 )
105 }
90 repositoryResolver(pathSegment: imagePathSegment, resolveRepositoryAssetURL)
10691 }
10792
10893 func linkURLResolver() -> ((String) -> String?)? {
94 repositoryResolver(pathSegment: linkPathSegment, resolveRepositoryLinkURL)
95 }
96
97 private typealias RepositoryURLFunction = (
98 String, String, String, String, String, String?, String
99 ) -> String?
100
101 /// `resolve` bound to this repository, or nil when the owner or name is unknown.
102 private func repositoryResolver(
103 pathSegment: String, _ resolve: @escaping RepositoryURLFunction
104 ) -> ((String) -> String?)? {
109105 guard let owner, let repositoryName else { return nil }
110106 let host = host
111107 let ref = ref
112108 let readmePath = readmePath
113 let segment = linkPathSegment
114109 return { source in
115 resolveRepositoryLinkURL(
116 source,
117 host: host,
118 owner: owner,
119 repositoryName: repositoryName,
120 ref: ref,
121 readmePath: readmePath,
122 pathSegment: segment
123 )
110 resolve(source, host, owner, repositoryName, ref, readmePath, pathSegment)
124111 }
125112 }
126113}
Sources/OrgSwift/Skeleton.swift +24 −15
@@ -133,28 +133,37 @@ public enum OrgSkeleton {
133133 var search = 0
134134 while let pos = indexOf(chars, nameChars, from: search) {
135135 let beforeOK = pos == 0 || chars[pos - 1].isWhitespace
136 var after = pos + nameChars.count
137 while after < chars.count && chars[after].isWhitespace { after += 1 }
136 let after = skipSpaces(chars, from: pos + nameChars.count)
138137 if beforeOK && after < chars.count && chars[after] == "=" {
139 var value = after + 1
140 while value < chars.count && chars[value].isWhitespace { value += 1 }
141 guard value < chars.count else { return nil }
142 let quote = chars[value]
143 if quote == "\"" || quote == "'" {
144 var end = value + 1
145 while end < chars.count && chars[end] != quote { end += 1 }
146 guard end < chars.count else { return nil }
147 return String(chars[(value + 1)..<end])
148 }
149 var end = value
150 while end < chars.count && !chars[end].isWhitespace { end += 1 }
151 return String(chars[value..<end])
138 return readAttributeValue(chars, from: skipSpaces(chars, from: after + 1))
152139 }
153140 search = pos + nameChars.count
154141 }
155142 return nil
156143 }
157144
145 private static func skipSpaces(_ chars: [Character], from start: Int) -> Int {
146 var i = start
147 while i < chars.count && chars[i].isWhitespace { i += 1 }
148 return i
149 }
150
151 /// A quoted or bare attribute value starting at `value`, or nil if it is
152 /// missing or its quote never closes.
153 private static func readAttributeValue(_ chars: [Character], from value: Int) -> String? {
154 guard value < chars.count else { return nil }
155 let quote = chars[value]
156 if quote == "\"" || quote == "'" {
157 var end = value + 1
158 while end < chars.count && chars[end] != quote { end += 1 }
159 guard end < chars.count else { return nil }
160 return String(chars[(value + 1)..<end])
161 }
162 var end = value
163 while end < chars.count && !chars[end].isWhitespace { end += 1 }
164 return String(chars[value..<end])
165 }
166
158167 private static func indexOf(_ haystack: [Character], _ needle: [Character], from: Int) -> Int? {
159168 if needle.isEmpty { return from }
160169 var k = from
Sources/OrgSwiftUI/OrgInlineStyler.swift +61 −44
@@ -24,57 +24,74 @@ struct OrgInlineStyler {
2424 style: Font.TextStyle = .body, bold forceBold: Bool = false
2525 ) -> AttributedString {
2626 var string = renderer.inline(objects, &notes)
27
2827 for range in string.runs.map(\.range) {
29 let intents = string[range].inlinePresentationIntent ?? []
30 let role = string[range][OrgRoleAttribute.self]
28 styleRun(&string, range, style: style, forceBold: forceBold)
29 }
30 return string
31 }
32
33 /// How one run's font is built.
34 private struct RunStyle {
35 var textStyle: Font.TextStyle
36 var monospaced = false
37 var bold: Bool
38 var italic: Bool
39 }
3140
32 var textStyle = style
33 var monospaced = false
34 var bold = forceBold
35 var italic = false
41 private func styleRun(
42 _ string: inout AttributedString, _ range: Range<AttributedString.Index>,
43 style: Font.TextStyle, forceBold: Bool
44 ) {
45 let intents = string[range].inlinePresentationIntent ?? []
46 var run = RunStyle(
47 textStyle: style,
48 bold: forceBold || intents.contains(.stronglyEmphasized),
49 italic: intents.contains(.emphasized)
50 )
51 if intents.contains(.code) {
52 run.monospaced = true
53 string[range].backgroundColor = .secondary.opacity(0.12)
54 }
3655
37 if intents.contains(.stronglyEmphasized) { bold = true }
38 if intents.contains(.emphasized) { italic = true }
39 if intents.contains(.code) {
40 monospaced = true
41 string[range].backgroundColor = .secondary.opacity(0.12)
42 }
56 Self.applyRole(string[range][OrgRoleAttribute.self], &string, range, &run)
4357
44 switch role {
45 case .underline:
46 string[range].underlineStyle = .single
47 case .strikeThrough:
48 string[range].strikethroughStyle = .single
49 case .superscript, .footnoteReference:
50 // No portable superscript attribute, so raise it and step the style down.
51 textStyle = Self.smaller(textStyle)
52 string[range].baselineOffset = 5
53 if role == .footnoteReference { string[range].foregroundColor = .accentColor }
54 case .timestamp:
55 string[range].foregroundColor = .secondary
56 case .image:
57 // An inline image inside a paragraph shows its alt text; the block-level
58 // `.figure` case is where an image is actually loaded.
59 italic = true
60 string[range].foregroundColor = .secondary
61 case nil:
62 break
63 }
58 if string[range][OrgMathAttribute.self] != nil {
59 string[range][OrgMathStyleAttribute.self] = run.textStyle
60 }
6461
65 if string[range][OrgMathAttribute.self] != nil {
66 string[range][OrgMathStyleAttribute.self] = textStyle
67 }
62 // Always set the font, never only on modified runs: a run with no emphasis
63 // would otherwise inherit the surrounding view's font and a heading, table cell
64 // or footnote would render at body size.
65 var font = Font.system(run.textStyle, design: run.monospaced ? .monospaced : .default)
66 if run.bold { font = font.bold() }
67 if run.italic { font = font.italic() }
68 string[range].font = font
69 }
6870
69 // Always set the font, never only on modified runs: a run with no emphasis
70 // would otherwise inherit the surrounding view's font and a heading, table cell
71 // or footnote would render at body size.
72 var font = Font.system(textStyle, design: monospaced ? .monospaced : .default)
73 if bold { font = font.bold() }
74 if italic { font = font.italic() }
75 string[range].font = font
71 private static func applyRole(
72 _ role: OrgRole?, _ string: inout AttributedString, _ range: Range<AttributedString.Index>,
73 _ run: inout RunStyle
74 ) {
75 switch role {
76 case .underline:
77 string[range].underlineStyle = .single
78 case .strikeThrough:
79 string[range].strikethroughStyle = .single
80 case .superscript, .footnoteReference:
81 // No portable superscript attribute, so raise it and step the style down.
82 run.textStyle = smaller(run.textStyle)
83 string[range].baselineOffset = 5
84 if role == .footnoteReference { string[range].foregroundColor = .accentColor }
85 case .timestamp:
86 string[range].foregroundColor = .secondary
87 case .image:
88 // An inline image inside a paragraph shows its alt text; the block-level
89 // `.figure` case is where an image is actually loaded.
90 run.italic = true
91 string[range].foregroundColor = .secondary
92 case nil:
93 break
7694 }
77 return string
7895 }
7996
8097 /// One step down the semantic scale, for superscripts and footnote markers.