Commit efe22bbf66
Unsigned ci/gitbay-security: success
Layout: unified · split
ARCHITECTURE.md +2 −1
| @@ -4,7 +4,7 @@ OrgSwift parses org into an element tree and renders that tree. Parsing happens | |||
| 4 | output format is a walk over the result. | 4 | output format is a walk over the result. |
| 5 | 5 | ||
| 6 | ``` | 6 | ``` |
| 7 | Sources/OrgSwift/ Foundation only | 7 | Sources/OrgSwift/ standard library; Foundation for AttributedString |
| 8 | AST/ | 8 | AST/ |
| 9 | OrgDocument.swift the element tree | 9 | OrgDocument.swift the element tree |
| 10 | OrgParser.swift source → OrgDocument (blocks) | 10 | OrgParser.swift source → OrgDocument (blocks) |
| @@ -16,6 +16,7 @@ Sources/OrgSwift/ Foundation only | |||
| 16 | OrgRenderer.swift the public entry point, plus OrgRenderOptions | 16 | OrgRenderer.swift the public entry point, plus OrgRenderOptions |
| 17 | Escaping.swift, Links.swift, … shared helpers: escaping, URL sanitising and | 17 | Escaping.swift, Links.swift, … shared helpers: escaping, URL sanitising and |
| 18 | repository-relative resolution, line predicates | 18 | repository-relative resolution, line predicates |
| 19 | Text.swift trimming, searching, line splitting, percent-encoding | ||
| 19 | Skeleton.swift the HTML → semantic-skeleton reduction used by tests | 20 | Skeleton.swift the HTML → semantic-skeleton reduction used by tests |
| 20 | 21 | ||
| 21 | Sources/OrgSwiftUI/ depends on OrgSwift | 22 | Sources/OrgSwiftUI/ depends on OrgSwift |
README.md +4 −2
| @@ -3,8 +3,10 @@ | |||
| 3 | A dependency-free Swift library that renders a practical subset of | 3 | A dependency-free Swift library that renders a practical subset of |
| 4 | [org-mode](https://orgmode.org). Two products: | 4 | [org-mode](https://orgmode.org). Two products: |
| 5 | 5 | ||
| 6 | - **`OrgSwift`** — org to sanitized HTML or `AttributedString`. Pure Foundation, | 6 | - **`OrgSwift`** — org to sanitized HTML or `AttributedString`. No SwiftUI, WebKit, |
| 7 | no SwiftUI, WebKit, UIKit, or third-party packages. | 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. | ||
| 8 | - **`OrgSwiftUI`** — org to native SwiftUI views, no web view involved. | 10 | - **`OrgSwiftUI`** — org to native SwiftUI views, no web view involved. |
| 9 | 11 | ||
| 10 | Originally extracted from the hand-rolled renderer in the Hutch iOS client so it | 12 | Originally 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) | ||
| 1 | import Foundation | 2 | import Foundation |
| 2 | 3 | ||
| 3 | /// Renders inline org content to `AttributedString` — the native counterpart to the HTML | 4 | /// Renders inline org content to `AttributedString` — the native counterpart to the HTML |
| @@ -181,3 +182,4 @@ public extension AttributedString { | |||
| 181 | set { self[OrgRoleAttribute.self] = newValue } | 182 | set { self[OrgRoleAttribute.self] = newValue } |
| 182 | } | 183 | } |
| 183 | } | 184 | } |
| 185 | #endif | ||
Sources/OrgSwift/AST/OrgDocument.swift +1 −3
| @@ -1,5 +1,3 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // The org element tree — the document model, deliberately mirroring orgo's `model.rs` | 1 | // The org element tree — the document model, deliberately mirroring orgo's `model.rs` |
| 4 | // (`Element`/`Object`, `TableRow::{Cells, Rule}`, `ListKind`, `Checkbox`) so the two can be | 2 | // (`Element`/`Object`, `TableRow::{Cells, Rule}`, `ListKind`, `Checkbox`) so the two can be |
| 5 | // compared tree-to-tree later, instead of only through rendered HTML. | 3 | // compared tree-to-tree later, instead of only through rendered HTML. |
| @@ -21,7 +19,7 @@ public struct OrgDocument: Sendable, Equatable { | |||
| 21 | } | 19 | } |
| 22 | 20 | ||
| 23 | public func keyword(_ name: String) -> String? { | 21 | public func keyword(_ name: String) -> String? { |
| 24 | keywords.first { $0.key.caseInsensitiveCompare(name) == .orderedSame }?.value | 22 | keywords.first { $0.key.lowercased() == name.lowercased() }?.value |
| 25 | } | 23 | } |
| 26 | 24 | ||
| 27 | public static func == (lhs: OrgDocument, rhs: OrgDocument) -> Bool { | 25 | public static func == (lhs: OrgDocument, rhs: OrgDocument) -> Bool { |
Sources/OrgSwift/AST/OrgFootnotes.swift −2
| @@ -1,5 +1,3 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Assigns footnote numbers in first-reference order and holds the notes they resolve to. | 1 | /// Assigns footnote numbers in first-reference order and holds the notes they resolve to. |
| 4 | /// | 2 | /// |
| 5 | /// Numbering is document-wide and order-of-use, so it belongs to the render pass rather than | 3 | /// 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 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Renders an ``OrgDocument`` to HTML by walking the tree. | 1 | /// Renders an ``OrgDocument`` to HTML by walking the tree. |
| 4 | /// | 2 | /// |
| 5 | /// The point of the prototype: this produces the same shape of output as the shipped | 3 | /// 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 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // Inline parsing into `[OrgObject]`. | 1 | // Inline parsing into `[OrgObject]`. |
| 4 | // | 2 | // |
| 5 | // The shipped renderer does inline work by regex-substituting HTML into an escaped string, | 3 | // The shipped renderer does inline work by regex-substituting HTML into an escaped string, |
| @@ -36,7 +34,7 @@ extension OrgParser { | |||
| 36 | var plain = "" | 34 | var plain = "" |
| 37 | let chars = Array(text) | 35 | let chars = Array(text) |
| 38 | var i = 0 | 36 | var i = 0 |
| 39 | let lastEnd = lastEnvironmentEnd(text) | 37 | let lastEnd = lastEnvironmentEnd(chars) |
| 40 | // A closer that is missing once is missing for every later opener of its kind. | 38 | // A closer that is missing once is missing for every later opener of its kind. |
| 41 | var missing: Set<String> = [] | 39 | var missing: Set<String> = [] |
| 42 | 40 | ||
| @@ -262,21 +260,49 @@ extension OrgParser { | |||
| 262 | .contains { lower.hasSuffix($0) } | 260 | .contains { lower.hasSuffix($0) } |
| 263 | } | 261 | } |
| 264 | 262 | ||
| 265 | private static let footnoteReferencePattern = /^\[fn:([A-Za-z0-9_-]+)(?::([^\]]*))?\]/ | 263 | /// `^\[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 | |||
| 271 | private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { | 264 | private static func scanFootnote(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { |
| 272 | guard chars[start...].starts(with: "[fn:") else { return nil } | 265 | guard chars[start...].starts(with: "[fn:") else { return nil } |
| 273 | let rest = String(chars[start...]) | 266 | let label = chars[(start + 4)...].prefix(while: { isASCIIWordCharacter($0) || $0 == "-" }) |
| 274 | guard let match = rest.firstMatch(of: footnoteReferencePattern) else { return nil } | 267 | guard !label.isEmpty, label.endIndex < chars.count else { return nil } |
| 275 | let label = String(match.1) | 268 | var inline: [OrgObject]? |
| 276 | // An inline footnote defines its note where it is used; parse that text as content. | 269 | var close = label.endIndex |
| 277 | let inline = match.2.map { parseInline(String($0)) } | 270 | if chars[close] == ":", let end = chars[(close + 1)...].firstIndex(of: "]") { |
| 278 | let consumed = rest.distance(from: rest.startIndex, to: match.range.upperBound) | 271 | // An inline footnote defines its note where it is used; parse that text as content. |
| 279 | return (.footnoteRef(label: label, inline: inline), start + consumed) | 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)])) | ||
| 280 | } | 306 | } |
| 281 | 307 | ||
| 282 | private static func scanTimestamp(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { | 308 | private static func scanTimestamp(_ chars: [Character], from start: Int) -> (object: OrgObject, next: Int)? { |
| @@ -289,15 +315,13 @@ extension OrgParser { | |||
| 289 | if chars[j] == "\n" || body.count > 64 { return nil } | 315 | if chars[j] == "\n" || body.count > 64 { return nil } |
| 290 | body.append(chars[j]); j += 1 | 316 | body.append(chars[j]); j += 1 |
| 291 | } | 317 | } |
| 292 | guard j < chars.count else { return nil } | 318 | guard j < chars.count, let date = firstDate(chars[(start + 1)..<j]) else { return nil } |
| 293 | guard let dateMatch = body.firstMatch(of: datePattern) else { return nil } | ||
| 294 | 319 | ||
| 295 | let date = String(dateMatch.1) | ||
| 296 | var time: String? | 320 | var time: String? |
| 297 | var endTime: String? | 321 | var endTime: String? |
| 298 | if let timeMatch = body.firstMatch(of: timePattern) { | 322 | if let match = firstTime(chars[(start + 1)..<j]) { |
| 299 | time = String(timeMatch.1) | 323 | time = match.start |
| 300 | if let end = timeMatch.2 { endTime = String(end) } | 324 | endTime = match.end |
| 301 | } | 325 | } |
| 302 | var next = j + 1 | 326 | var next = j + 1 |
| 303 | 327 | ||
| @@ -307,10 +331,9 @@ extension OrgParser { | |||
| 307 | let opening: Character = active ? "<" : "[" | 331 | let opening: Character = active ? "<" : "[" |
| 308 | if next + 2 < chars.count, chars[next] == "-", chars[next + 1] == "-", chars[next + 2] == opening { | 332 | if next + 2 < chars.count, chars[next] == "-", chars[next + 1] == "-", chars[next + 2] == opening { |
| 309 | var k = next + 3 | 333 | var k = next + 3 |
| 310 | var second = "" | 334 | while k < chars.count, chars[k] != closing { k += 1 } |
| 311 | while k < chars.count, chars[k] != closing { second.append(chars[k]); k += 1 } | 335 | if k < chars.count, let date = firstDate(chars[(next + 3)..<k]) { |
| 312 | if k < chars.count, let endMatch = second.firstMatch(of: datePattern) { | 336 | endDate = date |
| 313 | endDate = String(endMatch.1) | ||
| 314 | next = k + 1 | 337 | next = k + 1 |
| 315 | } | 338 | } |
| 316 | } | 339 | } |
| @@ -344,11 +367,16 @@ extension OrgParser { | |||
| 344 | // refused before the rest of the run is copied. | 367 | // refused before the rest of the run is copied. |
| 345 | let local = chars[start...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || "._%+-".contains($0)) }) | 368 | let local = chars[start...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || "._%+-".contains($0)) }) |
| 346 | guard !local.isEmpty, start + local.count < chars.count, chars[start + local.count] == "@" else { return nil } | 369 | 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)]) | 370 | // `^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}`: the domain is the longest run that |
| 348 | guard let match = rest.firstMatch(of: emailPattern) else { | 371 | // still leaves a dot and two letters at its end. |
| 349 | return nil | 372 | let at = start + local.count |
| 350 | } | 373 | let domain = chars[(at + 1)...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "-") }) |
| 351 | let address = String(rest[match.range]) | 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]) | ||
| 352 | // A trailing character that cannot end an address belongs to the sentence, not the link. | 380 | // A trailing character that cannot end an address belongs to the sentence, not the link. |
| 353 | guard !address.hasSuffix("."), !address.hasSuffix("-") else { return nil } | 381 | guard !address.hasSuffix("."), !address.hasSuffix("-") else { return nil } |
| 354 | return (.link(OrgLink(target: .external("mailto:\(address)"), | 382 | return (.link(OrgLink(target: .external("mailto:\(address)"), |
| @@ -406,10 +434,20 @@ extension OrgParser { | |||
| 406 | return (.math(OrgMath(tex: source, display: true, source: source)), close + closer.count) | 434 | return (.math(OrgMath(tex: source, display: true, source: source)), close + closer.count) |
| 407 | } | 435 | } |
| 408 | 436 | ||
| 409 | /// Where the run's last `\end{name}` starts, in characters, and its name. | 437 | /// Where the run's last `\end{name}` (`\\end\{(\w+)\}`) starts, in characters, and its name. |
| 410 | private static func lastEnvironmentEnd(_ text: String) -> (offset: Int, name: String)? { | 438 | private static func lastEnvironmentEnd(_ chars: [Character]) -> (offset: Int, name: String)? { |
| 411 | guard text.contains(#"\end{"#), let last = text.matches(of: environmentEndPattern).last else { return nil } | 439 | let opener = Array(#"\end{"#) |
| 412 | return (text.distance(from: text.startIndex, to: last.range.lowerBound), String(last.1)) | 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 | ||
| 413 | } | 451 | } |
| 414 | 452 | ||
| 415 | private static func firstIndex(of needle: [Character], in chars: [Character], from start: Int) -> Int? { | 453 | 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 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Parses org source into an ``OrgDocument``. | 1 | /// Parses org source into an ``OrgDocument``. |
| 4 | /// | 2 | /// |
| 5 | /// This is the prototype of the AST split: parsing happens once, here, and renderers walk the | 3 | /// This is the prototype of the AST split: parsing happens once, here, and renderers walk the |
| @@ -8,10 +6,7 @@ import Foundation | |||
| 8 | public enum OrgParser { | 6 | public enum OrgParser { |
| 9 | 7 | ||
| 10 | public static func parse(_ source: String) -> OrgDocument { | 8 | public static func parse(_ source: String) -> OrgDocument { |
| 11 | let lines = source | 9 | let lines = splitLines(source) |
| 12 | .replacingOccurrences(of: "\r\n", with: "\n") | ||
| 13 | .replacingOccurrences(of: "\r", with: "\n") | ||
| 14 | .components(separatedBy: "\n") | ||
| 15 | var state = State(lines: lines) | 10 | var state = State(lines: lines) |
| 16 | while state.index < lines.count { | 11 | while state.index < lines.count { |
| 17 | state.step() | 12 | state.step() |
| @@ -57,7 +52,7 @@ public enum OrgParser { | |||
| 57 | 52 | ||
| 58 | mutating func step() { | 53 | mutating func step() { |
| 59 | let line = lines[index] | 54 | let line = lines[index] |
| 60 | let trimmed = line.trimmingCharacters(in: .whitespaces) | 55 | let trimmed = line.trimmingWhitespace() |
| 61 | 56 | ||
| 62 | if trimmed.isEmpty { index += 1; return } | 57 | if trimmed.isEmpty { index += 1; return } |
| 63 | 58 | ||
| @@ -89,7 +84,7 @@ public enum OrgParser { | |||
| 89 | mutating func skipPropertyDrawer() { | 84 | mutating func skipPropertyDrawer() { |
| 90 | index += 1 | 85 | index += 1 |
| 91 | while index < lines.count, | 86 | while index < lines.count, |
| 92 | lines[index].trimmingCharacters(in: .whitespaces) != ":END:" { | 87 | lines[index].trimmingWhitespace() != ":END:" { |
| 93 | index += 1 | 88 | index += 1 |
| 94 | } | 89 | } |
| 95 | if index < lines.count { index += 1 } | 90 | if index < lines.count { index += 1 } |
| @@ -158,7 +153,7 @@ public enum OrgParser { | |||
| 158 | var paragraph: [String] = [] | 153 | var paragraph: [String] = [] |
| 159 | while index < lines.count { | 154 | while index < lines.count { |
| 160 | let candidate = lines[index] | 155 | let candidate = lines[index] |
| 161 | let candidateTrimmed = candidate.trimmingCharacters(in: .whitespaces) | 156 | let candidateTrimmed = candidate.trimmingWhitespace() |
| 162 | // The first line is always taken: nothing above claimed it, and | 157 | // The first line is always taken: nothing above claimed it, and |
| 163 | // leaving it would parse the same line forever. | 158 | // leaving it would parse the same line forever. |
| 164 | if !paragraph.isEmpty, | 159 | if !paragraph.isEmpty, |
| @@ -198,20 +193,28 @@ public enum OrgParser { | |||
| 198 | 193 | ||
| 199 | // MARK: - LaTeX block | 194 | // MARK: - LaTeX block |
| 200 | 195 | ||
| 201 | private static let latexBeginLine = /^\\begin\{([^}]+)\}$/.ignoresCase() | ||
| 202 | private static let latexEndLine = /^\\end\{([^}]+)\}$/.ignoresCase() | ||
| 203 | |||
| 204 | /// The environment a `\begin{name}` line opens, as go-org's lexer reads it (any case). | 196 | /// The environment a `\begin{name}` line opens, as go-org's lexer reads it (any case). |
| 205 | private static func latexBegin(_ trimmed: String) -> String? { | 197 | private static func latexBegin(_ trimmed: String) -> String? { |
| 206 | guard trimmed.hasPrefix("\\") else { return nil } | 198 | latexEnvironmentLine(trimmed, command: "begin") |
| 207 | return trimmed.firstMatch(of: latexBeginLine).map { String($0.1).lowercased() } | ||
| 208 | } | 199 | } |
| 209 | 200 | ||
| 210 | /// The environment a `\end{name}` line closes. Like go-org's, it ends a paragraph | 201 | /// The environment a `\end{name}` line closes. Like go-org's, it ends a paragraph |
| 211 | /// whether or not a block is open. | 202 | /// whether or not a block is open. |
| 212 | private static func latexEnd(_ trimmed: String) -> String? { | 203 | 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? { | ||
| 213 | guard trimmed.hasPrefix("\\") else { return nil } | 209 | 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() | ||
| 215 | } | 218 | } |
| 216 | 219 | ||
| 217 | /// Each environment's `\end{name}` lines, in order, found in one pass so an opener | 220 | /// Each environment's `\end{name}` lines, in order, found in one pass so an opener |
| @@ -219,14 +222,14 @@ public enum OrgParser { | |||
| 219 | private static func latexEndLines(_ lines: [String]) -> [String: [Int]] { | 222 | private static func latexEndLines(_ lines: [String]) -> [String: [Int]] { |
| 220 | var ends: [String: [Int]] = [:] | 223 | var ends: [String: [Int]] = [:] |
| 221 | for (index, line) in lines.enumerated() { | 224 | 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) } |
| 223 | } | 226 | } |
| 224 | return ends | 227 | return ends |
| 225 | } | 228 | } |
| 226 | 229 | ||
| 227 | /// The line closing the block a `\begin{name}` line at `start` opens, if one follows. | 230 | /// The line closing the block a `\begin{name}` line at `start` opens, if one follows. |
| 228 | private static func latexBlockEnd(_ lines: [String], from start: Int, ends: [String: [Int]]) -> Int? { | 231 | 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()), |
| 230 | let candidates = ends[name] else { return nil } | 233 | let candidates = ends[name] else { return nil } |
| 231 | var low = 0, high = candidates.count | 234 | var low = 0, high = candidates.count |
| 232 | while low < high { | 235 | while low < high { |
| @@ -254,7 +257,7 @@ public enum OrgParser { | |||
| 254 | 257 | ||
| 255 | for keyword in ["TODO", "DONE"] where body == keyword || body.hasPrefix("\(keyword) ") { | 258 | for keyword in ["TODO", "DONE"] where body == keyword || body.hasPrefix("\(keyword) ") { |
| 256 | todo = keyword | 259 | todo = keyword |
| 257 | body = String(body.dropFirst(keyword.count)).trimmingCharacters(in: .whitespaces) | 260 | body = String(body.dropFirst(keyword.count)).trimmingWhitespace() |
| 258 | break | 261 | break |
| 259 | } | 262 | } |
| 260 | // `^\[#([A-Z])\]\s*` | 263 | // `^\[#([A-Z])\]\s*` |
| @@ -262,7 +265,7 @@ public enum OrgParser { | |||
| 262 | if cookie.count == 4, cookie[0] == "[", cookie[1] == "#", cookie[3] == "]", | 265 | if cookie.count == 4, cookie[0] == "[", cookie[1] == "#", cookie[3] == "]", |
| 263 | cookie[2].isASCII, cookie[2].isUppercase { | 266 | cookie[2].isASCII, cookie[2].isUppercase { |
| 264 | priority = cookie[2] | 267 | priority = cookie[2] |
| 265 | body = String(body.dropFirst(4).drop(while: \.isWhitespace)) | 268 | body = String(body.dropFirst(4).drop(while: { $0.isWhitespace })) |
| 266 | } | 269 | } |
| 267 | let (title, tags) = splitHeadingTags(body) | 270 | let (title, tags) = splitHeadingTags(body) |
| 268 | return OrgHeading(level: stars, todo: todo, priority: priority, | 271 | return OrgHeading(level: stars, todo: todo, priority: priority, |
| @@ -272,17 +275,17 @@ public enum OrgParser { | |||
| 272 | // MARK: - Blocks | 275 | // MARK: - Blocks |
| 273 | 276 | ||
| 274 | private static func parseBlock(_ lines: [String], from start: Int) -> (OrgElement?, Int) { | 277 | 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() |
| 276 | let lower = opener.lowercased() | 279 | let lower = opener.lowercased() |
| 277 | let name = String(lower.dropFirst("#+begin_".count)).split(separator: " ").first.map(String.init) ?? "" | 280 | let name = String(lower.dropFirst("#+begin_".count)).split(separator: " ").first.map(String.init) ?? "" |
| 278 | let argument = opener | 281 | let argument = opener |
| 279 | .split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true) | 282 | .split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true) |
| 280 | .dropFirst().first.map { String($0).trimmingCharacters(in: .whitespaces) } | 283 | .dropFirst().first.map { String($0).trimmingWhitespace() } |
| 281 | 284 | ||
| 282 | var body: [String] = [] | 285 | var body: [String] = [] |
| 283 | var index = start + 1 | 286 | var index = start + 1 |
| 284 | while index < lines.count { | 287 | while index < lines.count { |
| 285 | let trimmed = lines[index].trimmingCharacters(in: .whitespaces).lowercased() | 288 | let trimmed = lines[index].trimmingWhitespace().lowercased() |
| 286 | if trimmed == "#+end_\(name)" { index += 1; break } | 289 | if trimmed == "#+end_\(name)" { index += 1; break } |
| 287 | body.append(lines[index]) | 290 | body.append(lines[index]) |
| 288 | index += 1 | 291 | index += 1 |
| @@ -316,7 +319,7 @@ public enum OrgParser { | |||
| 316 | var index = start | 319 | var index = start |
| 317 | 320 | ||
| 318 | while index < lines.count { | 321 | while index < lines.count { |
| 319 | let trimmed = lines[index].trimmingCharacters(in: .whitespaces) | 322 | let trimmed = lines[index].trimmingWhitespace() |
| 320 | guard isTableLine(trimmed) else { break } | 323 | guard isTableLine(trimmed) else { break } |
| 321 | 324 | ||
| 322 | // A separator row's columns are divided by `+`, not `|`, so it needs its own | 325 | // A separator row's columns are divided by `+`, not `|`, so it needs its own |
| @@ -351,11 +354,11 @@ public enum OrgParser { | |||
| 351 | var pendingBlanks: [String] = [] | 354 | var pendingBlanks: [String] = [] |
| 352 | // A top-level marker of the other kind starts a *separate* list: an ordered list | 355 | // A top-level marker of the other kind starts a *separate* list: an ordered list |
| 353 | // followed by a bullet list is two lists, not one with mixed items. | 356 | // 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 |
| 355 | 358 | ||
| 356 | while index < lines.count { | 359 | while index < lines.count { |
| 357 | let line = lines[index] | 360 | let line = lines[index] |
| 358 | let trimmed = line.trimmingCharacters(in: .whitespaces) | 361 | let trimmed = line.trimmingWhitespace() |
| 359 | if trimmed.isEmpty { | 362 | if trimmed.isEmpty { |
| 360 | pendingBlanks.append(line); index += 1; continue | 363 | pendingBlanks.append(line); index += 1; continue |
| 361 | } | 364 | } |
| @@ -375,7 +378,7 @@ public enum OrgParser { | |||
| 375 | 378 | ||
| 376 | /// Group a list block's lines into items, recursing for nested lists. | 379 | /// Group a list block's lines into items, recursing for nested lists. |
| 377 | private static func buildList(_ lines: [String]) -> OrgList { | 380 | 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 } |
| 379 | .map(leadingWidth).min() ?? 0 | 382 | .map(leadingWidth).min() ?? 0 |
| 380 | let normalized = lines.map { dropLeading($0, base) } | 383 | let normalized = lines.map { dropLeading($0, base) } |
| 381 | 384 | ||
| @@ -393,7 +396,7 @@ public enum OrgParser { | |||
| 393 | 396 | ||
| 394 | let firstMarker = groups.first?.first ?? "" | 397 | let firstMarker = groups.first?.first ?? "" |
| 395 | var kind: OrgListKind = orderedListItem(in: firstMarker) != nil ? .ordered : .unordered | 398 | var kind: OrgListKind = orderedListItem(in: firstMarker) != nil ? .ordered : .unordered |
| 396 | if stripMarker(firstMarker).contains(" :: ") { kind = .description } | 399 | if stripMarker(firstMarker).containsText(" :: ") { kind = .description } |
| 397 | 400 | ||
| 398 | let items = groups.map { buildItem($0, kind: kind) } | 401 | let items = groups.map { buildItem($0, kind: kind) } |
| 399 | return OrgList(kind: kind, items: items) | 402 | return OrgList(kind: kind, items: items) |
| @@ -408,7 +411,7 @@ public enum OrgParser { | |||
| 408 | 411 | ||
| 409 | // `term :: definition` splits on the item's first line only, as org requires. | 412 | // `term :: definition` splits on the item's first line only, as org requires. |
| 410 | var term: [OrgObject]? | 413 | var term: [OrgObject]? |
| 411 | if kind == .description, let range = head.range(of: " :: ") { | 414 | if kind == .description, let range = head.firstRange(ofText: " :: ") { |
| 412 | term = parseInline(String(head[..<range.lowerBound])) | 415 | term = parseInline(String(head[..<range.lowerBound])) |
| 413 | head = String(head[range.upperBound...]) | 416 | head = String(head[range.upperBound...]) |
| 414 | } | 417 | } |
| @@ -417,7 +420,7 @@ public enum OrgParser { | |||
| 417 | // item holds whatever a document holds — several paragraphs, a nested list, a source | 420 | // item holds whatever a document holds — several paragraphs, a nested list, a source |
| 418 | // block, a table — in source order. | 421 | // block, a table — in source order. |
| 419 | let rest = Array(lines.dropFirst()) | 422 | let rest = Array(lines.dropFirst()) |
| 420 | let childIndent = rest.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty } | 423 | let childIndent = rest.filter { !$0.trimmingWhitespace().isEmpty } |
| 421 | .map(leadingWidth).min() ?? 0 | 424 | .map(leadingWidth).min() ?? 0 |
| 422 | let body = ([head] + rest.map { dropLeading($0, childIndent) }).joined(separator: "\n") | 425 | let body = ([head] + rest.map { dropLeading($0, childIndent) }).joined(separator: "\n") |
| 423 | 426 | ||
| @@ -426,30 +429,67 @@ public enum OrgParser { | |||
| 426 | 429 | ||
| 427 | // MARK: - Helpers | 430 | // MARK: - Helpers |
| 428 | 431 | ||
| 429 | private static let attributePattern = try? NSRegularExpression( | 432 | /// Each `:([A-Za-z_][A-Za-z0-9_-]*)\s+("[^"]*"|\S+)` in turn, scanned by scalar with ICU's |
| 430 | pattern: #":([A-Za-z_][A-Za-z0-9_-]*)\s+("[^"]*"|\S+)"# | 433 | /// `\s` (tab, LF, FF, CR and the separators), as `NSRegularExpression` matched it. |
| 431 | ) | ||
| 432 | |||
| 433 | private static func parseAttributes(_ value: String) -> [(key: String, value: String)] { | 434 | private static func parseAttributes(_ value: String) -> [(key: String, value: String)] { |
| 434 | guard let regex = attributePattern else { return [] } | 435 | let scalars = Array(value.unicodeScalars) |
| 435 | let ns = value as NSString | 436 | func isSpace(_ s: Unicode.Scalar) -> Bool { |
| 436 | return regex.matches(in: value, range: NSRange(location: 0, length: ns.length)).map { m in | 437 | switch s.value { |
| 437 | var raw = ns.substring(with: m.range(at: 2)) | 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) | ||
| 438 | if raw.count >= 2, raw.hasPrefix("\""), raw.hasSuffix("\"") { raw = String(raw.dropFirst().dropLast()) } | 476 | 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 | ||
| 440 | } | 479 | } |
| 480 | return attributes | ||
| 441 | } | 481 | } |
| 442 | 482 | ||
| 443 | private static func stripMarker(_ line: String) -> String { | 483 | private static func stripMarker(_ line: String) -> String { |
| 444 | let trimmed = line.trimmingCharacters(in: .whitespaces) | 484 | let trimmed = line.trimmingWhitespace() |
| 445 | if trimmed.hasPrefix("- ") || trimmed.hasPrefix("+ ") { return String(trimmed.dropFirst(2)) } | 485 | if trimmed.hasPrefix("- ") || trimmed.hasPrefix("+ ") { return String(trimmed.dropFirst(2)) } |
| 446 | // `^\d+[.)]\s+(.*)$` | 486 | // `^\d+[.)]\s+(.*)$` |
| 447 | let digits = trimmed.prefix(while: \.isNumber) | 487 | let digits = trimmed.prefix(while: { $0.isNumber }) |
| 448 | let afterDigits = trimmed[digits.endIndex...] | 488 | let afterDigits = trimmed[digits.endIndex...] |
| 449 | if !digits.isEmpty, afterDigits.first == "." || afterDigits.first == ")", | 489 | if !digits.isEmpty, afterDigits.first == "." || afterDigits.first == ")", |
| 450 | afterDigits.dropFirst().first?.isWhitespace == true { | 490 | afterDigits.dropFirst().first?.isWhitespace == true { |
| 451 | let text = afterDigits.dropFirst().drop(while: \.isWhitespace) | 491 | let text = afterDigits.dropFirst().drop(while: { $0.isWhitespace }) |
| 452 | if !text.contains(where: \.isNewline) { return String(text) } | 492 | if !text.contains(where: { $0.isNewline }) { return String(text) } |
| 453 | } | 493 | } |
| 454 | return trimmed | 494 | return trimmed |
| 455 | } | 495 | } |
Sources/OrgSwift/AST/OrgURLResolver.swift −2
| @@ -1,5 +1,3 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Resolves a link target or image source to a safe absolute URL string, or nil when it | 1 | /// Resolves a link target or image source to a safe absolute URL string, or nil when it |
| 4 | /// cannot be made safe. | 2 | /// cannot be made safe. |
| 5 | /// | 3 | /// |
Sources/OrgSwift/Escaping.swift +173 −21
| @@ -1,16 +1,36 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // MARK: - HTML Escaping | 1 | // MARK: - HTML Escaping |
| 4 | 2 | ||
| 5 | func escapeHTML(_ text: String) -> String { | 3 | func escapeHTML(_ text: String) -> String { |
| 6 | text.replacingOccurrences(of: "&", with: "&") | 4 | escaping(text, apostrophe: false) |
| 7 | .replacingOccurrences(of: "<", with: "<") | ||
| 8 | .replacingOccurrences(of: ">", with: ">") | ||
| 9 | .replacingOccurrences(of: "\"", with: """) | ||
| 10 | } | 5 | } |
| 11 | 6 | ||
| 12 | func escapeHTMLAttribute(_ text: String) -> String { | 7 | func escapeHTMLAttribute(_ text: String) -> String { |
| 13 | escapeHTML(text).replacingOccurrences(of: "'", with: "'") | 8 | escaping(text, apostrophe: true) |
| 9 | } | ||
| 10 | |||
| 11 | /// Replace `&`, `<`, `>`, `"` (and `'` when asked) by scalar, copying the runs between them. | ||
| 12 | private 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 = "&" | ||
| 20 | case UInt8(ascii: "<"): entity = "<" | ||
| 21 | case UInt8(ascii: ">"): entity = ">" | ||
| 22 | case UInt8(ascii: "\""): entity = """ | ||
| 23 | case UInt8(ascii: "'") where apostrophe: entity = "'" | ||
| 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 | ||
| 14 | } | 34 | } |
| 15 | 35 | ||
| 16 | // MARK: - URL Sanitization | 36 | // MARK: - URL Sanitization |
| @@ -39,19 +59,20 @@ private func sanitizeReadmeURLString( | |||
| 39 | allowedSchemes: Set<String>, | 59 | allowedSchemes: Set<String>, |
| 40 | allowsFragmentOnly: Bool | 60 | allowsFragmentOnly: Bool |
| 41 | ) -> String? { | 61 | ) -> String? { |
| 42 | let trimmedURL = rawURL.trimmingCharacters(in: .whitespacesAndNewlines) | 62 | let trimmedURL = rawURL.trimmingWhitespaceAndNewlines() |
| 43 | guard !trimmedURL.isEmpty else { return nil } | 63 | guard !trimmedURL.isEmpty else { return nil } |
| 44 | 64 | ||
| 45 | if allowsFragmentOnly, trimmedURL.hasPrefix("#"), trimmedURL.count > 1 { | 65 | if allowsFragmentOnly, trimmedURL.hasPrefix("#"), trimmedURL.count > 1 { |
| 46 | return trimmedURL | 66 | return trimmedURL |
| 47 | } | 67 | } |
| 48 | 68 | ||
| 49 | if let scheme = URLComponents(string: trimmedURL)?.scheme?.lowercased() { | 69 | let bytes = Array(trimmedURL.utf8) |
| 50 | guard allowedSchemes.contains(scheme), | 70 | if let schemeEnd = urlSchemeEnd(bytes) { |
| 51 | let sanitizedURL = URLComponents(string: trimmedURL)?.url?.absoluteString else { | 71 | let scheme = String(decoding: bytes[..<schemeEnd], as: UTF8.self) |
| 52 | return nil | 72 | guard allowedSchemes.contains(scheme.lowercased()) else { return nil } |
| 53 | } | 73 | // An allowed scheme with an authority that will not parse stays as written, as it did |
| 54 | return sanitizedURL | 74 | // when `URLComponents` refused it; the scheme alone is what makes it safe. |
| 75 | return normalizedURL(bytes, schemeEnd: schemeEnd) ?? trimmedURL | ||
| 55 | } | 76 | } |
| 56 | 77 | ||
| 57 | // No scheme → a relative reference (`diagram.png`, `docs/x`). It cannot carry a | 78 | // No scheme → a relative reference (`diagram.png`, `docs/x`). It cannot carry a |
| @@ -62,6 +83,137 @@ private func sanitizeReadmeURLString( | |||
| 62 | return trimmedURL | 83 | return trimmedURL |
| 63 | } | 84 | } |
| 64 | 85 | ||
| 86 | /// Where RFC 3986 `scheme` ends (at its `:`): a letter, then letters, digits, `+`, `-` or `.`. | ||
| 87 | private 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. | ||
| 100 | private 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. | ||
| 187 | private 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. | ||
| 203 | private func isPathCharacterByte(_ byte: UInt8) -> Bool { | ||
| 204 | isURLPathAllowedByte(byte) || byte == UInt8(ascii: ":") | ||
| 205 | } | ||
| 206 | |||
| 207 | /// A query or fragment's characters: a path's, and `?`. | ||
| 208 | private func isQueryByte(_ byte: UInt8) -> Bool { | ||
| 209 | isPathCharacterByte(byte) || byte == UInt8(ascii: "?") | ||
| 210 | } | ||
| 211 | |||
| 212 | /// `CharacterSet.urlUserAllowed` (and `urlPasswordAllowed`, the same set). | ||
| 213 | private func isUserByte(_ byte: UInt8) -> Bool { | ||
| 214 | isUnreservedByte(byte) || isSubDelimByte(byte) | ||
| 215 | } | ||
| 216 | |||
| 65 | // MARK: - Line Scanners | 217 | // MARK: - Line Scanners |
| 66 | 218 | ||
| 67 | // These run on every line, so they scan by hand rather than through a regex. Each doc comment | 219 | // 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)? { | |||
| 77 | let keyword = rest.prefix(while: { isASCIIWordCharacter($0) || $0 == "-" }) | 229 | let keyword = rest.prefix(while: { isASCIIWordCharacter($0) || $0 == "-" }) |
| 78 | let afterKeyword = rest[keyword.endIndex...] | 230 | let afterKeyword = rest[keyword.endIndex...] |
| 79 | guard afterKeyword.first == ":" else { return nil } | 231 | guard afterKeyword.first == ":" else { return nil } |
| 80 | let value = afterKeyword.dropFirst().drop(while: \.isWhitespace) | 232 | let value = afterKeyword.dropFirst().drop(while: { $0.isWhitespace }) |
| 81 | guard !value.contains(where: \.isNewline) else { return nil } | 233 | guard !value.contains(where: { $0.isNewline }) else { return nil } |
| 82 | return ( | 234 | return ( |
| 83 | keyword: keyword.lowercased(), | 235 | keyword: keyword.lowercased(), |
| 84 | value: String(value).trimmingCharacters(in: .whitespaces) | 236 | value: String(value).trimmingWhitespace() |
| 85 | ) | 237 | ) |
| 86 | } | 238 | } |
| 87 | 239 | ||
| 88 | /// `^\s*-{5,}\s*$` | 240 | /// `^\s*-{5,}\s*$` |
| 89 | func isOrgHorizontalRule(_ line: String) -> Bool { | 241 | func isOrgHorizontalRule(_ line: String) -> Bool { |
| 90 | let dashes = line.drop(while: \.isWhitespace).prefix(while: { $0 == "-" }) | 242 | let dashes = line.drop(while: { $0.isWhitespace }).prefix(while: { $0 == "-" }) |
| 91 | return dashes.count >= 5 && line[dashes.endIndex...].allSatisfy(\.isWhitespace) | 243 | return dashes.count >= 5 && line[dashes.endIndex...].allSatisfy({ $0.isWhitespace }) |
| 92 | } | 244 | } |
| 93 | 245 | ||
| 94 | /// What `\s+(.+)$` captures at the start of `text`: the rest of the line after at least one | 246 | /// 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 { | |||
| 96 | /// regex does when it backtracks. | 248 | /// regex does when it backtracks. |
| 97 | func textAfterWhitespace(_ text: Substring) -> Substring? { | 249 | func textAfterWhitespace(_ text: Substring) -> Substring? { |
| 98 | guard let first = text.first, first.isWhitespace else { return nil } | 250 | 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 }) |
| 100 | if rest.isEmpty { | 252 | if rest.isEmpty { |
| 101 | guard text.count >= 2, let last = text.last, !last.isNewline else { return nil } | 253 | guard text.count >= 2, let last = text.last, !last.isNewline else { return nil } |
| 102 | return text.suffix(1) | 254 | return text.suffix(1) |
| 103 | } | 255 | } |
| 104 | return rest.contains(where: \.isNewline) ? nil : rest | 256 | return rest.contains(where: { $0.isNewline }) ? nil : rest |
| 105 | } | 257 | } |
| 106 | 258 | ||
| 107 | func isASCIILetter(_ c: Character) -> Bool { | 259 | func isASCIILetter(_ c: Character) -> Bool { |
Sources/OrgSwift/Footnotes.swift −2
| @@ -1,5 +1,3 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Detect a reference-style footnote definition line: `[fn:label] text…`. Returns the | 1 | /// 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. | 2 | /// label and the definition text, or nil if the line is not one. |
| 5 | /// | 3 | /// |
Sources/OrgSwift/Links.swift +12 −20
| @@ -1,5 +1,3 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Strip org's `file:` link prefix. `[[file:diagram.png]]` targets a local path the same | 1 | /// Strip org's `file:` link prefix. `[[file:diagram.png]]` targets a local path the same |
| 4 | /// way `[[diagram.png]]` does; the scheme is org bookkeeping, not part of the URL. | 2 | /// way `[[diagram.png]]` does; the scheme is org bookkeeping, not part of the URL. |
| 5 | func normalizeOrgLinkTarget(_ target: String) -> String { | 3 | func normalizeOrgLinkTarget(_ target: String) -> String { |
| @@ -16,10 +14,10 @@ private func isRenderableImageSource(_ source: String) -> Bool { | |||
| 16 | /// If a whole line is just an image link with no description (`[[file:x.png]]`), return its | 14 | /// If a whole line is just an image link with no description (`[[file:x.png]]`), return its |
| 17 | /// path (with `file:` stripped). A link carrying a description is not a standalone image. | 15 | /// path (with `file:` stripped). A link carrying a description is not a standalone image. |
| 18 | func standaloneOrgImage(in line: String) -> String? { | 16 | func standaloneOrgImage(in line: String) -> String? { |
| 19 | let trimmed = line.trimmingCharacters(in: .whitespaces) | 17 | let trimmed = line.trimmingWhitespace() |
| 20 | guard trimmed.hasPrefix("[[") && trimmed.hasSuffix("]]") else { return nil } | 18 | guard trimmed.hasPrefix("[[") && trimmed.hasSuffix("]]") else { return nil } |
| 21 | let inner = String(trimmed.dropFirst(2).dropLast(2)) | 19 | let inner = String(trimmed.dropFirst(2).dropLast(2)) |
| 22 | guard !inner.contains("][") else { return nil } | 20 | guard !inner.containsText("][") else { return nil } |
| 23 | let path = normalizeOrgLinkTarget(inner) | 21 | let path = normalizeOrgLinkTarget(inner) |
| 24 | guard isRenderableImageSource(path) else { return nil } | 22 | guard isRenderableImageSource(path) else { return nil } |
| 25 | return path | 23 | return path |
| @@ -35,7 +33,7 @@ func resolveRepositoryLinkURL( | |||
| 35 | readmePath: String?, | 33 | readmePath: String?, |
| 36 | pathSegment: String = "blob" | 34 | pathSegment: String = "blob" |
| 37 | ) -> String? { | 35 | ) -> String? { |
| 38 | let trimmedSource = source.trimmingCharacters(in: .whitespacesAndNewlines) | 36 | let trimmedSource = source.trimmingWhitespaceAndNewlines() |
| 39 | guard !trimmedSource.isEmpty else { return nil } | 37 | guard !trimmedSource.isEmpty else { return nil } |
| 40 | 38 | ||
| 41 | if trimmedSource.hasPrefix("http://") || trimmedSource.hasPrefix("https://") | 39 | if trimmedSource.hasPrefix("http://") || trimmedSource.hasPrefix("https://") |
| @@ -63,7 +61,7 @@ func resolveRepositoryAssetURL( | |||
| 63 | readmePath: String?, | 61 | readmePath: String?, |
| 64 | pathSegment: String = "blob" | 62 | pathSegment: String = "blob" |
| 65 | ) -> String? { | 63 | ) -> String? { |
| 66 | let trimmedSource = source.trimmingCharacters(in: .whitespacesAndNewlines) | 64 | let trimmedSource = source.trimmingWhitespaceAndNewlines() |
| 67 | guard !trimmedSource.isEmpty else { return nil } | 65 | guard !trimmedSource.isEmpty else { return nil } |
| 68 | 66 | ||
| 69 | if trimmedSource.hasPrefix("http://") || trimmedSource.hasPrefix("https://") || trimmedSource.hasPrefix("data:") { | 67 | if trimmedSource.hasPrefix("http://") || trimmedSource.hasPrefix("https://") || trimmedSource.hasPrefix("data:") { |
| @@ -74,28 +72,22 @@ func resolveRepositoryAssetURL( | |||
| 74 | if trimmedSource.hasPrefix("/") { | 72 | if trimmedSource.hasPrefix("/") { |
| 75 | relativePath = String(trimmedSource.dropFirst()) | 73 | relativePath = String(trimmedSource.dropFirst()) |
| 76 | } else { | 74 | } else { |
| 77 | let readmeDirectory = (readmePath as NSString?)?.deletingLastPathComponent ?? "" | 75 | let readmeDirectory = (readmePath ?? "").split(separator: "/").dropLast() |
| 78 | relativePath = normalizeRepositoryPath( | 76 | relativePath = normalizeRepositoryPath( |
| 79 | (readmeDirectory as NSString).appendingPathComponent(trimmedSource) | 77 | (readmeDirectory + [trimmedSource[...]]).joined(separator: "/") |
| 80 | ) | 78 | ) |
| 81 | } | 79 | } |
| 82 | 80 | ||
| 83 | guard !relativePath.isEmpty else { return nil } | 81 | guard !relativePath.isEmpty else { return nil } |
| 84 | var components = URLComponents() | 82 | let encodedOwner = percentEncoded(owner, allowing: isURLPathAllowedByte) |
| 85 | components.scheme = "https" | 83 | let encodedRepository = percentEncoded(repositoryName, allowing: isURLPathAllowedByte) |
| 86 | components.host = host | 84 | let encodedRef = percentEncoded(ref, allowing: isURLPathAllowedByte) |
| 87 | let encodedOwner = owner.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? owner | ||
| 88 | let encodedRepository = repositoryName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? repositoryName | ||
| 89 | let encodedRef = ref.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ref | ||
| 90 | let encodedRelativePath = relativePath | 85 | let encodedRelativePath = relativePath |
| 91 | .split(separator: "/", omittingEmptySubsequences: false) | 86 | .split(separator: "/", omittingEmptySubsequences: false) |
| 92 | .map { segment in | 87 | .map { percentEncoded($0, allowing: isURLPathAllowedByte) } |
| 93 | String(segment).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? String(segment) | ||
| 94 | } | ||
| 95 | .joined(separator: "/") | 88 | .joined(separator: "/") |
| 96 | let encodedSegment = pathSegment.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? pathSegment | 89 | let encodedSegment = percentEncoded(pathSegment, allowing: isURLPathAllowedByte) |
| 97 | components.percentEncodedPath = "/\(encodedOwner)/\(encodedRepository)/\(encodedSegment)/\(encodedRef)/\(encodedRelativePath)" | 90 | return "https://\(host)/\(encodedOwner)/\(encodedRepository)/\(encodedSegment)/\(encodedRef)/\(encodedRelativePath)" |
| 98 | return components.string | ||
| 99 | } | 91 | } |
| 100 | 92 | ||
| 101 | private func normalizeRepositoryPath(_ path: String) -> String { | 93 | private func normalizeRepositoryPath(_ path: String) -> String { |
Sources/OrgSwift/Lists.swift +2 −4
| @@ -1,8 +1,6 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// `^(\d+)\.\s+(.+)$` | 1 | /// `^(\d+)\.\s+(.+)$` |
| 4 | func orderedListItem(in line: String) -> String? { | 2 | func orderedListItem(in line: String) -> String? { |
| 5 | let digits = line.prefix(while: \.isNumber) | 3 | let digits = line.prefix(while: { $0.isNumber }) |
| 6 | let afterDigits = line[digits.endIndex...] | 4 | let afterDigits = line[digits.endIndex...] |
| 7 | guard !digits.isEmpty, afterDigits.first == ".", | 5 | guard !digits.isEmpty, afterDigits.first == ".", |
| 8 | let text = textAfterWhitespace(afterDigits.dropFirst()) else { return nil } | 6 | let text = textAfterWhitespace(afterDigits.dropFirst()) else { return nil } |
| @@ -15,7 +13,7 @@ func isListMarkerLine(_ line: String) -> Bool { | |||
| 15 | } | 13 | } |
| 16 | 14 | ||
| 17 | func isIndentedContinuationLine(_ line: String) -> Bool { | 15 | func isIndentedContinuationLine(_ line: String) -> Bool { |
| 18 | guard !line.trimmingCharacters(in: .whitespaces).isEmpty else { return false } | 16 | guard !line.trimmingWhitespace().isEmpty else { return false } |
| 19 | guard let first = line.first else { return false } | 17 | guard let first = line.first else { return false } |
| 20 | return first == " " || first == "\t" | 18 | return first == " " || first == "\t" |
| 21 | }\ No newline at end of file | 19 | }\ No newline at end of file |
Sources/OrgSwift/OrgRenderer.swift +4 −6
| @@ -1,5 +1,3 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Produces highlighted HTML for a fenced code block. Returning `nil` makes the | 1 | /// Produces highlighted HTML for a fenced code block. Returning `nil` makes the |
| 4 | /// renderer fall back to an escaped `<pre><code>` block. | 2 | /// renderer fall back to an escaped `<pre><code>` block. |
| 5 | public protocol CodeHighlighter { | 3 | public protocol CodeHighlighter { |
| @@ -133,9 +131,9 @@ public enum OrgRenderer { | |||
| 133 | /// `^(.*?)\s+(:(?:[A-Za-z0-9_@#%]+:)+)$`: tags hold no whitespace, so they are the last | 131 | /// `^(.*?)\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. | 132 | /// whitespace-separated word, and the lazy title stops where the whitespace before it starts. |
| 135 | func splitHeadingTags(_ heading: String) -> (title: String, tags: [String]) { | 133 | func 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, []) } |
| 137 | let tagText = heading[heading.index(after: space)...] | 135 | 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("::"), |
| 139 | tagText.allSatisfy({ $0 == ":" || isASCIIWordCharacter($0) || "@#%".contains($0) }) else { | 137 | tagText.allSatisfy({ $0 == ":" || isASCIIWordCharacter($0) || "@#%".contains($0) }) else { |
| 140 | return (heading, []) | 138 | return (heading, []) |
| 141 | } | 139 | } |
| @@ -144,7 +142,7 @@ func splitHeadingTags(_ heading: String) -> (title: String, tags: [String]) { | |||
| 144 | titleEnd = heading.index(before: titleEnd) | 142 | titleEnd = heading.index(before: titleEnd) |
| 145 | } | 143 | } |
| 146 | let title = heading[..<titleEnd] | 144 | let title = heading[..<titleEnd] |
| 147 | guard !title.contains(where: \.isNewline) else { return (heading, []) } | 145 | guard !title.contains(where: { $0.isNewline }) else { return (heading, []) } |
| 148 | let tags = tagText.split(separator: ":").map(String.init) | 146 | let tags = tagText.split(separator: ":").map(String.init) |
| 149 | return (String(title).trimmingCharacters(in: .whitespaces), tags) | 147 | return (String(title).trimmingWhitespace(), tags) |
| 150 | } | 148 | } |
Sources/OrgSwift/Skeleton.swift +3 −5
| @@ -11,8 +11,6 @@ | |||
| 11 | // package's conformance test self-checks that first, by feeding each corpus `.html` | 11 | // package's conformance test self-checks that first, by feeding each corpus `.html` |
| 12 | // through this port and requiring it to reproduce the checked-in `.skeleton`. | 12 | // through this port and requiring it to reproduce the checked-in `.skeleton`. |
| 13 | 13 | ||
| 14 | import Foundation | ||
| 15 | |||
| 16 | public enum OrgSkeleton { | 14 | public enum OrgSkeleton { |
| 17 | /// Elements dropped entirely: `div` is layout, `span` is per-token highlighter noise. | 15 | /// Elements dropped entirely: `div` is layout, `span` is per-token highlighter noise. |
| 18 | private static let ignored: Set<String> = ["div", "span"] | 16 | private static let ignored: Set<String> = ["div", "span"] |
| @@ -53,12 +51,12 @@ public enum OrgSkeleton { | |||
| 53 | i = end + 1 | 51 | i = end + 1 |
| 54 | 52 | ||
| 55 | // trim → strip trailing '/' → trim | 53 | // trim → strip trailing '/' → trim |
| 56 | var raw = rawFull.trimmingCharacters(in: .whitespaces) | 54 | var raw = rawFull.trimmingWhitespace() |
| 57 | if raw.hasSuffix("/") { raw.removeLast() } | 55 | if raw.hasSuffix("/") { raw.removeLast() } |
| 58 | raw = raw.trimmingCharacters(in: .whitespaces) | 56 | raw = raw.trimmingWhitespace() |
| 59 | 57 | ||
| 60 | if raw.hasPrefix("/") { | 58 | if raw.hasPrefix("/") { |
| 61 | let name = raw.dropFirst().trimmingCharacters(in: .whitespaces).lowercased() | 59 | let name = raw.dropFirst().trimmingWhitespace().lowercased() |
| 62 | if !ignored.contains(name) && !void.contains(name) { | 60 | if !ignored.contains(name) && !void.contains(name) { |
| 63 | flushText(&text, &out) | 61 | flushText(&text, &out) |
| 64 | out.append("</\(name)>") | 62 | out.append("</\(name)>") |
Sources/OrgSwift/Tables.swift +5 −7
| @@ -1,5 +1,3 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | func isTableLine(_ line: String) -> Bool { | 1 | func isTableLine(_ line: String) -> Bool { |
| 4 | line.hasPrefix("|") && line.hasSuffix("|") | 2 | line.hasPrefix("|") && line.hasSuffix("|") |
| 5 | } | 3 | } |
| @@ -9,11 +7,11 @@ func parseTableRow(_ line: String) -> [String] { | |||
| 9 | .split(separator: "|", omittingEmptySubsequences: false) | 7 | .split(separator: "|", omittingEmptySubsequences: false) |
| 10 | .dropFirst() | 8 | .dropFirst() |
| 11 | .dropLast() | 9 | .dropLast() |
| 12 | .map { String($0).trimmingCharacters(in: .whitespaces) } | 10 | .map { String($0).trimmingWhitespace() } |
| 13 | } | 11 | } |
| 14 | 12 | ||
| 15 | func parseOrgTableSeparatorRow(_ line: String) -> [String] { | 13 | func parseOrgTableSeparatorRow(_ line: String) -> [String] { |
| 16 | var content = line.trimmingCharacters(in: .whitespaces) | 14 | var content = line.trimmingWhitespace() |
| 17 | if content.hasPrefix("|") { | 15 | if content.hasPrefix("|") { |
| 18 | content.removeFirst() | 16 | content.removeFirst() |
| 19 | } | 17 | } |
| @@ -22,7 +20,7 @@ func parseOrgTableSeparatorRow(_ line: String) -> [String] { | |||
| 22 | } | 20 | } |
| 23 | return content | 21 | return content |
| 24 | .split(separator: "+", omittingEmptySubsequences: false) | 22 | .split(separator: "+", omittingEmptySubsequences: false) |
| 25 | .map { String($0).trimmingCharacters(in: .whitespaces) } | 23 | .map { String($0).trimmingWhitespace() } |
| 26 | } | 24 | } |
| 27 | 25 | ||
| 28 | func isTableSeparatorCell(_ cell: String) -> Bool { | 26 | func isTableSeparatorCell(_ cell: String) -> Bool { |
| @@ -30,10 +28,10 @@ func isTableSeparatorCell(_ cell: String) -> Bool { | |||
| 30 | } | 28 | } |
| 31 | 29 | ||
| 32 | func tableAlignment(for cell: String) -> String? { | 30 | func tableAlignment(for cell: String) -> String? { |
| 33 | let trimmed = cell.trimmingCharacters(in: .whitespaces) | 31 | let trimmed = cell.trimmingWhitespace() |
| 34 | guard !trimmed.isEmpty else { return nil } | 32 | guard !trimmed.isEmpty else { return nil } |
| 35 | 33 | ||
| 36 | let core = trimmed.replacingOccurrences(of: ":", with: "") | 34 | let core = trimmed.filter { $0 != ":" } |
| 37 | guard !core.isEmpty, core.allSatisfy({ $0 == "-" || $0 == "+" }) else { | 35 | guard !core.isEmpty, core.allSatisfy({ $0 == "-" || $0 == "+" }) else { |
| 38 | return nil | 36 | return nil |
| 39 | } | 37 | } |
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 | |||
| 6 | extension 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 | |||
| 18 | extension 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. | ||
| 26 | private 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. | ||
| 34 | func 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`. | ||
| 42 | func 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 | |||
| 51 | extension 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. | ||
| 77 | func 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`. | ||
| 103 | func percentEncoded<S: StringProtocol>(_ text: S, allowing allowed: (UInt8) -> Bool) -> String { | ||
| 104 | String(decoding: percentEncodedBytes(text.utf8, allowing: allowed), as: UTF8.self) | ||
| 105 | } | ||
| 106 | |||
| 107 | func 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 | |||
| 123 | func isASCIILetterByte(_ byte: UInt8) -> Bool { | ||
| 124 | (UInt8(ascii: "A")...UInt8(ascii: "Z")).contains(byte) || (UInt8(ascii: "a")...UInt8(ascii: "z")).contains(byte) | ||
| 125 | } | ||
| 126 | |||
| 127 | func isASCIIDigitByte(_ byte: UInt8) -> Bool { | ||
| 128 | (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(byte) | ||
| 129 | } | ||
| 130 | |||
| 131 | func 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`. | ||
| 140 | func 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`. | ||
| 150 | func 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 `:`. | ||
| 160 | func 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 { | |||
| 566 | // Without one there is nothing to resolve against, and the scheme allowlist rejects it. | 566 | // Without one there is nothing to resolve against, and the scheme allowlist rejects it. |
| 567 | #expect(OrgRenderOptions().resolvedLinkURL("javascript:alert(1)") == nil) | 567 | #expect(OrgRenderOptions().resolvedLinkURL("javascript:alert(1)") == nil) |
| 568 | #expect(OrgRenderOptions().resolvedImageURL("javascript:alert(1)") == nil) | 568 | #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"\u{301} onmouseover" | ||
| 580 | #expect(!html.contains(quote)) | ||
| 581 | #expect(html.contains(escaped)) | ||
| 569 | } | 582 | } |
| 570 | 583 | ||
| 571 | /// A resolved URL is a URL, not an HTML attribute: `&` survives for a `URL(string:)` | 584 | /// A resolved URL is a URL, not an HTML attribute: `&` survives for a `URL(string:)` |