Commit ef5b86d8d3

ef5b86d8d321fc6e804fa037cb2346e6f80d6e09

parent: d8d6302e6f

Verified · cmc

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

Parse and build agenda sources several times faster

- List items: counter and description-tag scans by hand instead of
  Swift Regex, checked against the old patterns.
- Whole-file "#+setupfile:" and similar checks by bytes instead of a
  case-insensitive range(of:).
- upHeadingSafe stops at top-level headings instead of walking to the
  top of the file.
- Agenda regular expressions compiled once.

Layout: unified · split

Sources/OrgCore/ASCIISearch.swift added +33
@@ -0,0 +1,33 @@
1import Foundation
2
3extension StringProtocol {
4 /// Whether the text contains `needle` ignoring ASCII case, by bytes: much faster than a
5 /// case-insensitive `range(of:)` over a whole file. `needle` is ASCII.
6 public func containsIgnoringASCIICase(_ needle: String) -> Bool {
7 let target = Array(needle.lowercased().utf8)
8 guard let first = target.first else { return true }
9 let firstUpper = first >= 97 && first <= 122 ? first - 32 : first
10 func search(_ bytes: UnsafeBufferPointer<UInt8>) -> Bool {
11 guard bytes.count >= target.count else { return false }
12 var i = 0
13 let last = bytes.count - target.count
14 while i <= last {
15 let b = bytes[i]
16 if b == first || b == firstUpper {
17 var k = 1
18 while k < target.count {
19 var c = bytes[i + k]
20 if c >= 65 && c <= 90 { c += 32 }
21 if c != target[k] { break }
22 k += 1
23 }
24 if k == target.count { return true }
25 }
26 i += 1
27 }
28 return false
29 }
30 if let found = utf8.withContiguousStorageIfAvailable(search) { return found }
31 return Array(utf8).withUnsafeBufferPointer(search)
32 }
33}
Sources/OrgCore/Agenda/AgendaFilter.swift +3 −1
@@ -4,6 +4,8 @@ import Foundation
4/// each a list of `+x` (keep) and `-x` (drop) terms. Lines without an entry (the time grid) 4/// each a list of `+x` (keep) and `-x` (drop) terms. Lines without an entry (the time grid)
5/// always show. 5/// always show.
6public struct AgendaFilter: Sendable, Equatable { 6public struct AgendaFilter: Sendable, Equatable {
7 static let wordRegex = try! NSRegularExpression(pattern: "^[ \\t]*([-+])?(([^-+<>=/ \\t]+)|([<>=][0-9:]+)|(/([^/]+)/?))")
8
7 public var categories: [String] = [] 9 public var categories: [String] = []
8 public var tags: [String] = [] 10 public var tags: [String] = []
9 public var efforts: [String] = [] 11 public var efforts: [String] = []
@@ -42,7 +44,7 @@ public struct AgendaFilter: Sendable, Equatable {
42 s = s.replacingOccurrences(of: "\"([^\"]*)-([^\"]*)\"", with: "\"$1~~~$2\"", options: .regularExpression) 44 s = s.replacingOccurrences(of: "\"([^\"]*)-([^\"]*)\"", with: "\"$1~~~$2\"", options: .regularExpression)
43 var result = keep ? self : AgendaFilter() 45 var result = keep ? self : AgendaFilter()
44 var ignored: [String] = [] 46 var ignored: [String] = []
45 let regex = try! NSRegularExpression(pattern: "^[ \\t]*([-+])?(([^-+<>=/ \\t]+)|([<>=][0-9:]+)|(/([^/]+)/?))") 47 let regex = Self.wordRegex
46 func append(_ term: String, to list: inout [String]) { if !list.contains(term) { list.append(term) } } 48 func append(_ term: String, to list: inout [String]) { if !list.contains(term) { list.append(term) } }
47 while true { 49 while true {
48 let ns = s as NSString 50 let ns = s as NSString
Sources/OrgCore/Agenda/AgendaSearch.swift +3 −1
@@ -233,6 +233,8 @@ extension Agenda {
233 233
234/// `org-make-tags-matcher`: `+work-boss|LEVEL>2+TODO="WAIT"/!NEXT`. 234/// `org-make-tags-matcher`: `+work-boss|LEVEL>2+TODO="WAIT"/!NEXT`.
235public struct TagsMatcher: Sendable { 235public struct TagsMatcher: Sendable {
236 static let slashesRegex = try! NSRegularExpression(pattern: "/+")
237
236 indirect enum Term: Sendable { 238 indirect enum Term: Sendable {
237 case tag(String) 239 case tag(String)
238 case tagRegex(String) 240 case tagRegex(String)
@@ -262,7 +264,7 @@ public struct TagsMatcher: Sendable {
262 var tagsPart = match 264 var tagsPart = match
263 var todoPart: String? 265 var todoPart: String?
264 let ns = match as NSString 266 let ns = match as NSString
265 let slashes = try! NSRegularExpression(pattern: "/+") 267 let slashes = Self.slashesRegex
266 if let last = slashes.matches(in: match, range: NSRange(location: 0, length: ns.length)).last, 268 if let last = slashes.matches(in: match, range: NSRange(location: 0, length: ns.length)).last,
267 !ns.substring(from: last.range.location).contains("\"") { 269 !ns.substring(from: last.range.location).contains("\"") {
268 tagsPart = ns.substring(to: last.range.location) 270 tagsPart = ns.substring(to: last.range.location)
Sources/OrgCore/Agenda/AgendaSource.swift +12 −6
@@ -3,6 +3,12 @@ import Foundation
3/// What the agenda needs from one file, read once from its text: headings with their planning, 3/// What the agenda needs from one file, read once from its text: headings with their planning,
4/// and the active timestamps and date ranges org's agenda would consider. Positions are UTF-16. 4/// and the active timestamps and date ranges org's agenda would consider. Positions are UTF-16.
5public struct AgendaSource: Sendable { 5public struct AgendaSource: Sendable {
6 static let planningRegex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE): *<([^>]+)>")
7 static let planningAnyRegex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE|CLOSED): *([\\[<]\(Self.tsInternal)[\\]>])")
8 static let activeRangeRegex = try! NSRegularExpression(pattern: "<(\(Self.tsInternal))>--?-?<(\(Self.tsInternal))>")
9 static let inactiveRegex = try! NSRegularExpression(pattern: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)\\]")
10 static let dateRangeRegex = try! NSRegularExpression(pattern: "[\\[<](\(tsInternal))[\\]>]--?-?[\\[<](\(tsInternal))[\\]>]")
11
6 public let path: String 12 public let path: String
7 /// The file names `#+SETUPFILE`s. 13 /// The file names `#+SETUPFILE`s.
8 public let readsSetupFiles: Bool 14 public let readsSetupFiles: Bool
@@ -110,7 +116,7 @@ public struct AgendaSource: Sendable {
110 /// setting is on. 116 /// setting is on.
111 public init(path: String, text: String, defaults: OrgSettings = .default, checksBlocking: Bool = true) { 117 public init(path: String, text: String, defaults: OrgSettings = .default, checksBlocking: Bool = true) {
112 self.path = path 118 self.path = path
113 readsSetupFiles = text.range(of: "#+setupfile:", options: .caseInsensitive) != nil 119 readsSetupFiles = text.containsIgnoringASCIICase("#+setupfile:")
114 let tree = OrgParser.parse(text, defaults: defaults) 120 let tree = OrgParser.parse(text, defaults: defaults)
115 let model = DocumentModel(tree: tree) 121 let model = DocumentModel(tree: tree)
116 let ns = text as NSString 122 let ns = text as NSString
@@ -215,13 +221,13 @@ public struct AgendaSource: Sendable {
215 let afterHeading = info.headingRange.upperBound 221 let afterHeading = info.headingRange.upperBound
216 if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) { 222 if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) {
217 let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count)) 223 let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count))
218 let regex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE): *<([^>]+)>") 224 let regex = Self.planningRegex
219 let pns = planningText as NSString 225 let pns = planningText as NSString
220 for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) { 226 for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
221 let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1) 227 let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1)
222 if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value } 228 if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value }
223 } 229 }
224 let any = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE|CLOSED): *([\\[<]\(Self.tsInternal)[\\]>])") 230 let any = Self.planningAnyRegex
225 for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) { 231 for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
226 let key = pns.substring(with: m.range(at: 1)) 232 let key = pns.substring(with: m.range(at: 1))
227 if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) } 233 if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) }
@@ -314,7 +320,7 @@ public struct AgendaSource: Sendable {
314 320
315 // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks. 321 // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks.
316 var blocks: [Block] = [] 322 var blocks: [Block] = []
317 let range = try! NSRegularExpression(pattern: "<(\(Self.tsInternal))>--?-?<(\(Self.tsInternal))>") 323 let range = Self.activeRangeRegex
318 for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) { 324 for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
319 let point = NSMaxRange(m.range) 325 let point = NSMaxRange(m.range)
320 let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0))) 326 let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0)))
@@ -328,7 +334,7 @@ public struct AgendaSource: Sendable {
328 // Log lines: org searches the raw text, then the heading above each match. 334 // Log lines: org searches the raw text, then the heading above each match.
329 let keywordPattern = keywords.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") 335 let keywordPattern = keywords.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
330 let logLine = try! NSRegularExpression(pattern: "(\\bCLOSED:|\\bCLOCK:|- +State \"(\(keywordPattern.isEmpty ? "(?!)" : keywordPattern))\".*?) *\\[([0-9]{4}-[0-9]{2}-[0-9]{2})") 336 let logLine = try! NSRegularExpression(pattern: "(\\bCLOSED:|\\bCLOCK:|- +State \"(\(keywordPattern.isEmpty ? "(?!)" : keywordPattern))\".*?) *\\[([0-9]{4}-[0-9]{2}-[0-9]{2})")
331 let inactive = try! NSRegularExpression(pattern: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)\\]") 337 let inactive = Self.inactiveRegex
332 let clockEnd = try! NSRegularExpression(pattern: "([0-9]{1,2}:[0-9]{2})\\].*?([0-9]{1,2}:[0-9]{2})") 338 let clockEnd = try! NSRegularExpression(pattern: "([0-9]{1,2}:[0-9]{2})\\].*?([0-9]{1,2}:[0-9]{2})")
333 let stateNote = try! NSRegularExpression(pattern: ".*\\\\\\n[ \\t]*([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines) 339 let stateNote = try! NSRegularExpression(pattern: ".*\\\\\\n[ \\t]*([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
334 let clockNote = try! NSRegularExpression(pattern: ".*\\n[ \\t]*-[ \\t]+([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines) 340 let clockNote = try! NSRegularExpression(pattern: ".*\\n[ \\t]*-[ \\t]+([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
@@ -380,7 +386,7 @@ public struct AgendaSource: Sendable {
380 static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool { 386 static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool {
381 let point = offset + 11 387 let point = offset + 11
382 let line = ns.lineRange(for: NSRange(location: offset, length: 0)) 388 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
383 let regex = try! NSRegularExpression(pattern: "[\\[<](\(tsInternal))[\\]>]--?-?[\\[<](\(tsInternal))[\\]>]") 389 let regex = Self.dateRangeRegex
384 for m in regex.matches(in: ns as String, range: line) { 390 for m in regex.matches(in: ns as String, range: line) {
385 if m.range.location > point { break } 391 if m.range.location > point { break }
386 if NSMaxRange(m.range) >= point { return true } 392 if NSMaxRange(m.range) >= point { return true }
Sources/OrgCore/Agenda/Days.swift +3 −1
@@ -3,6 +3,8 @@ import Foundation
3/// Calendar days as Emacs numbers them (`calendar-absolute-from-gregorian`): 1 is 3/// Calendar days as Emacs numbers them (`calendar-absolute-from-gregorian`): 1 is
4/// 1 January of year 1, proleptic Gregorian. 4/// 1 January of year 1, proleptic Gregorian.
5public enum Days { 5public enum Days {
6 static let hourRegex = try! NSRegularExpression(pattern: "^( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))")
7
6 /// Out-of-range days and months roll over, as with `encode-time`. 8 /// Out-of-range days and months roll over, as with `encode-time`.
7 public static func absolute(year: Int, month: Int, day: Int) -> Int { 9 public static func absolute(year: Int, month: Int, day: Int) -> Int {
8 let monthIndex = month - 1 10 let monthIndex = month - 1
@@ -65,7 +67,7 @@ public enum Days {
65 guard let date = dateRegex.firstMatch(in: string, range: NSRange(location: 0, length: ns.length)) else { return 0 } 67 guard let date = dateRegex.firstMatch(in: string, range: NSRange(location: 0, length: ns.length)) else { return 0 }
66 let rest = NSRange(location: NSMaxRange(date.range), length: ns.length - NSMaxRange(date.range)) 68 let rest = NSRange(location: NSMaxRange(date.range), length: ns.length - NSMaxRange(date.range))
67 // org-ts-regexp0: a day name may sit between the date and the time. 69 // org-ts-regexp0: a day name may sit between the date and the time.
68 let pattern = try! NSRegularExpression(pattern: "^( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))") 70 let pattern = Self.hourRegex
69 guard let m = pattern.firstMatch(in: string, range: rest) else { return 0 } 71 guard let m = pattern.firstMatch(in: string, range: rest) else { return 0 }
70 return Int(ns.substring(with: m.range(at: 3)))! 72 return Int(ns.substring(with: m.range(at: 3)))!
71 } 73 }
Sources/OrgCore/Agenda/PrefixFormat.swift +3 −1
@@ -7,6 +7,8 @@ import Foundation
7/// width with an optional `.N` limit on categories, and a punctuation character added after a 7/// width with an optional `.N` limit on categories, and a punctuation character added after a
8/// non-empty value. `%(…)` forms run Lisp; they are empty here. 8/// non-empty value. `%(…)` forms run Lisp; they are empty here.
9public struct PrefixFormat: Sendable, Equatable { 9public struct PrefixFormat: Sendable, Equatable {
10 static let directiveRegex = try! NSRegularExpression(pattern: "%(\\?)?([-+]?[0-9.]*)([ .;,:!?=|/<>]?)([cltseibT]|\\(.+?\\))")
11
10 enum Piece: Sendable, Equatable { 12 enum Piece: Sendable, Equatable {
11 case literal(String) 13 case literal(String)
12 case field(key: Character, optional: Bool, width: String, punctuation: String) 14 case field(key: Character, optional: Bool, width: String, punctuation: String)
@@ -19,7 +21,7 @@ public struct PrefixFormat: Sendable, Equatable {
19 let categoryMaxLength: Int? 21 let categoryMaxLength: Int?
20 22
21 public init(_ format: String) { 23 public init(_ format: String) {
22 let regex = try! NSRegularExpression(pattern: "%(\\?)?([-+]?[0-9.]*)([ .;,:!?=|/<>]?)([cltseibT]|\\(.+?\\))") 24 let regex = Self.directiveRegex
23 let ns = format as NSString 25 let ns = format as NSString
24 var pieces: [Piece] = [] 26 var pieces: [Piece] = []
25 var hasTime = false 27 var hasTime = false
Sources/OrgCore/Commands/Statistics.swift +2 −1
@@ -51,7 +51,8 @@ extension EmacsBuffer {
51 guard let start = try? backToHeading() else { return nil } 51 guard let start = try? backToHeading() else { return nil }
52 let level = headingLevel(atLine: start)! 52 let level = headingLevel(atLine: start)!
53 var at = start 53 var at = start
54 while let previous = previousHeadingStart(before: at) { 54 // A top-level heading has no parent; without this the walk goes to the top of the file.
55 while level > 1, let previous = previousHeadingStart(before: at) {
55 at = previous 56 at = previous
56 if let parentLevel = headingLevel(atLine: previous), parentLevel < level { 57 if let parentLevel = headingLevel(atLine: previous), parentLevel < level {
57 point = previous 58 point = previous
Sources/OrgCore/Export/Citations.swift +2 −2
@@ -79,7 +79,7 @@ struct CiteProcessor {
79 /// The text with nocite citations removed, and the blanks before them, as 79 /// The text with nocite citations removed, and the blanks before them, as
80 /// `org-cite--set-previous-post-blank` leaves it. 80 /// `org-cite--set-previous-post-blank` leaves it.
81 static func removingNocite(_ text: String) -> String { 81 static func removingNocite(_ text: String) -> String {
82 guard text.range(of: "[cite", options: .caseInsensitive) != nil else { return text } 82 guard text.containsIgnoringASCIICase("[cite") else { return text }
83 let defaultStyle = exportSettings(text)?.citeStyle 83 let defaultStyle = exportSettings(text)?.citeStyle
84 let regex = try! NSRegularExpression(pattern: "[ \\t]*(\\[cite[/:][^\\]]*\\])") 84 let regex = try! NSRegularExpression(pattern: "[ \\t]*(\\[cite[/:][^\\]]*\\])")
85 var out = text 85 var out = text
@@ -383,7 +383,7 @@ struct CiteProcessor {
383 /// The citations of `text` (as written, nocite citations included) worked out in document 383 /// The citations of `text` (as written, nocite citations included) worked out in document
384 /// order, then the bibliography; nil when the export leaves citations alone. 384 /// order, then the bibliography; nil when the export leaves citations alone.
385 init?(text: String, directory: URL?) { 385 init?(text: String, directory: URL?) {
386 guard text.range(of: "[cite", options: .caseInsensitive) != nil else { return nil } 386 guard text.containsIgnoringASCIICase("[cite") else { return nil }
387 let settings = Self.exportSettings(text) 387 let settings = Self.exportSettings(text)
388 if let settings, settings.processor != "basic" { return nil } 388 if let settings, settings.processor != "basic" { return nil }
389 // Each `#+bibliography:` names one file. 389 // Each `#+bibliography:` names one file.
Sources/OrgCore/Export/ExportOptions.swift +1 −1
@@ -95,7 +95,7 @@ public enum ExportPreprocess {
95 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with 95 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with
96 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`. 96 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`.
97 public static func includes(_ text: String, directory: URL?, depth: Int = 0) -> String { 97 public static func includes(_ text: String, directory: URL?, depth: Int = 0) -> String {
98 guard depth < 8, text.range(of: "#+INCLUDE:", options: .caseInsensitive) != nil else { return text } 98 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text }
99 var lines: [String] = [] 99 var lines: [String] = []
100 for line in text.components(separatedBy: "\n") { 100 for line in text.components(separatedBy: "\n") {
101 guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"(.*)$/#) else { 101 guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"(.*)$/#) else {
Sources/OrgCore/Parser/Parser.swift +42 −7
@@ -382,24 +382,23 @@ struct Parser {
382 let bullet = rest.prefix { $0 != " " && $0 != "\t" } 382 let bullet = rest.prefix { $0 != " " && $0 != "\t" }
383 builder.token(.bullet, bullet) 383 builder.token(.bullet, bullet)
384 rest = whitespace(rest.dropFirst(bullet.count)) 384 rest = whitespace(rest.dropFirst(bullet.count))
385 if let counter = rest.prefixMatch(of: /\[@(?:start:)?(?:[0-9]+|[A-Za-z])\]/) { 385 if let counter = Self.counter(rest) {
386 builder.token(.counter, rest[counter.range]) 386 builder.token(.counter, counter)
387 rest = whitespace(rest[counter.range.upperBound...]) 387 rest = whitespace(rest[counter.endIndex...])
388 } 388 }
389 if let box = checkbox(rest) { 389 if let box = checkbox(rest) {
390 builder.token(.checkbox, box) 390 builder.token(.checkbox, box)
391 rest = whitespace(rest.dropFirst(box.count)) 391 rest = whitespace(rest.dropFirst(box.count))
392 } 392 }
393 // A description item's tag: up to the last ` ::` on the line, for `-`, `+` and `*`. 393 // A description item's tag: up to the last ` ::` on the line, for `-`, `+` and `*`.
394 if "-+*".contains(bullet), let m = rest.prefixMatch(of: /(.*)([ \t]+::)(?:[ \t]+|$)/.anchorsMatchLineEndings()) { 394 if "-+*".contains(bullet), let (tag, separator) = Self.descriptionTag(rest) {
395 builder.start(.itemTag) 395 builder.start(.itemTag)
396 inline(rest[m.1.startIndex..<m.1.endIndex]) 396 inline(tag)
397 builder.finish() 397 builder.finish()
398 let separator = rest[m.2.startIndex..<m.2.endIndex]
399 let blank = separator.prefix { $0 == " " || $0 == "\t" } 398 let blank = separator.prefix { $0 == " " || $0 == "\t" }
400 builder.token(.whitespace, blank) 399 builder.token(.whitespace, blank)
401 builder.token(.marker, separator.dropFirst(blank.count)) 400 builder.token(.marker, separator.dropFirst(blank.count))
402 rest = whitespace(rest[m.2.endIndex...]) 401 rest = whitespace(rest[separator.endIndex...])
403 } 402 }
404 // The rest of the bullet line and its continuation lines are the item's first paragraph. 403 // The rest of the bullet line and its continuation lines are the item's first paragraph.
405 var end = i + 1 404 var end = i + 1
@@ -432,6 +431,42 @@ struct Parser {
432 } 431 }
433 432
434 /// `[ ]`, `[X]`, `[x]` or `[-]`, followed by whitespace or end of line. 433 /// `[ ]`, `[X]`, `[x]` or `[-]`, followed by whitespace or end of line.
434 /// A counter cookie at the start of `s`: `[@3]`, `[@start:3]`, `[@b]`.
435 static func counter(_ s: Substring) -> Substring? {
436 guard s.hasPrefix("[@") else { return nil }
437 func value(from start: Substring.Index) -> Substring.Index? {
438 var j = start
439 while j < s.endIndex, s[j].isASCII, s[j].isNumber { j = s.index(after: j) }
440 if j == start {
441 guard j < s.endIndex, s[j].isASCII, s[j].isLetter else { return nil }
442 j = s.index(after: j)
443 }
444 return j < s.endIndex && s[j] == "]" ? s.index(after: j) : nil
445 }
446 let afterAt = s.index(s.startIndex, offsetBy: 2)
447 if s[afterAt...].hasPrefix("start:"), let end = value(from: s.index(afterAt, offsetBy: 6)) { return s[..<end] }
448 return value(from: afterAt).map { s[..<$0] }
449 }
450
451 /// A description item's tag and separator: the text before the last ` ::` on the line
452 /// that ends it or has blanks after it, and that blank with the `::`.
453 static func descriptionTag(_ s: Substring) -> (tag: Substring, separator: Substring)? {
454 let line = s.prefix { $0 != "\n" && $0 != "\r" }
455 var k = line.endIndex
456 while k > line.startIndex {
457 k = line.index(before: k)
458 guard line[k] == ":", k > line.startIndex else { continue }
459 let colon = line.index(before: k)
460 guard line[colon] == ":", colon > line.startIndex else { continue }
461 let blank = line.index(before: colon)
462 guard line[blank] == " " || line[blank] == "\t" else { continue }
463 let after = line.index(after: k)
464 guard after == line.endIndex || line[after] == " " || line[after] == "\t" else { continue }
465 return (line[..<blank], line[blank...k])
466 }
467 return nil
468 }
469
435 func checkbox(_ s: Substring) -> Substring? { 470 func checkbox(_ s: Substring) -> Substring? {
436 guard s.count >= 3, s.first == "[", "Xx -".contains(s.dropFirst().first!), 471 guard s.count >= 3, s.first == "[", "Xx -".contains(s.dropFirst().first!),
437 s.dropFirst(2).first == "]" else { return nil } 472 s.dropFirst(2).first == "]" else { return nil }
Sources/OrgCore/Parser/Settings.swift +1 −1
@@ -125,7 +125,7 @@ enum SettingsScanner {
125 } 125 }
126 let sequences = types + todos + seqs 126 let sequences = types + todos + seqs
127 var radio: [String] = [] 127 var radio: [String] = []
128 for line in lines where line.content.contains("<<<") { 128 for line in lines where line.content.utf8.contains(UInt8(ascii: "<")) && line.content.contains("<<<") {
129 for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) { 129 for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) {
130 radio.append(String(m.1)) 130 radio.append(String(m.1))
131 } 131 }
Sources/OrgCore/Parser/SetupFile.swift +1 −1
@@ -12,7 +12,7 @@ public enum SetupFile {
12 } 12 }
13 13
14 private static func lines(in text: String, directory: String, read: (String) -> String?, own: Bool, seen: Set<String>) -> String { 14 private static func lines(in text: String, directory: String, read: (String) -> String?, own: Bool, seen: Set<String>) -> String {
15 guard own || text.range(of: "#+setupfile:", options: .caseInsensitive) != nil else { return "" } 15 guard own || text.containsIgnoringASCIICase("#+setupfile:") else { return "" }
16 var out = "" 16 var out = ""
17 for node in OrgParser.parse(text).root.descendants() where node.kind == .keyword { 17 for node in OrgParser.parse(text).root.descendants() where node.kind == .keyword {
18 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines) 18 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
Sources/OrgIndex/FileRecord.swift +2 −2
@@ -132,7 +132,7 @@ public struct FileRecord: Sendable, Equatable {
132 /// The settings version a file's rows are built under: the index's, with the keywords of 132 /// The settings version a file's rows are built under: the index's, with the keywords of
133 /// the setup files it names mixed in, so a changed setup file indexes it again. 133 /// the setup files it names mixed in, so a changed setup file indexes it again.
134 public static func settingsVersion(_ settings: IndexSettings, text: String, setupKeywords: String) -> Int { 134 public static func settingsVersion(_ settings: IndexSettings, text: String, setupKeywords: String) -> Int {
135 guard text.range(of: "#+setupfile:", options: .caseInsensitive) != nil else { return settings.version } 135 guard text.containsIgnoringASCIICase("#+setupfile:") else { return settings.version }
136 var hash: UInt64 = 0xcbf29ce484222325 136 var hash: UInt64 = 0xcbf29ce484222325
137 for byte in setupKeywords.utf8 { 137 for byte in setupKeywords.utf8 {
138 hash ^= UInt64(byte) 138 hash ^= UInt64(byte)
@@ -144,7 +144,7 @@ public struct FileRecord: Sendable, Equatable {
144 /// `settingsVersion` for a file's bytes, reading the setup files it names. 144 /// `settingsVersion` for a file's bytes, reading the setup files it names.
145 public static func settingsVersion(_ settings: IndexSettings, bytes: [UInt8], path: String) -> Int { 145 public static func settingsVersion(_ settings: IndexSettings, bytes: [UInt8], path: String) -> Int {
146 let text = SourceText(bytes: bytes).text 146 let text = SourceText(bytes: bytes).text
147 guard text.range(of: "#+setupfile:", options: .caseInsensitive) != nil else { return settings.version } 147 guard text.containsIgnoringASCIICase("#+setupfile:") else { return settings.version }
148 let keywords = settings.org.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile).setupKeywords 148 let keywords = settings.org.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile).setupKeywords
149 return settingsVersion(settings, text: text, setupKeywords: keywords) 149 return settingsVersion(settings, text: text, setupKeywords: keywords)
150 } 150 }
Tests/OrgCoreTests/ASCIISearchTests.swift added +15
@@ -0,0 +1,15 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct ASCIISearchTests {
6 @Test func matchesCaseInsensitiveRangeOf() {
7 let texts = ["", "#+SETUPFILE: x", "a\n#+SetupFile:y", "#+setupfil", "é #+setupfile:", "##+setupfile:", "[CITE:@a]", "x[cit"]
8 for text in texts {
9 for needle in ["#+setupfile:", "[cite", "#+INCLUDE:"] {
10 #expect(text.containsIgnoringASCIICase(needle) == (text.range(of: needle, options: .caseInsensitive) != nil), "\(text) \(needle)")
11 #expect(text[...].containsIgnoringASCIICase(needle) == (text.range(of: needle, options: .caseInsensitive) != nil))
12 }
13 }
14 }
15}
Tests/OrgCoreTests/ListItemScanTests.swift added +36
@@ -0,0 +1,36 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// The hand-written scans for list item counters and description tags against the
6/// patterns they replace.
7struct ListItemScanTests {
8 static let pieces = ["[@", "start:", "3", "12", "b", "B", "]", " ", "\t", "::", ":", "a", "é", "x y", "[", "\\n"]
9
10 static func strings() -> [Substring] {
11 var generator = SystemRandomNumberGenerator()
12 var out: [Substring] = ["", "[@3]", "[@start:3] x", "[@b]", "[@start:]", "[@start:b]", "[@3", "[@ab]", "a :: b", "a ::", "a::b",
13 "a :: b :: c", "a\t::\tb", " :: x", "::", "a ::b", "tag :: rest", "x :: y\nz :: w"]
14 for _ in 0..<5000 {
15 let count = Int.random(in: 1...7, using: &generator)
16 out.append(Substring((0..<count).map { _ in pieces.randomElement(using: &generator)! }.joined().replacingOccurrences(of: "\\n", with: "\n")))
17 }
18 return out
19 }
20
21 @Test func counterMatchesThePattern() {
22 for s in Self.strings() {
23 let expected = s.prefixMatch(of: /\[@(?:start:)?(?:[0-9]+|[A-Za-z])\]/).map { s[$0.range] }
24 #expect(Parser.counter(s) == expected, "\(s.debugDescription)")
25 }
26 }
27
28 @Test func descriptionTagMatchesThePattern() {
29 for s in Self.strings() {
30 let m = s.prefixMatch(of: /(.*)([ \t]+::)(?:[ \t]+|$)/.anchorsMatchLineEndings())
31 let found = Parser.descriptionTag(s)
32 #expect(found?.tag == m.map { s[$0.1.startIndex..<$0.1.endIndex] }, "\(s.debugDescription)")
33 #expect(found?.separator == m.map { s[$0.2.startIndex..<$0.2.endIndex] }, "\(s.debugDescription)")
34 }
35 }
36}