krz/org-swift

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

Commit a35aabf552

a35aabf5524cce249e87d7882eb0174a841f5ab5

parent: 1f84ad11e0

Unsigned

cmc <hello@cleberg.net> · 2026-11-01 03:18 UTC

Build for Wasm; scan hot line patterns by hand (!14)

## Wasm build

`OrgAttributedStringRenderer` used `InlinePresentationIntent` (Darwin Foundation only) for bold, italic, verbatim and code. Those cases and the `applying(_: InlinePresentationIntent, …)` helper are now under `#if canImport(Darwin)`; on other platforms the runs keep their text without an intent. The macOS/iOS API and `OrgSwiftUI` are unchanged.

```
TOOLCHAINS=org.swift.642202610261a swift build --swift-sdk swift-6.4.2-RELEASE_wasm --product OrgSwift
Build complete!
```

## Parse performance

Swift Regex literals were compiled from their source string on every evaluation. Per-line patterns are now hand scanners that keep Swift Regex's semantics (ASCII classes match only ASCII characters, `.` excludes newlines, `\s`/`\d` are `isWhitespace`/`isNumber`):

- `orgKeywordDirective`, `isOrgHorizontalRule` (was an `NSRegularExpression` per call; `matchesRegex` removed)
- `orgFootnoteDefinition`, `orderedListItem`, `splitHeadingTags`
- heading line, heading-start test, priority cookie, ordered `stripMarker` in `OrgParser`
- bare URL in `OrgInlineParser`

The rest (footnote reference, timestamp, email, LaTeX begin/end lines, `\end{…}` lookup, `#+attr_html`) are hoisted to `static let`.

`swift run -c release OrgSwiftBenchmark` renders 2000 sections of `* Heading N` / paragraph with `*bold*`, `~code~` and a URL / `- item` (176 KB), best of 10:

| sections | before | after |
|---|---|---|
| 2000 | 1756 ms | 91 ms |

After: 1000 → 45 ms, 4000 → 181 ms (linear). org-js on the same input: 35 ms.

Output was compared against `main` on 500k random documents built from fragments that hit each scanner's edge cases (7 stars, exotic whitespace and newlines, combining marks, non-ASCII digits, `::` tags, `https` without `://`): byte-identical HTML. `swift test` passes, including `ConformanceTests` against org-conformance.

## Next step

A stdlib-only port (no Foundation, no Swift Regex) would allow the `swift-6.4.2-RELEASE_wasm-embedded` SDK, which currently fails on `import Foundation`. Remaining Foundation uses include `trimmingCharacters`, `replacingOccurrences`, `URLComponents`, `NSString` path helpers, `NSRegularExpression` for `#+attr_html`, and `AttributedString`.

Layout: unified · split

Package.swift +1
@@ -21,6 +21,7 @@ let package = Package(
21 dependencies: ["OrgSwift"], 21 dependencies: ["OrgSwift"],
22 swiftSettings: [.enableUpcomingFeature("BareSlashRegexLiterals")] 22 swiftSettings: [.enableUpcomingFeature("BareSlashRegexLiterals")]
23 ), 23 ),
24 .executableTarget(name: "OrgSwiftBenchmark", dependencies: ["OrgSwift"]),
24 .testTarget(name: "OrgSwiftTests", dependencies: ["OrgSwift"]), 25 .testTarget(name: "OrgSwiftTests", dependencies: ["OrgSwift"]),
25 .testTarget(name: "OrgSwiftUITests", dependencies: ["OrgSwiftUI"]) 26 .testTarget(name: "OrgSwiftUITests", dependencies: ["OrgSwiftUI"])
26 ] 27 ]
README.md +6
@@ -171,3 +171,9 @@ corpus, whose golden outputs come from `orgo` (itself validated against Emacs
171a semantic skeleton and compares them; the current pass/divergence state is 171a semantic skeleton and compares them; the current pass/divergence state is
172recorded per case, so a closed gap or a regression both surface as a failing 172recorded per case, so a closed gap or a regression both surface as a failing
173test. See [GAPS.md](GAPS.md) for the outstanding backlog. 173test. See [GAPS.md](GAPS.md) for the outstanding backlog.
174
175## Benchmark
176
177`swift run -c release OrgSwiftBenchmark [sections] [iterations]` times
178`OrgRenderer.renderToHTML` on a generated document of `sections` heading sections
179(default 2000, about 176 KB) and prints the best of `iterations` runs.
Sources/OrgSwift/AST/OrgAttributedStringRenderer.swift +14 −3
@@ -33,12 +33,24 @@ public struct OrgAttributedStringRenderer: Sendable {
33 case .text(let text): 33 case .text(let text):
34 result += AttributedString(text) 34 result += AttributedString(text)
35 35
36 #if canImport(Darwin)
36 case .bold(let children): 37 case .bold(let children):
37 result += applying(.stronglyEmphasized, to: inline(children, &notes)) 38 result += applying(.stronglyEmphasized, to: inline(children, &notes))
38 39
39 case .italic(let children): 40 case .italic(let children):
40 result += applying(.emphasized, to: inline(children, &notes)) 41 result += applying(.emphasized, to: inline(children, &notes))
41 42
43 case .verbatim(let text), .code(let text):
44 result += applying(.code, to: AttributedString(text))
45 #else
46 // `InlinePresentationIntent` is Darwin-only; elsewhere these keep their text only.
47 case .bold(let children), .italic(let children):
48 result += inline(children, &notes)
49
50 case .verbatim(let text), .code(let text):
51 result += AttributedString(text)
52 #endif
53
42 // Underline and strikethrough have no Foundation-portable attribute (the 54 // Underline and strikethrough have no Foundation-portable attribute (the
43 // underlineStyle/strikethroughStyle keys live in the UIKit/AppKit scopes), so they 55 // underlineStyle/strikethroughStyle keys live in the UIKit/AppKit scopes), so they
44 // travel as roles the UI layer applies. 56 // travel as roles the UI layer applies.
@@ -48,9 +60,6 @@ public struct OrgAttributedStringRenderer: Sendable {
48 case .strikeThrough(let children): 60 case .strikeThrough(let children):
49 result += applying(.strikeThrough, to: inline(children, &notes)) 61 result += applying(.strikeThrough, to: inline(children, &notes))
50 62
51 case .verbatim(let text), .code(let text):
52 result += applying(.code, to: AttributedString(text))
53
54 case .superscript(let children): 63 case .superscript(let children):
55 // No portable superscript attribute; mark it so a UI layer can raise it. 64 // No portable superscript attribute; mark it so a UI layer can raise it.
56 result += applying(.superscript, to: inline(children, &notes)) 65 result += applying(.superscript, to: inline(children, &notes))
@@ -92,6 +101,7 @@ public struct OrgAttributedStringRenderer: Sendable {
92 101
93 // MARK: - Nesting 102 // MARK: - Nesting
94 103
104 #if canImport(Darwin)
95 /// Add an intent to every run, keeping intents the children already carry. Assigning 105 /// Add an intent to every run, keeping intents the children already carry. Assigning
96 /// over the whole range instead would flatten `*bold /italic/*` to bold alone. 106 /// over the whole range instead would flatten `*bold /italic/*` to bold alone.
97 private func applying( 107 private func applying(
@@ -104,6 +114,7 @@ public struct OrgAttributedStringRenderer: Sendable {
104 } 114 }
105 return result 115 return result
106 } 116 }
117 #endif
107 118
108 /// Mark runs that carry no role yet. A role is a single slot, so the innermost — the more 119 /// Mark runs that carry no role yet. A role is a single slot, so the innermost — the more
109 /// specific — wins; org nests two role-bearing markups (`_+both+_`) rarely enough that a 120 /// specific — wins; org nests two role-bearing markups (`_+both+_`) rarely enough that a
Sources/OrgSwift/AST/OrgInlineParser.swift +20 −11
@@ -262,10 +262,16 @@ extension OrgParser {
262 .contains { lower.hasSuffix($0) } 262 .contains { lower.hasSuffix($0) }
263 } 263 }
264 264
265 private static let footnoteReferencePattern = /^\[fn:([A-Za-z0-9_-]+)(?::([^\]]*))?\]/
266 private static let datePattern = /(\d{4}-\d{2}-\d{2})/
267 private static let timePattern = /(\d{2}:\d{2})(?:-(\d{2}:\d{2}))?/
268 private static let emailPattern = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/
269 private static let environmentEndPattern = /\\end\{(\w+)\}/
270
265 private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { 271 private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
266 guard chars[start...].starts(with: "[fn:") else { return nil } 272 guard chars[start...].starts(with: "[fn:") else { return nil }
267 let rest = String(chars[start...]) 273 let rest = String(chars[start...])
268 guard let match = rest.firstMatch(of: /^\[fn:([A-Za-z0-9_-]+)(?::([^\]]*))?\]/) else { return nil } 274 guard let match = rest.firstMatch(of: footnoteReferencePattern) else { return nil }
269 let label = String(match.1) 275 let label = String(match.1)
270 // An inline footnote defines its note where it is used; parse that text as content. 276 // An inline footnote defines its note where it is used; parse that text as content.
271 let inline = match.2.map { parseInline(String($0)) } 277 let inline = match.2.map { parseInline(String($0)) }
@@ -284,12 +290,12 @@ extension OrgParser {
284 body.append(chars[j]); j += 1 290 body.append(chars[j]); j += 1
285 } 291 }
286 guard j < chars.count else { return nil } 292 guard j < chars.count else { return nil }
287 guard let dateMatch = body.firstMatch(of: /(\d{4}-\d{2}-\d{2})/) else { return nil } 293 guard let dateMatch = body.firstMatch(of: datePattern) else { return nil }
288 294
289 let date = String(dateMatch.1) 295 let date = String(dateMatch.1)
290 var time: String? 296 var time: String?
291 var endTime: String? 297 var endTime: String?
292 if let timeMatch = body.firstMatch(of: /(\d{2}:\d{2})(?:-(\d{2}:\d{2}))?/) { 298 if let timeMatch = body.firstMatch(of: timePattern) {
293 time = String(timeMatch.1) 299 time = String(timeMatch.1)
294 if let end = timeMatch.2 { endTime = String(end) } 300 if let end = timeMatch.2 { endTime = String(end) }
295 } 301 }
@@ -303,7 +309,7 @@ extension OrgParser {
303 var k = next + 3 309 var k = next + 3
304 var second = "" 310 var second = ""
305 while k < chars.count, chars[k] != closing { second.append(chars[k]); k += 1 } 311 while k < chars.count, chars[k] != closing { second.append(chars[k]); k += 1 }
306 if k < chars.count, let endMatch = second.firstMatch(of: /(\d{4}-\d{2}-\d{2})/) { 312 if k < chars.count, let endMatch = second.firstMatch(of: datePattern) {
307 endDate = String(endMatch.1) 313 endDate = String(endMatch.1)
308 next = k + 1 314 next = k + 1
309 } 315 }
@@ -314,12 +320,15 @@ extension OrgParser {
314 } 320 }
315 321
316 private static func scanBareURL(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { 322 private static func scanBareURL(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
317 // Matched on the word alone, after a cheap prefix test: copying the rest of the run 323 // `^https?:\/\/[^\s<>()\[\]]+`
318 // at every `h` made long text quadratic.
319 guard chars[start...].starts(with: "http") else { return nil } 324 guard chars[start...].starts(with: "http") else { return nil }
320 let rest = String(chars[start..<(chars[start...].firstIndex(where: \.isWhitespace) ?? chars.count)]) 325 var j = start + 4
321 guard let match = rest.firstMatch(of: /^https?:\/\/[^\s<>()\[\]]+/) else { return nil } 326 if j < chars.count, chars[j] == "s" { j += 1 }
322 var url = String(rest[match.range]) 327 guard chars[j...].starts(with: "://") else { return nil }
328 j += 3
329 let tail = chars[j...].prefix(while: { !$0.isWhitespace && !"<>()[]".contains($0) })
330 guard !tail.isEmpty else { return nil }
331 var url = String(chars[start..<tail.endIndex])
323 while let last = url.last, ".,;:!?".contains(last) { url.removeLast() } 332 while let last = url.last, ".,;:!?".contains(last) { url.removeLast() }
324 return (.link(OrgLink(target: .external(url), description: nil)), start + url.count) 333 return (.link(OrgLink(target: .external(url), description: nil)), start + url.count)
325 } 334 }
@@ -336,7 +345,7 @@ extension OrgParser {
336 let local = chars[start...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || "._%+-".contains($0)) }) 345 let local = chars[start...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || "._%+-".contains($0)) })
337 guard !local.isEmpty, start + local.count < chars.count, chars[start + local.count] == "@" else { return nil } 346 guard !local.isEmpty, start + local.count < chars.count, chars[start + local.count] == "@" else { return nil }
338 let rest = String(chars[start..<(chars[start...].firstIndex(where: \.isWhitespace) ?? chars.count)]) 347 let rest = String(chars[start..<(chars[start...].firstIndex(where: \.isWhitespace) ?? chars.count)])
339 guard let match = rest.firstMatch(of: /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/) else { 348 guard let match = rest.firstMatch(of: emailPattern) else {
340 return nil 349 return nil
341 } 350 }
342 let address = String(rest[match.range]) 351 let address = String(rest[match.range])
@@ -399,7 +408,7 @@ extension OrgParser {
399 408
400 /// Where the run's last `\end{name}` starts, in characters, and its name. 409 /// Where the run's last `\end{name}` starts, in characters, and its name.
401 private static func lastEnvironmentEnd(_ text: String) -> (offset: Int, name: String)? { 410 private static func lastEnvironmentEnd(_ text: String) -> (offset: Int, name: String)? {
402 guard text.contains(#"\end{"#), let last = text.matches(of: /\\end\{(\w+)\}/).last else { return nil } 411 guard text.contains(#"\end{"#), let last = text.matches(of: environmentEndPattern).last else { return nil }
403 return (text.distance(from: text.startIndex, to: last.range.lowerBound), String(last.1)) 412 return (text.distance(from: text.startIndex, to: last.range.lowerBound), String(last.1))
404 } 413 }
405 414
Sources/OrgSwift/AST/OrgParser.swift +37 −12
@@ -107,8 +107,8 @@ public enum OrgParser {
107 /// A heading, horizontal rule, footnote definition, or standalone image on 107 /// A heading, horizontal rule, footnote definition, or standalone image on
108 /// this line. Returns false if the line is none of those. 108 /// this line. Returns false if the line is none of those.
109 mutating func parseSingleLine(_ trimmed: String) -> Bool { 109 mutating func parseSingleLine(_ trimmed: String) -> Bool {
110 if let match = trimmed.firstMatch(of: /^(\*{1,6})\s+(.+)$/) { 110 if let (stars, rest) = OrgParser.headingLine(trimmed) {
111 document.elements.append(.heading(OrgParser.parseHeading(stars: match.1.count, rest: String(match.2)))) 111 document.elements.append(.heading(OrgParser.parseHeading(stars: stars, rest: String(rest))))
112 } else if isOrgHorizontalRule(trimmed) { 112 } else if isOrgHorizontalRule(trimmed) {
113 document.elements.append(.horizontalRule) 113 document.elements.append(.horizontalRule)
114 } else if let def = orgFootnoteDefinition(in: trimmed) { 114 } else if let def = orgFootnoteDefinition(in: trimmed) {
@@ -178,7 +178,8 @@ public enum OrgParser {
178 private static func startsNewConstruct(_ trimmed: String, raw: String) -> Bool { 178 private static func startsNewConstruct(_ trimmed: String, raw: String) -> Bool {
179 // A keyword or a comment; `#12 fixed this` is prose. 179 // A keyword or a comment; `#12 fixed this` is prose.
180 if trimmed.hasPrefix("#+") || trimmed == "#" || trimmed.hasPrefix("# ") { return true } 180 if trimmed.hasPrefix("#+") || trimmed == "#" || trimmed.hasPrefix("# ") { return true }
181 if trimmed.firstMatch(of: /^\*{1,6}\s+/) != nil { return true } 181 let stars = trimmed.prefix(while: { $0 == "*" })
182 if (1...6).contains(stars.count), trimmed[stars.endIndex...].first?.isWhitespace == true { return true }
182 if isOrgHorizontalRule(trimmed) { return true } 183 if isOrgHorizontalRule(trimmed) { return true }
183 if isTableLine(trimmed) { return true } 184 if isTableLine(trimmed) { return true }
184 if orgFootnoteDefinition(in: trimmed) != nil { return true } 185 if orgFootnoteDefinition(in: trimmed) != nil { return true }
@@ -186,19 +187,31 @@ public enum OrgParser {
186 return false 187 return false
187 } 188 }
188 189
190 /// `^(\*{1,6})\s+(.+)$`: a heading's star count and the rest of its line.
191 private static func headingLine(_ trimmed: String) -> (stars: Int, rest: Substring)? {
192 let stars = trimmed.prefix(while: { $0 == "*" })
193 guard (1...6).contains(stars.count), let rest = textAfterWhitespace(trimmed[stars.endIndex...]) else {
194 return nil
195 }
196 return (stars.count, rest)
197 }
198
189 // MARK: - LaTeX block 199 // MARK: - LaTeX block
190 200
201 private static let latexBeginLine = /^\\begin\{([^}]+)\}$/.ignoresCase()
202 private static let latexEndLine = /^\\end\{([^}]+)\}$/.ignoresCase()
203
191 /// The environment a `\begin{name}` line opens, as go-org's lexer reads it (any case). 204 /// The environment a `\begin{name}` line opens, as go-org's lexer reads it (any case).
192 private static func latexBegin(_ trimmed: String) -> String? { 205 private static func latexBegin(_ trimmed: String) -> String? {
193 guard trimmed.hasPrefix("\\") else { return nil } 206 guard trimmed.hasPrefix("\\") else { return nil }
194 return trimmed.firstMatch(of: /^\\begin\{([^}]+)\}$/.ignoresCase()).map { String($0.1).lowercased() } 207 return trimmed.firstMatch(of: latexBeginLine).map { String($0.1).lowercased() }
195 } 208 }
196 209
197 /// The environment a `\end{name}` line closes. Like go-org's, it ends a paragraph 210 /// The environment a `\end{name}` line closes. Like go-org's, it ends a paragraph
198 /// whether or not a block is open. 211 /// whether or not a block is open.
199 private static func latexEnd(_ trimmed: String) -> String? { 212 private static func latexEnd(_ trimmed: String) -> String? {
200 guard trimmed.hasPrefix("\\") else { return nil } 213 guard trimmed.hasPrefix("\\") else { return nil }
201 return trimmed.firstMatch(of: /^\\end\{([^}]+)\}$/.ignoresCase()).map { String($0.1).lowercased() } 214 return trimmed.firstMatch(of: latexEndLine).map { String($0.1).lowercased() }
202 } 215 }
203 216
204 /// Each environment's `\end{name}` lines, in order, found in one pass so an opener 217 /// Each environment's `\end{name}` lines, in order, found in one pass so an opener
@@ -244,9 +257,12 @@ public enum OrgParser {
244 body = String(body.dropFirst(keyword.count)).trimmingCharacters(in: .whitespaces) 257 body = String(body.dropFirst(keyword.count)).trimmingCharacters(in: .whitespaces)
245 break 258 break
246 } 259 }
247 if let match = body.firstMatch(of: /^\[#([A-Z])\]\s*/) { 260 // `^\[#([A-Z])\]\s*`
248 priority = Character(String(match.1)) 261 let cookie = Array(body.prefix(4))
249 body = String(body[match.range.upperBound...]) 262 if cookie.count == 4, cookie[0] == "[", cookie[1] == "#", cookie[3] == "]",
263 cookie[2].isASCII, cookie[2].isUppercase {
264 priority = cookie[2]
265 body = String(body.dropFirst(4).drop(while: \.isWhitespace))
250 } 266 }
251 let (title, tags) = splitHeadingTags(body) 267 let (title, tags) = splitHeadingTags(body)
252 return OrgHeading(level: stars, todo: todo, priority: priority, 268 return OrgHeading(level: stars, todo: todo, priority: priority,
@@ -410,10 +426,12 @@ public enum OrgParser {
410 426
411 // MARK: - Helpers 427 // MARK: - Helpers
412 428
429 private static let attributePattern = try? NSRegularExpression(
430 pattern: #":([A-Za-z_][A-Za-z0-9_-]*)\s+("[^"]*"|\S+)"#
431 )
432
413 private static func parseAttributes(_ value: String) -> [(key: String, value: String)] { 433 private static func parseAttributes(_ value: String) -> [(key: String, value: String)] {
414 guard let regex = try? NSRegularExpression(pattern: #":([A-Za-z_][A-Za-z0-9_-]*)\s+("[^"]*"|\S+)"#) else { 434 guard let regex = attributePattern else { return [] }
415 return []
416 }
417 let ns = value as NSString 435 let ns = value as NSString
418 return regex.matches(in: value, range: NSRange(location: 0, length: ns.length)).map { m in 436 return regex.matches(in: value, range: NSRange(location: 0, length: ns.length)).map { m in
419 var raw = ns.substring(with: m.range(at: 2)) 437 var raw = ns.substring(with: m.range(at: 2))
@@ -425,7 +443,14 @@ public enum OrgParser {
425 private static func stripMarker(_ line: String) -> String { 443 private static func stripMarker(_ line: String) -> String {
426 let trimmed = line.trimmingCharacters(in: .whitespaces) 444 let trimmed = line.trimmingCharacters(in: .whitespaces)
427 if trimmed.hasPrefix("- ") || trimmed.hasPrefix("+ ") { return String(trimmed.dropFirst(2)) } 445 if trimmed.hasPrefix("- ") || trimmed.hasPrefix("+ ") { return String(trimmed.dropFirst(2)) }
428 if let match = trimmed.firstMatch(of: /^\d+[.)]\s+(.*)$/) { return String(match.1) } 446 // `^\d+[.)]\s+(.*)$`
447 let digits = trimmed.prefix(while: \.isNumber)
448 let afterDigits = trimmed[digits.endIndex...]
449 if !digits.isEmpty, afterDigits.first == "." || afterDigits.first == ")",
450 afterDigits.dropFirst().first?.isWhitespace == true {
451 let text = afterDigits.dropFirst().drop(while: \.isWhitespace)
452 if !text.contains(where: \.isNewline) { return String(text) }
453 }
429 return trimmed 454 return trimmed
430 } 455 }
431 456
Sources/OrgSwift/Escaping.swift +40 −11
@@ -62,24 +62,53 @@ private func sanitizeReadmeURLString(
62 return trimmedURL 62 return trimmedURL
63} 63}
64 64
65// MARK: - Regex Helpers 65// MARK: - Line Scanners
66 66
67// These run on every line, so they scan by hand rather than through a regex. Each doc comment
68// gives the pattern it implements; the character classes keep Swift Regex's meaning, where an
69// ASCII class matches only an ASCII character, `.` anything but a newline, and `\s` and `\d`
70// `Character.isWhitespace` and `Character.isNumber`.
71
72/// `^#\+([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$`, the keyword lowercased and the value trimmed.
67func orgKeywordDirective(in line: String) -> (keyword: String, value: String)? { 73func orgKeywordDirective(in line: String) -> (keyword: String, value: String)? {
68 guard let match = line.firstMatch(of: /^#\+([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/) else { 74 guard line.hasPrefix("#+") else { return nil }
69 return nil 75 let rest = line.dropFirst(2)
70 } 76 guard let first = rest.first, isASCIILetter(first) else { return nil }
77 let keyword = rest.prefix(while: { isASCIIWordCharacter($0) || $0 == "-" })
78 let afterKeyword = rest[keyword.endIndex...]
79 guard afterKeyword.first == ":" else { return nil }
80 let value = afterKeyword.dropFirst().drop(while: \.isWhitespace)
81 guard !value.contains(where: \.isNewline) else { return nil }
71 return ( 82 return (
72 keyword: String(match.1).lowercased(), 83 keyword: keyword.lowercased(),
73 value: String(match.2).trimmingCharacters(in: .whitespaces) 84 value: String(value).trimmingCharacters(in: .whitespaces)
74 ) 85 )
75} 86}
76 87
88/// `^\s*-{5,}\s*$`
77func isOrgHorizontalRule(_ line: String) -> Bool { 89func isOrgHorizontalRule(_ line: String) -> Bool {
78 matchesRegex(line, pattern: #"^\s*-{5,}\s*$"#) 90 let dashes = line.drop(while: \.isWhitespace).prefix(while: { $0 == "-" })
91 return dashes.count >= 5 && line[dashes.endIndex...].allSatisfy(\.isWhitespace)
92}
93
94/// What `\s+(.+)$` captures at the start of `text`: the rest of the line after at least one
95/// whitespace character. A run of only whitespace gives up its last character, as the
96/// regex does when it backtracks.
97func textAfterWhitespace(_ text: Substring) -> Substring? {
98 guard let first = text.first, first.isWhitespace else { return nil }
99 let rest = text.drop(while: \.isWhitespace)
100 if rest.isEmpty {
101 guard text.count >= 2, let last = text.last, !last.isNewline else { return nil }
102 return text.suffix(1)
103 }
104 return rest.contains(where: \.isNewline) ? nil : rest
105}
106
107func isASCIILetter(_ c: Character) -> Bool {
108 c.isASCII && c.isLetter
79} 109}
80 110
81func matchesRegex(_ text: String, pattern: String) -> Bool { 111/// `[A-Za-z0-9_]`
82 guard let regex = try? NSRegularExpression(pattern: pattern) else { return false } 112func isASCIIWordCharacter(_ c: Character) -> Bool {
83 let range = NSRange(location: 0, length: (text as NSString).length) 113 c.isASCII && (c.isLetter || c.isNumber || c == "_")
84 return regex.firstMatch(in: text, range: range) != nil
85} 114}
Sources/OrgSwift/Footnotes.swift +9 −2
@@ -2,9 +2,16 @@ import Foundation
2 2
3/// Detect a reference-style footnote definition line: `[fn:label] text…`. Returns the 3/// Detect a reference-style footnote definition line: `[fn:label] text…`. Returns the
4/// label and the definition text, or nil if the line is not one. 4/// label and the definition text, or nil if the line is not one.
5///
6/// `^\[fn:([A-Za-z0-9_-]+)\]\s+(.+)$`
5func orgFootnoteDefinition(in line: String) -> (label: String, text: String)? { 7func orgFootnoteDefinition(in line: String) -> (label: String, text: String)? {
6 guard let match = line.firstMatch(of: /^\[fn:([A-Za-z0-9_-]+)\]\s+(.+)$/) else { 8 guard line.hasPrefix("[fn:") else { return nil }
9 let rest = line.dropFirst(4)
10 let label = rest.prefix(while: { isASCIIWordCharacter($0) || $0 == "-" })
11 let afterLabel = rest[label.endIndex...]
12 guard !label.isEmpty, afterLabel.first == "]",
13 let text = textAfterWhitespace(afterLabel.dropFirst()) else {
7 return nil 14 return nil
8 } 15 }
9 return (String(match.1), String(match.2)) 16 return (String(label), String(text))
10} 17}
Sources/OrgSwift/Lists.swift +6 −2
@@ -1,8 +1,12 @@
1import Foundation 1import Foundation
2 2
3/// `^(\d+)\.\s+(.+)$`
3func orderedListItem(in line: String) -> String? { 4func orderedListItem(in line: String) -> String? {
4 guard let match = line.firstMatch(of: /^(\d+)\.\s+(.+)$/) else { return nil } 5 let digits = line.prefix(while: \.isNumber)
5 return String(match.2) 6 let afterDigits = line[digits.endIndex...]
7 guard !digits.isEmpty, afterDigits.first == ".",
8 let text = textAfterWhitespace(afterDigits.dropFirst()) else { return nil }
9 return String(text)
6} 10}
7 11
8/// True if a line (already outdented to its level) starts a list item at column 0. 12/// True if a line (already outdented to its level) starts a list item at column 0.
Sources/OrgSwift/OrgRenderer.swift +15 −3
@@ -129,10 +129,22 @@ public enum OrgRenderer {
129/// Split an org heading's trailing `:tag1:tag2:` off its title. Tags are the final 129/// Split an org heading's trailing `:tag1:tag2:` off its title. Tags are the final
130/// whitespace-separated run of colon-delimited words; a heading without them returns its 130/// whitespace-separated run of colon-delimited words; a heading without them returns its
131/// text unchanged and no tags. 131/// text unchanged and no tags.
132///
133/// `^(.*?)\s+(:(?:[A-Za-z0-9_@#%]+:)+)$`: tags hold no whitespace, so they are the last
134/// whitespace-separated word, and the lazy title stops where the whitespace before it starts.
132func splitHeadingTags(_ heading: String) -> (title: String, tags: [String]) { 135func splitHeadingTags(_ heading: String) -> (title: String, tags: [String]) {
133 guard let match = heading.firstMatch(of: /^(.*?)\s+(:(?:[A-Za-z0-9_@#%]+:)+)$/) else { 136 guard let space = heading.lastIndex(where: \.isWhitespace) else { return (heading, []) }
137 let tagText = heading[heading.index(after: space)...]
138 guard tagText.count >= 3, tagText.first == ":", tagText.last == ":", !tagText.contains("::"),
139 tagText.allSatisfy({ $0 == ":" || isASCIIWordCharacter($0) || "@#%".contains($0) }) else {
134 return (heading, []) 140 return (heading, [])
135 } 141 }
136 let tags = String(match.2).split(separator: ":").map(String.init).filter { !$0.isEmpty } 142 var titleEnd = space
137 return (String(match.1).trimmingCharacters(in: .whitespaces), tags) 143 while titleEnd > heading.startIndex, heading[heading.index(before: titleEnd)].isWhitespace {
144 titleEnd = heading.index(before: titleEnd)
145 }
146 let title = heading[..<titleEnd]
147 guard !title.contains(where: \.isNewline) else { return (heading, []) }
148 let tags = tagText.split(separator: ":").map(String.init)
149 return (String(title).trimmingCharacters(in: .whitespaces), tags)
138} 150}
Sources/OrgSwiftBenchmark/main.swift added +21
@@ -0,0 +1,21 @@
1import Foundation
2import OrgSwift
3
4// Times OrgRenderer.renderToHTML on a generated document. Run in release:
5// swift run -c release OrgSwiftBenchmark [sections] [iterations]
6
7let arguments = CommandLine.arguments.dropFirst().compactMap { Int($0) }
8let sections = arguments.first ?? 2000
9let iterations = arguments.dropFirst().first ?? 5
10
11let source = (0..<sections).map {
12 "* Heading \($0)\nParagraph with *bold* \($0) and ~code~ and https://example.com/\($0).\n- item\n"
13}.joined()
14
15var best = Double.infinity
16for _ in 0..<iterations {
17 let start = Date()
18 _ = OrgRenderer.renderToHTML(source)
19 best = min(best, Date().timeIntervalSince(start))
20}
21print(String(format: "%d sections, %d bytes: best of %d = %.1f ms", sections, source.utf8.count, iterations, best * 1000))