krz/org-swift

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

Commit efe22bbf66

efe22bbf66b954c421dad84b5e7707ae6a8b32d1

parent: a35aabf552

Unsigned ci/gitbay-security: success

cmc <hello@cleberg.net> · 2026-11-01 04:07 UTC

Build the HTML path with the standard library only (!15)

`OrgRenderer.renderToHTML(_:options:)` and `OrgRenderOptions` no longer use Foundation or Swift Regex, so `OrgSwift` builds with the Embedded Swift Wasm SDK:

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

An executable that links it needs `-Xlinker -lswiftUnicodeDataTables` (`Character` properties, `lowercased()`, grapheme breaking). With that, a sample program that calls `renderToHTML` links to 1.6 MB of unstripped Wasm. Run under Node's WASI, its HTML is byte-identical to the native build's.

## What changed

- Remaining regexes are hand scanners: LaTeX `\begin`/`\end` lines (case-insensitive), footnote references, timestamps (date, time, range), email, last `\end{…}`, and the `#+attr_html` `NSRegularExpression` (scanned by scalar with ICU's `\s`).
- `Text.swift` has stdlib replacements for `trimmingCharacters` (`.whitespaces` / `.whitespacesAndNewlines`, scalar-based, with Foundation's exact sets including U+200B), `replacingOccurrences`, `components(separatedBy:)`, `range(of:)`/`contains`, and `addingPercentEncoding(.urlPathAllowed)` (which encodes `:`). `caseInsensitiveCompare` became `lowercased() ==`. `NSString` path operations became split/join, which `normalizeRepositoryPath` already normalizes.
- `URLComponents` in the link/image sanitizer is replaced by an RFC 3986 scanner that reproduces its output. A URL whose components are valid comes back as written. Otherwise each invalid component is re-encoded as a whole (`%` included) and an empty port is dropped. A bad host or port returns nil (the raw string, as before).
- `OrgAttributedStringRenderer` (and `OrgRole`, the attribute keys) is under `#if canImport(Foundation)`. The macOS/iOS API and `OrgSwiftUI` are unchanged. `CodeHighlighter` is still an existential; 6.4.2 Embedded accepts it.
- Embedded language restrictions: key-path closures became explicit closures.

## Differences from Foundation

Checked against the old Foundation code on 400k random URL/text strings and against `main` on 400k random documents. Every remaining difference is in one of these groups:

1. **HTML escaping works by scalar.** `replacingOccurrences` skipped a `"`, `<`, `>`, `&` or `'` followed by a combining mark. On `main`, `[[x"́ onmouseover=alert(1) y]]` renders `<a href="x"́ onmouseover=alert(1) y">`, which closes the attribute. Now `&quot;`. Test: `quoteBeforeCombiningMarkIsEscaped`.
2. **A scheme outside the allowlist is rejected even when the rest does not parse.** On `main`, `URLComponents` returns nil for `javascript://a b/%0aalert(1)`, so the sanitizer treated it as a relative path and emitted it as the `href`. Test added to `resolvedURLsAreAvailableToNonOrgCallers`.
3. **A non-ASCII host stays as written** instead of being converted to Punycode (`https://é/` was `https://xn--9ca/`). Path, query and fragment are encoded as before. About 0.5% of random documents in the fuzz, all with such a host.
4. A CR followed by a combining mark now ends a line (`replacingOccurrences` didn't match it).

Hosts from `OrgRenderOptions.host` are used as given (`URLComponents` would have converted a non-ASCII one).

## Checks

- `swift test`: 91 tests pass. `ConformanceTests` is unchanged (12 of 13 match orgo, `outofscope` diverges).
- Native, full Wasm SDK and Embedded Wasm SDK builds succeed with no warnings.
- `swift run -c release OrgSwiftBenchmark` (2000 sections, 176 KB): 91 ms on `main`, 44 ms here.

## Left on Foundation

- `OrgAttributedStringRenderer`, `OrgRole`, `OrgRoleAttribute`, `OrgMathAttribute`, `AttributeScopes.OrgAttributes` (need `AttributedString`).
- `OrgSwiftUI` (whole product).
- `OrgSwiftBenchmark` (`String(format:)`, `Date`), native only.

Layout: unified · split

ARCHITECTURE.md +2 −1
@@ -4,7 +4,7 @@ OrgSwift parses org into an element tree and renders that tree. Parsing happens
44output format is a walk over the result.
55
66```
7Sources/OrgSwift/ Foundation only
7Sources/OrgSwift/ standard library; Foundation for AttributedString
88 AST/
99 OrgDocument.swift the element tree
1010 OrgParser.swift source → OrgDocument (blocks)
@@ -16,6 +16,7 @@ Sources/OrgSwift/ Foundation only
1616 OrgRenderer.swift the public entry point, plus OrgRenderOptions
1717 Escaping.swift, Links.swift, … shared helpers: escaping, URL sanitising and
1818 repository-relative resolution, line predicates
19 Text.swift trimming, searching, line splitting, percent-encoding
1920 Skeleton.swift the HTML → semantic-skeleton reduction used by tests
2021
2122Sources/OrgSwiftUI/ depends on OrgSwift
README.md +4 −2
@@ -3,8 +3,10 @@
33A dependency-free Swift library that renders a practical subset of
44[org-mode](https://orgmode.org). Two products:
55
6- **`OrgSwift`** — org to sanitized HTML or `AttributedString`. Pure Foundation,
7 no SwiftUI, WebKit, UIKit, or third-party packages.
6- **`OrgSwift`** — org to sanitized HTML or `AttributedString`. No SwiftUI, WebKit,
7 UIKit, or third-party packages. The HTML path uses only the standard library and
8 builds with the Embedded Swift Wasm SDK (link `-lswiftUnicodeDataTables`);
9 `OrgAttributedStringRenderer` needs Foundation.
810- **`OrgSwiftUI`** — org to native SwiftUI views, no web view involved.
911
1012Originally extracted from the hand-rolled renderer in the Hutch iOS client so it
Sources/OrgSwift/AST/OrgAttributedStringRenderer.swift +2
@@ -1,3 +1,4 @@
1#if canImport(Foundation)
12import Foundation
23
34/// Renders inline org content to `AttributedString` — the native counterpart to the HTML
@@ -181,3 +182,4 @@ public extension AttributedString {
181182 set { self[OrgRoleAttribute.self] = newValue }
182183 }
183184}
185#endif
Sources/OrgSwift/AST/OrgDocument.swift +1 −3
@@ -1,5 +1,3 @@
1import Foundation
2
31// The org element tree — the document model, deliberately mirroring orgo's `model.rs`
42// (`Element`/`Object`, `TableRow::{Cells, Rule}`, `ListKind`, `Checkbox`) so the two can be
53// compared tree-to-tree later, instead of only through rendered HTML.
@@ -21,7 +19,7 @@ public struct OrgDocument: Sendable, Equatable {
2119 }
2220
2321 public func keyword(_ name: String) -> String? {
24 keywords.first { $0.key.caseInsensitiveCompare(name) == .orderedSame }?.value
22 keywords.first { $0.key.lowercased() == name.lowercased() }?.value
2523 }
2624
2725 public static func == (lhs: OrgDocument, rhs: OrgDocument) -> Bool {
Sources/OrgSwift/AST/OrgFootnotes.swift −2
@@ -1,5 +1,3 @@
1import Foundation
2
31/// Assigns footnote numbers in first-reference order and holds the notes they resolve to.
42///
53/// Numbering is document-wide and order-of-use, so it belongs to the render pass rather than
Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift −2
@@ -1,5 +1,3 @@
1import Foundation
2
31/// Renders an ``OrgDocument`` to HTML by walking the tree.
42///
53/// The point of the prototype: this produces the same shape of output as the shipped
Sources/OrgSwift/AST/OrgInlineParser.swift +73 −35
@@ -1,5 +1,3 @@
1import Foundation
2
31// Inline parsing into `[OrgObject]`.
42//
53// The shipped renderer does inline work by regex-substituting HTML into an escaped string,
@@ -36,7 +34,7 @@ extension OrgParser {
3634 var plain = ""
3735 let chars = Array(text)
3836 var i = 0
39 let lastEnd = lastEnvironmentEnd(text)
37 let lastEnd = lastEnvironmentEnd(chars)
4038 // A closer that is missing once is missing for every later opener of its kind.
4139 var missing: Set<String> = []
4240
@@ -262,21 +260,49 @@ extension OrgParser {
262260 .contains { lower.hasSuffix($0) }
263261 }
264262
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
263 /// `^\[fn:([A-Za-z0-9_-]+)(?::([^\]]*))?\]`
271264 private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
272265 guard chars[start...].starts(with: "[fn:") else { return nil }
273 let rest = String(chars[start...])
274 guard let match = rest.firstMatch(of: footnoteReferencePattern) else { return nil }
275 let label = String(match.1)
276 // An inline footnote defines its note where it is used; parse that text as content.
277 let inline = match.2.map { parseInline(String($0)) }
278 let consumed = rest.distance(from: rest.startIndex, to: match.range.upperBound)
279 return (.footnoteRef(label: label, inline: inline), start + consumed)
266 let label = chars[(start + 4)...].prefix(while: { isASCIIWordCharacter($0) || $0 == "-" })
267 guard !label.isEmpty, label.endIndex < chars.count else { return nil }
268 var inline: [OrgObject]?
269 var close = label.endIndex
270 if chars[close] == ":", let end = chars[(close + 1)...].firstIndex(of: "]") {
271 // An inline footnote defines its note where it is used; parse that text as content.
272 inline = parseInline(String(chars[(close + 1)..<end]))
273 close = end
274 }
275 guard chars[close] == "]" else { return nil }
276 return (.footnoteRef(label: String(label), inline: inline), close + 1)
277 }
278
279 /// `\d{count}` at `i`.
280 private static func isDigits(_ chars: ArraySlice<Character>, at i: Int, count: Int) -> Bool {
281 i + count <= chars.endIndex && chars[i..<(i + count)].allSatisfy({ $0.isNumber })
282 }
283
284 /// The first `\d{4}-\d{2}-\d{2}`.
285 private static func firstDate(_ chars: ArraySlice<Character>) -> String? {
286 for i in chars.indices where isDigits(chars, at: i, count: 4) && i + 10 <= chars.endIndex
287 && chars[i + 4] == "-" && isDigits(chars, at: i + 5, count: 2)
288 && chars[i + 7] == "-" && isDigits(chars, at: i + 8, count: 2) {
289 return String(chars[i..<(i + 10)])
290 }
291 return nil
292 }
293
294 /// `\d{2}:\d{2}` at `i`.
295 private static func isTime(_ chars: ArraySlice<Character>, at i: Int) -> Bool {
296 i + 5 <= chars.endIndex && isDigits(chars, at: i, count: 2) && chars[i + 2] == ":"
297 && isDigits(chars, at: i + 3, count: 2)
298 }
299
300 /// The first `(\d{2}:\d{2})(?:-(\d{2}:\d{2}))?`.
301 private static func firstTime(_ chars: ArraySlice<Character>) -> (start: String, end: String?)? {
302 guard let i = chars.indices.first(where: { isTime(chars, at: $0) }) else { return nil }
303 let start = String(chars[i..<(i + 5)])
304 guard i + 5 < chars.endIndex, chars[i + 5] == "-", isTime(chars, at: i + 6) else { return (start, nil) }
305 return (start, String(chars[(i + 6)..<(i + 11)]))
280306 }
281307
282308 private static func scanTimestamp(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? {
@@ -289,15 +315,13 @@ extension OrgParser {
289315 if chars[j] == "\n" || body.count > 64 { return nil }
290316 body.append(chars[j]); j += 1
291317 }
292 guard j < chars.count else { return nil }
293 guard let dateMatch = body.firstMatch(of: datePattern) else { return nil }
318 guard j < chars.count, let date = firstDate(chars[(start + 1)..<j]) else { return nil }
294319
295 let date = String(dateMatch.1)
296320 var time: String?
297321 var endTime: String?
298 if let timeMatch = body.firstMatch(of: timePattern) {
299 time = String(timeMatch.1)
300 if let end = timeMatch.2 { endTime = String(end) }
322 if let match = firstTime(chars[(start + 1)..<j]) {
323 time = match.start
324 endTime = match.end
301325 }
302326 var next = j + 1
303327
@@ -307,10 +331,9 @@ extension OrgParser {
307331 let opening: Character = active ? "<" : "["
308332 if next + 2 < chars.count, chars[next] == "-", chars[next + 1] == "-", chars[next + 2] == opening {
309333 var k = next + 3
310 var second = ""
311 while k < chars.count, chars[k] != closing { second.append(chars[k]); k += 1 }
312 if k < chars.count, let endMatch = second.firstMatch(of: datePattern) {
313 endDate = String(endMatch.1)
334 while k < chars.count, chars[k] != closing { k += 1 }
335 if k < chars.count, let date = firstDate(chars[(next + 3)..<k]) {
336 endDate = date
314337 next = k + 1
315338 }
316339 }
@@ -344,11 +367,16 @@ extension OrgParser {
344367 // refused before the rest of the run is copied.
345368 let local = chars[start...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || "._%+-".contains($0)) })
346369 guard !local.isEmpty, start + local.count < chars.count, chars[start + local.count] == "@" else { return nil }
347 let rest = String(chars[start..<(chars[start...].firstIndex(where: \.isWhitespace) ?? chars.count)])
348 guard let match = rest.firstMatch(of: emailPattern) else {
349 return nil
350 }
351 let address = String(rest[match.range])
370 // `^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}`: the domain is the longest run that
371 // still leaves a dot and two letters at its end.
372 let at = start + local.count
373 let domain = chars[(at + 1)...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "-") })
374 guard let dot = domain.indices.reversed().first(where: { i in
375 i > domain.startIndex && chars[i] == "." && i + 2 < domain.endIndex
376 && chars[i + 1].isLetter && chars[i + 2].isLetter
377 }) else { return nil }
378 let end = domain[(dot + 1)...].prefix(while: { $0.isLetter }).endIndex
379 let address = String(chars[start..<end])
352380 // A trailing character that cannot end an address belongs to the sentence, not the link.
353381 guard !address.hasSuffix("."), !address.hasSuffix("-") else { return nil }
354382 return (.link(OrgLink(target: .external("mailto:\(address)"),
@@ -406,10 +434,20 @@ extension OrgParser {
406434 return (.math(OrgMath(tex: source, display: true, source: source)), close + closer.count)
407435 }
408436
409 /// Where the run's last `\end{name}` starts, in characters, and its name.
410 private static func lastEnvironmentEnd(_ text: String) -> (offset: Int, name: String)? {
411 guard text.contains(#"\end{"#), let last = text.matches(of: environmentEndPattern).last else { return nil }
412 return (text.distance(from: text.startIndex, to: last.range.lowerBound), String(last.1))
437 /// Where the run's last `\end{name}` (`\\end\{(\w+)\}`) starts, in characters, and its name.
438 private static func lastEnvironmentEnd(_ chars: [Character]) -> (offset: Int, name: String)? {
439 let opener = Array(#"\end{"#)
440 var i = chars.count - opener.count
441 while i >= 0 {
442 if chars[i] == "\\", chars[i..<(i + opener.count)].elementsEqual(opener) {
443 let name = chars[(i + opener.count)...].prefix(while: { $0.isLetter || $0.isNumber || $0 == "_" })
444 if !name.isEmpty, name.endIndex < chars.count, chars[name.endIndex] == "}" {
445 return (i, String(name))
446 }
447 }
448 i -= 1
449 }
450 return nil
413451 }
414452
415453 private static func firstIndex(of needle: [Character], in chars: [Character], from start: Int) -> Int? {
Sources/OrgSwift/AST/OrgParser.swift +82 −42
@@ -1,5 +1,3 @@
1import Foundation
2
31/// Parses org source into an ``OrgDocument``.
42///
53/// This is the prototype of the AST split: parsing happens once, here, and renderers walk the
@@ -8,10 +6,7 @@ import Foundation
86public enum OrgParser {
97
108 public static func parse(_ source: String) -> OrgDocument {
11 let lines = source
12 .replacingOccurrences(of: "\r\n", with: "\n")
13 .replacingOccurrences(of: "\r", with: "\n")
14 .components(separatedBy: "\n")
9 let lines = splitLines(source)
1510 var state = State(lines: lines)
1611 while state.index < lines.count {
1712 state.step()
@@ -57,7 +52,7 @@ public enum OrgParser {
5752
5853 mutating func step() {
5954 let line = lines[index]
60 let trimmed = line.trimmingCharacters(in: .whitespaces)
55 let trimmed = line.trimmingWhitespace()
6156
6257 if trimmed.isEmpty { index += 1; return }
6358
@@ -89,7 +84,7 @@ public enum OrgParser {
8984 mutating func skipPropertyDrawer() {
9085 index += 1
9186 while index < lines.count,
92 lines[index].trimmingCharacters(in: .whitespaces) != ":END:" {
87 lines[index].trimmingWhitespace() != ":END:" {
9388 index += 1
9489 }
9590 if index < lines.count { index += 1 }
@@ -158,7 +153,7 @@ public enum OrgParser {
158153 var paragraph: [String] = []
159154 while index < lines.count {
160155 let candidate = lines[index]
161 let candidateTrimmed = candidate.trimmingCharacters(in: .whitespaces)
156 let candidateTrimmed = candidate.trimmingWhitespace()
162157 // The first line is always taken: nothing above claimed it, and
163158 // leaving it would parse the same line forever.
164159 if !paragraph.isEmpty,
@@ -198,20 +193,28 @@ public enum OrgParser {
198193
199194 // MARK: - LaTeX block
200195
201 private static let latexBeginLine = /^\\begin\{([^}]+)\}$/.ignoresCase()
202 private static let latexEndLine = /^\\end\{([^}]+)\}$/.ignoresCase()
203
204196 /// The environment a `\begin{name}` line opens, as go-org's lexer reads it (any case).
205197 private static func latexBegin(_ trimmed: String) -> String? {
206 guard trimmed.hasPrefix("\\") else { return nil }
207 return trimmed.firstMatch(of: latexBeginLine).map { String($0.1).lowercased() }
198 latexEnvironmentLine(trimmed, command: "begin")
208199 }
209200
210201 /// The environment a `\end{name}` line closes. Like go-org's, it ends a paragraph
211202 /// whether or not a block is open.
212203 private static func latexEnd(_ trimmed: String) -> String? {
204 latexEnvironmentLine(trimmed, command: "end")
205 }
206
207 /// `^\\command\{([^}]+)\}$`, the command matched in any case, the name lowercased.
208 private static func latexEnvironmentLine(_ trimmed: String, command: String) -> String? {
213209 guard trimmed.hasPrefix("\\") else { return nil }
214 return trimmed.firstMatch(of: latexEndLine).map { String($0.1).lowercased() }
210 let rest = trimmed.dropFirst()
211 guard rest.count > command.count + 2,
212 zip(rest, command).allSatisfy({ $0.lowercased() == String($1) }) else { return nil }
213 let body = rest.dropFirst(command.count)
214 guard body.first == "{", body.last == "}" else { return nil }
215 let name = body.dropFirst().dropLast()
216 guard !name.contains("}") else { return nil }
217 return name.lowercased()
215218 }
216219
217220 /// Each environment's `\end{name}` lines, in order, found in one pass so an opener
@@ -219,14 +222,14 @@ public enum OrgParser {
219222 private static func latexEndLines(_ lines: [String]) -> [String: [Int]] {
220223 var ends: [String: [Int]] = [:]
221224 for (index, line) in lines.enumerated() {
222 if let name = latexEnd(line.trimmingCharacters(in: .whitespaces)) { ends[name, default: []].append(index) }
225 if let name = latexEnd(line.trimmingWhitespace()) { ends[name, default: []].append(index) }
223226 }
224227 return ends
225228 }
226229
227230 /// The line closing the block a `\begin{name}` line at `start` opens, if one follows.
228231 private static func latexBlockEnd(_ lines: [String], from start: Int, ends: [String: [Int]]) -> Int? {
229 guard let name = latexBegin(lines[start].trimmingCharacters(in: .whitespaces)),
232 guard let name = latexBegin(lines[start].trimmingWhitespace()),
230233 let candidates = ends[name] else { return nil }
231234 var low = 0, high = candidates.count
232235 while low < high {
@@ -254,7 +257,7 @@ public enum OrgParser {
254257
255258 for keyword in ["TODO", "DONE"] where body == keyword || body.hasPrefix("\(keyword) ") {
256259 todo = keyword
257 body = String(body.dropFirst(keyword.count)).trimmingCharacters(in: .whitespaces)
260 body = String(body.dropFirst(keyword.count)).trimmingWhitespace()
258261 break
259262 }
260263 // `^\[#([A-Z])\]\s*`
@@ -262,7 +265,7 @@ public enum OrgParser {
262265 if cookie.count == 4, cookie[0] == "[", cookie[1] == "#", cookie[3] == "]",
263266 cookie[2].isASCII, cookie[2].isUppercase {
264267 priority = cookie[2]
265 body = String(body.dropFirst(4).drop(while: \.isWhitespace))
268 body = String(body.dropFirst(4).drop(while: { $0.isWhitespace }))
266269 }
267270 let (title, tags) = splitHeadingTags(body)
268271 return OrgHeading(level: stars, todo: todo, priority: priority,
@@ -272,17 +275,17 @@ public enum OrgParser {
272275 // MARK: - Blocks
273276
274277 private static func parseBlock(_ lines: [String], from start: Int) -> (OrgElement?, Int) {
275 let opener = lines[start].trimmingCharacters(in: .whitespaces)
278 let opener = lines[start].trimmingWhitespace()
276279 let lower = opener.lowercased()
277280 let name = String(lower.dropFirst("#+begin_".count)).split(separator: " ").first.map(String.init) ?? ""
278281 let argument = opener
279282 .split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true)
280 .dropFirst().first.map { String($0).trimmingCharacters(in: .whitespaces) }
283 .dropFirst().first.map { String($0).trimmingWhitespace() }
281284
282285 var body: [String] = []
283286 var index = start + 1
284287 while index < lines.count {
285 let trimmed = lines[index].trimmingCharacters(in: .whitespaces).lowercased()
288 let trimmed = lines[index].trimmingWhitespace().lowercased()
286289 if trimmed == "#+end_\(name)" { index += 1; break }
287290 body.append(lines[index])
288291 index += 1
@@ -316,7 +319,7 @@ public enum OrgParser {
316319 var index = start
317320
318321 while index < lines.count {
319 let trimmed = lines[index].trimmingCharacters(in: .whitespaces)
322 let trimmed = lines[index].trimmingWhitespace()
320323 guard isTableLine(trimmed) else { break }
321324
322325 // A separator row's columns are divided by `+`, not `|`, so it needs its own
@@ -351,11 +354,11 @@ public enum OrgParser {
351354 var pendingBlanks: [String] = []
352355 // A top-level marker of the other kind starts a *separate* list: an ordered list
353356 // followed by a bullet list is two lists, not one with mixed items.
354 let startsOrdered = orderedListItem(in: lines[start].trimmingCharacters(in: .whitespaces)) != nil
357 let startsOrdered = orderedListItem(in: lines[start].trimmingWhitespace()) != nil
355358
356359 while index < lines.count {
357360 let line = lines[index]
358 let trimmed = line.trimmingCharacters(in: .whitespaces)
361 let trimmed = line.trimmingWhitespace()
359362 if trimmed.isEmpty {
360363 pendingBlanks.append(line); index += 1; continue
361364 }
@@ -375,7 +378,7 @@ public enum OrgParser {
375378
376379 /// Group a list block's lines into items, recursing for nested lists.
377380 private static func buildList(_ lines: [String]) -> OrgList {
378 let base = lines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
381 let base = lines.filter { !$0.trimmingWhitespace().isEmpty }
379382 .map(leadingWidth).min() ?? 0
380383 let normalized = lines.map { dropLeading($0, base) }
381384
@@ -393,7 +396,7 @@ public enum OrgParser {
393396
394397 let firstMarker = groups.first?.first ?? ""
395398 var kind: OrgListKind = orderedListItem(in: firstMarker) != nil ? .ordered : .unordered
396 if stripMarker(firstMarker).contains(" :: ") { kind = .description }
399 if stripMarker(firstMarker).containsText(" :: ") { kind = .description }
397400
398401 let items = groups.map { buildItem($0, kind: kind) }
399402 return OrgList(kind: kind, items: items)
@@ -408,7 +411,7 @@ public enum OrgParser {
408411
409412 // `term :: definition` splits on the item's first line only, as org requires.
410413 var term: [OrgObject]?
411 if kind == .description, let range = head.range(of: " :: ") {
414 if kind == .description, let range = head.firstRange(ofText: " :: ") {
412415 term = parseInline(String(head[..<range.lowerBound]))
413416 head = String(head[range.upperBound...])
414417 }
@@ -417,7 +420,7 @@ public enum OrgParser {
417420 // item holds whatever a document holds — several paragraphs, a nested list, a source
418421 // block, a table — in source order.
419422 let rest = Array(lines.dropFirst())
420 let childIndent = rest.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
423 let childIndent = rest.filter { !$0.trimmingWhitespace().isEmpty }
421424 .map(leadingWidth).min() ?? 0
422425 let body = ([head] + rest.map { dropLeading($0, childIndent) }).joined(separator: "\n")
423426
@@ -426,30 +429,67 @@ public enum OrgParser {
426429
427430 // MARK: - Helpers
428431
429 private static let attributePattern = try? NSRegularExpression(
430 pattern: #":([A-Za-z_][A-Za-z0-9_-]*)\s+("[^"]*"|\S+)"#
431 )
432
432 /// Each `:([A-Za-z_][A-Za-z0-9_-]*)\s+("[^"]*"|\S+)` in turn, scanned by scalar with ICU's
433 /// `\s` (tab, LF, FF, CR and the separators), as `NSRegularExpression` matched it.
433434 private static func parseAttributes(_ value: String) -> [(key: String, value: String)] {
434 guard let regex = attributePattern else { return [] }
435 let ns = value as NSString
436 return regex.matches(in: value, range: NSRange(location: 0, length: ns.length)).map { m in
437 var raw = ns.substring(with: m.range(at: 2))
435 let scalars = Array(value.unicodeScalars)
436 func isSpace(_ s: Unicode.Scalar) -> Bool {
437 switch s.value {
438 case 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0xA0, 0x1680, 0x2000...0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000:
439 return true
440 default:
441 return false
442 }
443 }
444 func isKey(_ s: Unicode.Scalar, first: Bool) -> Bool {
445 ("A"..."Z").contains(s) || ("a"..."z").contains(s) || s == "_"
446 || (!first && (("0"..."9").contains(s) || s == "-"))
447 }
448 func text(_ range: Range<Int>) -> String {
449 var text = ""
450 text.unicodeScalars.append(contentsOf: scalars[range])
451 return text
452 }
453
454 var attributes: [(key: String, value: String)] = []
455 var i = 0
456 while i < scalars.count {
457 guard scalars[i] == ":", i + 1 < scalars.count, isKey(scalars[i + 1], first: true) else {
458 i += 1
459 continue
460 }
461 var j = i + 2
462 while j < scalars.count, isKey(scalars[j], first: false) { j += 1 }
463 let keyEnd = j
464 while j < scalars.count, isSpace(scalars[j]) { j += 1 }
465 guard j > keyEnd, j < scalars.count else {
466 i += 1
467 continue
468 }
469 var end = j + 1
470 if scalars[j] == "\"", let close = scalars[end...].firstIndex(of: "\"") {
471 end = close + 1
472 } else {
473 while end < scalars.count, !isSpace(scalars[end]) { end += 1 }
474 }
475 var raw = text(j..<end)
438476 if raw.count >= 2, raw.hasPrefix("\""), raw.hasSuffix("\"") { raw = String(raw.dropFirst().dropLast()) }
439 return (ns.substring(with: m.range(at: 1)).lowercased(), raw)
477 attributes.append((text((i + 1)..<keyEnd).lowercased(), raw))
478 i = end
440479 }
480 return attributes
441481 }
442482
443483 private static func stripMarker(_ line: String) -> String {
444 let trimmed = line.trimmingCharacters(in: .whitespaces)
484 let trimmed = line.trimmingWhitespace()
445485 if trimmed.hasPrefix("- ") || trimmed.hasPrefix("+ ") { return String(trimmed.dropFirst(2)) }
446486 // `^\d+[.)]\s+(.*)$`
447 let digits = trimmed.prefix(while: \.isNumber)
487 let digits = trimmed.prefix(while: { $0.isNumber })
448488 let afterDigits = trimmed[digits.endIndex...]
449489 if !digits.isEmpty, afterDigits.first == "." || afterDigits.first == ")",
450490 afterDigits.dropFirst().first?.isWhitespace == true {
451 let text = afterDigits.dropFirst().drop(while: \.isWhitespace)
452 if !text.contains(where: \.isNewline) { return String(text) }
491 let text = afterDigits.dropFirst().drop(while: { $0.isWhitespace })
492 if !text.contains(where: { $0.isNewline }) { return String(text) }
453493 }
454494 return trimmed
455495 }
Sources/OrgSwift/AST/OrgURLResolver.swift −2
@@ -1,5 +1,3 @@
1import Foundation
2
31/// Resolves a link target or image source to a safe absolute URL string, or nil when it
42/// cannot be made safe.
53///
Sources/OrgSwift/Escaping.swift +173 −21
@@ -1,16 +1,36 @@
1import Foundation
2
31// MARK: - HTML Escaping
42
53func escapeHTML(_ text: String) -> String {
6 text.replacingOccurrences(of: "&", with: "&amp;")
7 .replacingOccurrences(of: "<", with: "&lt;")
8 .replacingOccurrences(of: ">", with: "&gt;")
9 .replacingOccurrences(of: "\"", with: "&quot;")
4 escaping(text, apostrophe: false)
105}
116
127func escapeHTMLAttribute(_ text: String) -> String {
13 escapeHTML(text).replacingOccurrences(of: "'", with: "&#39;")
8 escaping(text, apostrophe: true)
9}
10
11/// Replace `&`, `<`, `>`, `"` (and `'` when asked) by scalar, copying the runs between them.
12private func escaping(_ text: String, apostrophe: Bool) -> String {
13 var result = ""
14 let bytes = text.utf8
15 var run = bytes.startIndex
16 for i in bytes.indices {
17 let entity: String
18 switch bytes[i] {
19 case UInt8(ascii: "&"): entity = "&amp;"
20 case UInt8(ascii: "<"): entity = "&lt;"
21 case UInt8(ascii: ">"): entity = "&gt;"
22 case UInt8(ascii: "\""): entity = "&quot;"
23 case UInt8(ascii: "'") where apostrophe: entity = "&#39;"
24 default: continue
25 }
26 if result.isEmpty { result.reserveCapacity(bytes.count + 16) }
27 result += text[run..<i]
28 result += entity
29 run = bytes.index(after: i)
30 }
31 if run == bytes.startIndex { return text }
32 result += text[run...]
33 return result
1434}
1535
1636// MARK: - URL Sanitization
@@ -39,19 +59,20 @@ private func sanitizeReadmeURLString(
3959 allowedSchemes: Set<String>,
4060 allowsFragmentOnly: Bool
4161) -> String? {
42 let trimmedURL = rawURL.trimmingCharacters(in: .whitespacesAndNewlines)
62 let trimmedURL = rawURL.trimmingWhitespaceAndNewlines()
4363 guard !trimmedURL.isEmpty else { return nil }
4464
4565 if allowsFragmentOnly, trimmedURL.hasPrefix("#"), trimmedURL.count > 1 {
4666 return trimmedURL
4767 }
4868
49 if let scheme = URLComponents(string: trimmedURL)?.scheme?.lowercased() {
50 guard allowedSchemes.contains(scheme),
51 let sanitizedURL = URLComponents(string: trimmedURL)?.url?.absoluteString else {
52 return nil
53 }
54 return sanitizedURL
69 let bytes = Array(trimmedURL.utf8)
70 if let schemeEnd = urlSchemeEnd(bytes) {
71 let scheme = String(decoding: bytes[..<schemeEnd], as: UTF8.self)
72 guard allowedSchemes.contains(scheme.lowercased()) else { return nil }
73 // An allowed scheme with an authority that will not parse stays as written, as it did
74 // when `URLComponents` refused it; the scheme alone is what makes it safe.
75 return normalizedURL(bytes, schemeEnd: schemeEnd) ?? trimmedURL
5576 }
5677
5778 // No scheme → a relative reference (`diagram.png`, `docs/x`). It cannot carry a
@@ -62,6 +83,137 @@ private func sanitizeReadmeURLString(
6283 return trimmedURL
6384}
6485
86/// Where RFC 3986 `scheme` ends (at its `:`): a letter, then letters, digits, `+`, `-` or `.`.
87private func urlSchemeEnd(_ bytes: [UInt8]) -> Int? {
88 guard let colon = bytes.firstIndex(of: UInt8(ascii: ":")), colon > 0,
89 isASCIILetterByte(bytes[0]),
90 bytes[..<colon].allSatisfy({ isASCIILetterByte($0) || isASCIIDigitByte($0) || $0 == UInt8(ascii: "+")
91 || $0 == UInt8(ascii: "-") || $0 == UInt8(ascii: ".") }) else { return nil }
92 return colon
93}
94
95/// `URLComponents(string:)?.url?.absoluteString`. A URL whose components all hold only what
96/// they may comes back as written. Otherwise it is rebuilt: a component holding a character it
97/// may not, or a `%` that starts no escape, is percent-encoded whole, and an empty port is
98/// dropped. Nil where `URLComponents` gives up: a host with characters a host cannot hold, or
99/// a port that is not a number.
100private func normalizedURL(_ bytes: [UInt8], schemeEnd: Int) -> String? {
101 /// One component: the delimiter before it, its bytes, what it may hold, and what survives
102 /// re-encoding.
103 typealias Part = (delimiter: String, bytes: ArraySlice<UInt8>, valid: (UInt8) -> Bool, encoding: (UInt8) -> Bool)
104 var parts: [Part] = []
105 var i = schemeEnd + 1
106 let hasAuthority = bytes[i...].starts(with: [UInt8(ascii: "/"), UInt8(ascii: "/")])
107 var host: ArraySlice<UInt8> = []
108 var port: ArraySlice<UInt8>?
109
110 if hasAuthority {
111 i += 2
112 let end = bytes[i...].firstIndex(where: { $0 == UInt8(ascii: "/") || $0 == UInt8(ascii: "?") || $0 == UInt8(ascii: "#") })
113 ?? bytes.endIndex
114 let authority = bytes[i..<end]
115 i = end
116 var hostPort = authority
117 if let at = authority.lastIndex(of: UInt8(ascii: "@")) {
118 let userinfo = authority[..<at]
119 if let colon = userinfo.firstIndex(of: UInt8(ascii: ":")) {
120 parts.append(("", userinfo[..<colon], isUserByte, isUserByte))
121 parts.append((":", userinfo[(colon + 1)...], isUserByte, isUserByte))
122 } else {
123 parts.append(("", userinfo, isUserByte, isUserByte))
124 }
125 hostPort = authority[(at + 1)...]
126 }
127 host = hostPort
128 if let colon = hostPort.lastIndex(of: UInt8(ascii: ":")), !hostPort[colon...].contains(UInt8(ascii: "]")) {
129 port = hostPort[(colon + 1)...]
130 guard port!.allSatisfy(isASCIIDigitByte) else { return nil }
131 host = hostPort[..<colon]
132 }
133 let isIPLiteral = host.first == UInt8(ascii: "[") && host.last == UInt8(ascii: "]")
134 // A host outside ASCII stays as written; `URLComponents` would convert it to Punycode.
135 guard isIPLiteral || hasValidEscapes(host, { $0 >= 0x80 || isUnreservedByte($0) || isSubDelimByte($0) }) else {
136 return nil
137 }
138 }
139
140 let pathEnd = bytes[i...].firstIndex(where: { $0 == UInt8(ascii: "?") || $0 == UInt8(ascii: "#") }) ?? bytes.endIndex
141 let path = bytes[i..<pathEnd]
142 i = pathEnd
143 var query: ArraySlice<UInt8>?
144 var fragment: ArraySlice<UInt8>?
145 if i < bytes.endIndex, bytes[i] == UInt8(ascii: "?") {
146 let queryEnd = bytes[i...].firstIndex(of: UInt8(ascii: "#")) ?? bytes.endIndex
147 query = bytes[(i + 1)..<queryEnd]
148 i = queryEnd
149 }
150 if i < bytes.endIndex { fragment = bytes[(i + 1)...] }
151
152 let rebuild = !parts.allSatisfy({ hasValidEscapes($0.bytes, $0.valid) })
153 || !hasValidEscapes(path, isPathCharacterByte)
154 || query.map { !hasValidEscapes($0, isQueryByte) } ?? false
155 || fragment.map { !hasValidEscapes($0, isQueryByte) } ?? false
156 guard rebuild else { return String(decoding: bytes, as: UTF8.self) }
157
158 func encoded(_ component: ArraySlice<UInt8>, valid: (UInt8) -> Bool, encoding: (UInt8) -> Bool) -> [UInt8] {
159 hasValidEscapes(component, valid) ? Array(component) : percentEncodedBytes(component, allowing: encoding)
160 }
161 var result = Array(bytes[...schemeEnd])
162 if hasAuthority {
163 result += Array("//".utf8)
164 for part in parts {
165 result += Array(part.delimiter.utf8) + encoded(part.bytes, valid: part.valid, encoding: part.encoding)
166 }
167 if !parts.isEmpty { result.append(UInt8(ascii: "@")) }
168 result += host
169 if let port, !port.isEmpty { result += [UInt8(ascii: ":")] + port }
170 result += encoded(path, valid: isPathCharacterByte, encoding: isPathCharacterByte)
171 } else {
172 // Without an authority, a `:` in the first segment would read as a scheme.
173 let firstSegmentEnd = path.firstIndex(of: UInt8(ascii: "/")) ?? path.endIndex
174 if hasValidEscapes(path, isPathCharacterByte) {
175 result += path
176 } else {
177 result += percentEncodedBytes(path[..<firstSegmentEnd], allowing: isURLPathAllowedByte)
178 result += percentEncodedBytes(path[firstSegmentEnd...], allowing: isPathCharacterByte)
179 }
180 }
181 if let query { result += [UInt8(ascii: "?")] + encoded(query, valid: isQueryByte, encoding: isQueryByte) }
182 if let fragment { result += [UInt8(ascii: "#")] + encoded(fragment, valid: isQueryByte, encoding: isQueryByte) }
183 return String(decoding: result, as: UTF8.self)
184}
185
186/// Every byte is `valid`, or a `%` that starts an escape.
187private func hasValidEscapes(_ bytes: ArraySlice<UInt8>, _ valid: (UInt8) -> Bool) -> Bool {
188 var i = bytes.startIndex
189 while i < bytes.endIndex {
190 if valid(bytes[i]) {
191 i += 1
192 } else if bytes[i] == UInt8(ascii: "%"), i + 2 < bytes.endIndex,
193 isHexDigitByte(bytes[i + 1]), isHexDigitByte(bytes[i + 2]) {
194 i += 3
195 } else {
196 return false
197 }
198 }
199 return true
200}
201
202/// RFC 3986 path characters, `/` included.
203private func isPathCharacterByte(_ byte: UInt8) -> Bool {
204 isURLPathAllowedByte(byte) || byte == UInt8(ascii: ":")
205}
206
207/// A query or fragment's characters: a path's, and `?`.
208private func isQueryByte(_ byte: UInt8) -> Bool {
209 isPathCharacterByte(byte) || byte == UInt8(ascii: "?")
210}
211
212/// `CharacterSet.urlUserAllowed` (and `urlPasswordAllowed`, the same set).
213private func isUserByte(_ byte: UInt8) -> Bool {
214 isUnreservedByte(byte) || isSubDelimByte(byte)
215}
216
65217// MARK: - Line Scanners
66218
67219// These run on every line, so they scan by hand rather than through a regex. Each doc comment
@@ -77,18 +229,18 @@ func orgKeywordDirective(in line: String) -> (keyword: String, value: String)? {
77229 let keyword = rest.prefix(while: { isASCIIWordCharacter($0) || $0 == "-" })
78230 let afterKeyword = rest[keyword.endIndex...]
79231 guard afterKeyword.first == ":" else { return nil }
80 let value = afterKeyword.dropFirst().drop(while: \.isWhitespace)
81 guard !value.contains(where: \.isNewline) else { return nil }
232 let value = afterKeyword.dropFirst().drop(while: { $0.isWhitespace })
233 guard !value.contains(where: { $0.isNewline }) else { return nil }
82234 return (
83235 keyword: keyword.lowercased(),
84 value: String(value).trimmingCharacters(in: .whitespaces)
236 value: String(value).trimmingWhitespace()
85237 )
86238}
87239
88240/// `^\s*-{5,}\s*$`
89241func isOrgHorizontalRule(_ line: String) -> Bool {
90 let dashes = line.drop(while: \.isWhitespace).prefix(while: { $0 == "-" })
91 return dashes.count >= 5 && line[dashes.endIndex...].allSatisfy(\.isWhitespace)
242 let dashes = line.drop(while: { $0.isWhitespace }).prefix(while: { $0 == "-" })
243 return dashes.count >= 5 && line[dashes.endIndex...].allSatisfy({ $0.isWhitespace })
92244}
93245
94246/// What `\s+(.+)$` captures at the start of `text`: the rest of the line after at least one
@@ -96,12 +248,12 @@ func isOrgHorizontalRule(_ line: String) -> Bool {
96248/// regex does when it backtracks.
97249func textAfterWhitespace(_ text: Substring) -> Substring? {
98250 guard let first = text.first, first.isWhitespace else { return nil }
99 let rest = text.drop(while: \.isWhitespace)
251 let rest = text.drop(while: { $0.isWhitespace })
100252 if rest.isEmpty {
101253 guard text.count >= 2, let last = text.last, !last.isNewline else { return nil }
102254 return text.suffix(1)
103255 }
104 return rest.contains(where: \.isNewline) ? nil : rest
256 return rest.contains(where: { $0.isNewline }) ? nil : rest
105257}
106258
107259func isASCIILetter(_ c: Character) -> Bool {
Sources/OrgSwift/Footnotes.swift −2
@@ -1,5 +1,3 @@
1import Foundation
2
31/// Detect a reference-style footnote definition line: `[fn:label] text…`. Returns the
42/// label and the definition text, or nil if the line is not one.
53///
Sources/OrgSwift/Links.swift +12 −20
@@ -1,5 +1,3 @@
1import Foundation
2
31/// Strip org's `file:` link prefix. `[[file:diagram.png]]` targets a local path the same
42/// way `[[diagram.png]]` does; the scheme is org bookkeeping, not part of the URL.
53func normalizeOrgLinkTarget(_ target: String) -> String {
@@ -16,10 +14,10 @@ private func isRenderableImageSource(_ source: String) -> Bool {
1614/// If a whole line is just an image link with no description (`[[file:x.png]]`), return its
1715/// path (with `file:` stripped). A link carrying a description is not a standalone image.
1816func standaloneOrgImage(in line: String) -> String? {
19 let trimmed = line.trimmingCharacters(in: .whitespaces)
17 let trimmed = line.trimmingWhitespace()
2018 guard trimmed.hasPrefix("[[") && trimmed.hasSuffix("]]") else { return nil }
2119 let inner = String(trimmed.dropFirst(2).dropLast(2))
22 guard !inner.contains("][") else { return nil }
20 guard !inner.containsText("][") else { return nil }
2321 let path = normalizeOrgLinkTarget(inner)
2422 guard isRenderableImageSource(path) else { return nil }
2523 return path
@@ -35,7 +33,7 @@ func resolveRepositoryLinkURL(
3533 readmePath: String?,
3634 pathSegment: String = "blob"
3735) -> String? {
38 let trimmedSource = source.trimmingCharacters(in: .whitespacesAndNewlines)
36 let trimmedSource = source.trimmingWhitespaceAndNewlines()
3937 guard !trimmedSource.isEmpty else { return nil }
4038
4139 if trimmedSource.hasPrefix("http://") || trimmedSource.hasPrefix("https://")
@@ -63,7 +61,7 @@ func resolveRepositoryAssetURL(
6361 readmePath: String?,
6462 pathSegment: String = "blob"
6563) -> String? {
66 let trimmedSource = source.trimmingCharacters(in: .whitespacesAndNewlines)
64 let trimmedSource = source.trimmingWhitespaceAndNewlines()
6765 guard !trimmedSource.isEmpty else { return nil }
6866
6967 if trimmedSource.hasPrefix("http://") || trimmedSource.hasPrefix("https://") || trimmedSource.hasPrefix("data:") {
@@ -74,28 +72,22 @@ func resolveRepositoryAssetURL(
7472 if trimmedSource.hasPrefix("/") {
7573 relativePath = String(trimmedSource.dropFirst())
7674 } else {
77 let readmeDirectory = (readmePath as NSString?)?.deletingLastPathComponent ?? ""
75 let readmeDirectory = (readmePath ?? "").split(separator: "/").dropLast()
7876 relativePath = normalizeRepositoryPath(
79 (readmeDirectory as NSString).appendingPathComponent(trimmedSource)
77 (readmeDirectory + [trimmedSource[...]]).joined(separator: "/")
8078 )
8179 }
8280
8381 guard !relativePath.isEmpty else { return nil }
84 var components = URLComponents()
85 components.scheme = "https"
86 components.host = host
87 let encodedOwner = owner.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? owner
88 let encodedRepository = repositoryName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? repositoryName
89 let encodedRef = ref.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ref
82 let encodedOwner = percentEncoded(owner, allowing: isURLPathAllowedByte)
83 let encodedRepository = percentEncoded(repositoryName, allowing: isURLPathAllowedByte)
84 let encodedRef = percentEncoded(ref, allowing: isURLPathAllowedByte)
9085 let encodedRelativePath = relativePath
9186 .split(separator: "/", omittingEmptySubsequences: false)
92 .map { segment in
93 String(segment).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? String(segment)
94 }
87 .map { percentEncoded($0, allowing: isURLPathAllowedByte) }
9588 .joined(separator: "/")
96 let encodedSegment = pathSegment.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? pathSegment
97 components.percentEncodedPath = "/\(encodedOwner)/\(encodedRepository)/\(encodedSegment)/\(encodedRef)/\(encodedRelativePath)"
98 return components.string
89 let encodedSegment = percentEncoded(pathSegment, allowing: isURLPathAllowedByte)
90 return "https://\(host)/\(encodedOwner)/\(encodedRepository)/\(encodedSegment)/\(encodedRef)/\(encodedRelativePath)"
9991}
10092
10193private func normalizeRepositoryPath(_ path: String) -> String {
Sources/OrgSwift/Lists.swift +2 −4
@@ -1,8 +1,6 @@
1import Foundation
2
31/// `^(\d+)\.\s+(.+)$`
42func orderedListItem(in line: String) -> String? {
5 let digits = line.prefix(while: \.isNumber)
3 let digits = line.prefix(while: { $0.isNumber })
64 let afterDigits = line[digits.endIndex...]
75 guard !digits.isEmpty, afterDigits.first == ".",
86 let text = textAfterWhitespace(afterDigits.dropFirst()) else { return nil }
@@ -15,7 +13,7 @@ func isListMarkerLine(_ line: String) -> Bool {
1513}
1614
1715func isIndentedContinuationLine(_ line: String) -> Bool {
18 guard !line.trimmingCharacters(in: .whitespaces).isEmpty else { return false }
16 guard !line.trimmingWhitespace().isEmpty else { return false }
1917 guard let first = line.first else { return false }
2018 return first == " " || first == "\t"
2119}
\ No newline at end of file
Sources/OrgSwift/OrgRenderer.swift +4 −6
@@ -1,5 +1,3 @@
1import Foundation
2
31/// Produces highlighted HTML for a fenced code block. Returning `nil` makes the
42/// renderer fall back to an escaped `<pre><code>` block.
53public protocol CodeHighlighter {
@@ -133,9 +131,9 @@ public enum OrgRenderer {
133131/// `^(.*?)\s+(:(?:[A-Za-z0-9_@#%]+:)+)$`: tags hold no whitespace, so they are the last
134132/// whitespace-separated word, and the lazy title stops where the whitespace before it starts.
135133func splitHeadingTags(_ heading: String) -> (title: String, tags: [String]) {
136 guard let space = heading.lastIndex(where: \.isWhitespace) else { return (heading, []) }
134 guard let space = heading.lastIndex(where: { $0.isWhitespace }) else { return (heading, []) }
137135 let tagText = heading[heading.index(after: space)...]
138 guard tagText.count >= 3, tagText.first == ":", tagText.last == ":", !tagText.contains("::"),
136 guard tagText.count >= 3, tagText.first == ":", tagText.last == ":", !tagText.containsText("::"),
139137 tagText.allSatisfy({ $0 == ":" || isASCIIWordCharacter($0) || "@#%".contains($0) }) else {
140138 return (heading, [])
141139 }
@@ -144,7 +142,7 @@ func splitHeadingTags(_ heading: String) -> (title: String, tags: [String]) {
144142 titleEnd = heading.index(before: titleEnd)
145143 }
146144 let title = heading[..<titleEnd]
147 guard !title.contains(where: \.isNewline) else { return (heading, []) }
145 guard !title.contains(where: { $0.isNewline }) else { return (heading, []) }
148146 let tags = tagText.split(separator: ":").map(String.init)
149 return (String(title).trimmingCharacters(in: .whitespaces), tags)
147 return (String(title).trimmingWhitespace(), tags)
150148}
Sources/OrgSwift/Skeleton.swift +3 −5
@@ -11,8 +11,6 @@
1111// package's conformance test self-checks that first, by feeding each corpus `.html`
1212// through this port and requiring it to reproduce the checked-in `.skeleton`.
1313
14import Foundation
15
1614public enum OrgSkeleton {
1715 /// Elements dropped entirely: `div` is layout, `span` is per-token highlighter noise.
1816 private static let ignored: Set<String> = ["div", "span"]
@@ -53,12 +51,12 @@ public enum OrgSkeleton {
5351 i = end + 1
5452
5553 // trim → strip trailing '/' → trim
56 var raw = rawFull.trimmingCharacters(in: .whitespaces)
54 var raw = rawFull.trimmingWhitespace()
5755 if raw.hasSuffix("/") { raw.removeLast() }
58 raw = raw.trimmingCharacters(in: .whitespaces)
56 raw = raw.trimmingWhitespace()
5957
6058 if raw.hasPrefix("/") {
61 let name = raw.dropFirst().trimmingCharacters(in: .whitespaces).lowercased()
59 let name = raw.dropFirst().trimmingWhitespace().lowercased()
6260 if !ignored.contains(name) && !void.contains(name) {
6361 flushText(&text, &out)
6462 out.append("</\(name)>")
Sources/OrgSwift/Tables.swift +5 −7
@@ -1,5 +1,3 @@
1import Foundation
2
31func isTableLine(_ line: String) -> Bool {
42 line.hasPrefix("|") && line.hasSuffix("|")
53}
@@ -9,11 +7,11 @@ func parseTableRow(_ line: String) -> [String] {
97 .split(separator: "|", omittingEmptySubsequences: false)
108 .dropFirst()
119 .dropLast()
12 .map { String($0).trimmingCharacters(in: .whitespaces) }
10 .map { String($0).trimmingWhitespace() }
1311}
1412
1513func parseOrgTableSeparatorRow(_ line: String) -> [String] {
16 var content = line.trimmingCharacters(in: .whitespaces)
14 var content = line.trimmingWhitespace()
1715 if content.hasPrefix("|") {
1816 content.removeFirst()
1917 }
@@ -22,7 +20,7 @@ func parseOrgTableSeparatorRow(_ line: String) -> [String] {
2220 }
2321 return content
2422 .split(separator: "+", omittingEmptySubsequences: false)
25 .map { String($0).trimmingCharacters(in: .whitespaces) }
23 .map { String($0).trimmingWhitespace() }
2624}
2725
2826func isTableSeparatorCell(_ cell: String) -> Bool {
@@ -30,10 +28,10 @@ func isTableSeparatorCell(_ cell: String) -> Bool {
3028}
3129
3230func tableAlignment(for cell: String) -> String? {
33 let trimmed = cell.trimmingCharacters(in: .whitespaces)
31 let trimmed = cell.trimmingWhitespace()
3432 guard !trimmed.isEmpty else { return nil }
3533
36 let core = trimmed.replacingOccurrences(of: ":", with: "")
34 let core = trimmed.filter { $0 != ":" }
3735 guard !core.isEmpty, core.allSatisfy({ $0 == "-" || $0 == "+" }) else {
3836 return nil
3937 }
Sources/OrgSwift/Text.swift added +162
@@ -0,0 +1,162 @@
1// Standard-library stand-ins for the Foundation string operations the HTML path needs, so
2// OrgSwift builds where Foundation does not (Embedded Swift).
3
4// MARK: - Trimming
5
6extension String {
7 /// `trimmingCharacters(in: .whitespaces)`.
8 func trimmingWhitespace() -> String {
9 trimmingScalars(self[...], isWhitespaceScalar)
10 }
11
12 /// `trimmingCharacters(in: .whitespacesAndNewlines)`.
13 func trimmingWhitespaceAndNewlines() -> String {
14 trimmingScalars(self[...]) { isWhitespaceScalar($0) || isNewlineScalar($0) }
15 }
16}
17
18extension Substring {
19 /// `trimmingCharacters(in: .whitespaces)`.
20 func trimmingWhitespace() -> String {
21 trimmingScalars(self, isWhitespaceScalar)
22 }
23}
24
25/// Trims by scalar, as `CharacterSet` does, so a combining mark after a space survives.
26private func trimmingScalars(_ text: Substring, _ isTrimmed: (Unicode.Scalar) -> Bool) -> String {
27 let scalars = text.unicodeScalars
28 guard let first = scalars.firstIndex(where: { !isTrimmed($0) }),
29 let last = scalars.lastIndex(where: { !isTrimmed($0) }) else { return "" }
30 return String(scalars[first...last])
31}
32
33/// `CharacterSet.whitespaces`: tab, the space separators (Zs), and U+200B.
34func isWhitespaceScalar(_ scalar: Unicode.Scalar) -> Bool {
35 switch scalar.value {
36 case 0x09, 0x20, 0xA0, 0x1680, 0x2000...0x200B, 0x202F, 0x205F, 0x3000: return true
37 default: return false
38 }
39}
40
41/// `CharacterSet.newlines`.
42func isNewlineScalar(_ scalar: Unicode.Scalar) -> Bool {
43 switch scalar.value {
44 case 0x0A...0x0D, 0x85, 0x2028, 0x2029: return true
45 default: return false
46 }
47}
48
49// MARK: - Searching
50
51extension StringProtocol {
52 /// The first range of `needle`, compared by `Character`.
53 func firstRange(ofText needle: String) -> Range<Index>? {
54 guard let head = needle.first else { return startIndex..<startIndex }
55 var from = startIndex
56 while let candidate = self[from...].firstIndex(of: head) {
57 var i = candidate
58 var j = needle.startIndex
59 while i < endIndex, j < needle.endIndex, self[i] == needle[j] {
60 formIndex(after: &i)
61 needle.formIndex(after: &j)
62 }
63 if j == needle.endIndex { return candidate..<i }
64 from = index(after: candidate)
65 }
66 return nil
67 }
68
69 func containsText(_ needle: String) -> Bool {
70 firstRange(ofText: needle) != nil
71 }
72}
73
74// MARK: - Lines
75
76/// Split on `\n`, `\r\n` and `\r`, keeping empty lines, including a trailing one.
77func splitLines(_ text: String) -> [String] {
78 var lines: [String] = []
79 let bytes = text.utf8
80 var start = bytes.startIndex
81 var i = start
82 while i < bytes.endIndex {
83 let byte = bytes[i]
84 if byte == UInt8(ascii: "\n") || byte == UInt8(ascii: "\r") {
85 lines.append(String(text[start..<i]))
86 bytes.formIndex(after: &i)
87 if byte == UInt8(ascii: "\r"), i < bytes.endIndex, bytes[i] == UInt8(ascii: "\n") {
88 bytes.formIndex(after: &i)
89 }
90 start = i
91 } else {
92 bytes.formIndex(after: &i)
93 }
94 }
95 lines.append(String(text[start...]))
96 return lines
97}
98
99// MARK: - Percent-encoding
100
101/// `addingPercentEncoding(withAllowedCharacters:)`: each UTF-8 byte `allowed` rejects, and
102/// every `%`, as `%XX`.
103func percentEncoded<S: StringProtocol>(_ text: S, allowing allowed: (UInt8) -> Bool) -> String {
104 String(decoding: percentEncodedBytes(text.utf8, allowing: allowed), as: UTF8.self)
105}
106
107func percentEncodedBytes<S: Sequence<UInt8>>(_ bytes: S, allowing allowed: (UInt8) -> Bool) -> [UInt8] {
108 let hex = Array("0123456789ABCDEF".utf8)
109 var result: [UInt8] = []
110 result.reserveCapacity(bytes.underestimatedCount)
111 for byte in bytes {
112 if allowed(byte) && byte != UInt8(ascii: "%") {
113 result.append(byte)
114 } else {
115 result.append(UInt8(ascii: "%"))
116 result.append(hex[Int(byte >> 4)])
117 result.append(hex[Int(byte & 0x0F)])
118 }
119 }
120 return result
121}
122
123func isASCIILetterByte(_ byte: UInt8) -> Bool {
124 (UInt8(ascii: "A")...UInt8(ascii: "Z")).contains(byte) || (UInt8(ascii: "a")...UInt8(ascii: "z")).contains(byte)
125}
126
127func isASCIIDigitByte(_ byte: UInt8) -> Bool {
128 (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(byte)
129}
130
131func isHexDigitByte(_ byte: UInt8) -> Bool {
132 switch byte {
133 case UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "A")...UInt8(ascii: "F"),
134 UInt8(ascii: "a")...UInt8(ascii: "f"): return true
135 default: return false
136 }
137}
138
139/// RFC 3986 `unreserved`.
140func isUnreservedByte(_ byte: UInt8) -> Bool {
141 switch byte {
142 case UInt8(ascii: "A")...UInt8(ascii: "Z"), UInt8(ascii: "a")...UInt8(ascii: "z"),
143 UInt8(ascii: "0")...UInt8(ascii: "9"),
144 UInt8(ascii: "-"), UInt8(ascii: "."), UInt8(ascii: "_"), UInt8(ascii: "~"): return true
145 default: return false
146 }
147}
148
149/// RFC 3986 `sub-delims`.
150func isSubDelimByte(_ byte: UInt8) -> Bool {
151 switch byte {
152 case UInt8(ascii: "!"), UInt8(ascii: "$"), UInt8(ascii: "&"), UInt8(ascii: "'"),
153 UInt8(ascii: "("), UInt8(ascii: ")"), UInt8(ascii: "*"), UInt8(ascii: "+"),
154 UInt8(ascii: ","), UInt8(ascii: ";"), UInt8(ascii: "="): return true
155 default: return false
156 }
157}
158
159/// `CharacterSet.urlPathAllowed`, which leaves out `:`.
160func isURLPathAllowedByte(_ byte: UInt8) -> Bool {
161 isUnreservedByte(byte) || isSubDelimByte(byte) || byte == UInt8(ascii: "@") || byte == UInt8(ascii: "/")
162}
Tests/OrgSwiftTests/OrgRendererTests.swift +13
@@ -566,6 +566,19 @@ struct OrgRendererTests {
566566 // Without one there is nothing to resolve against, and the scheme allowlist rejects it.
567567 #expect(OrgRenderOptions().resolvedLinkURL("javascript:alert(1)") == nil)
568568 #expect(OrgRenderOptions().resolvedImageURL("javascript:alert(1)") == nil)
569 // Rejected by its scheme even where the rest would not parse as a URL.
570 #expect(OrgRenderOptions().resolvedLinkURL("javascript://a b/%0aalert(1)") == nil)
571 }
572
573 /// Escaping works by scalar: a quote followed by a combining mark is still a quote to an
574 /// HTML parser, so it must not survive into an attribute.
575 @Test
576 func quoteBeforeCombiningMarkIsEscaped() {
577 let quote = "\"\u{301}"
578 let html = OrgRenderer.renderToHTML("[[x\(quote) onmouseover=alert(1) y]]")
579 let escaped = "x&quot;\u{301} onmouseover"
580 #expect(!html.contains(quote))
581 #expect(html.contains(escaped))
569582 }
570583
571584 /// A resolved URL is a URL, not an HTML attribute: `&` survives for a `URL(string:)`