Sources/OrgCore/Agenda/AgendaSearch.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgCore/Agenda/AgendaSearch.swift history · blame · raw

646 lines · 33337 bytes

  1import Foundation
  2
  3extension Agenda {
  4    /// `org-todo-list`: unfinished entries, or with `keywords` (`WAIT|HOLD`) those with any of
  5    /// the keywords, without those the `todoIgnore` options leave out on `today`.
  6    public static func todoList(_ sources: [AgendaSource], keywords: String? = nil, options: AgendaOptions = AgendaOptions(),
  7                                today: Int = Days.absolute(Date(), calendar: .current)) -> [AgendaItem] {
  8        let selected = keywords.map { $0.split(separator: "|").map(String.init) }
  9        var items: [AgendaItem] = []
 10        for source in sources {
 11            for (index, heading) in source.headings.enumerated() where !heading.skipped {
 12                guard let todo = heading.todo else { continue }
 13                if let selected {
 14                    guard selected.contains(todo) else { continue }
 15                } else if heading.isDone {
 16                    continue
 17                }
 18                if ignoresTodo(source, index, options: options, today: today) { continue }
 19                items.append(format(
 20                    source, heading, kind: .todo, marker: heading.start, extra: "", dotime: .headline, removing: nil,
 21                    trailing: "", prefix: options.prefix("todo"), urgency: { 1 + $0 }
 22                ))
 23            }
 24        }
 25        return sortByUrgency(markBlocked(items, options: options))
 26    }
 27
 28    /// `org-tags-view`: entries matching a tags/property/TODO match string. `todoOnly` keeps
 29    /// unfinished TODO entries, as `M` does.
 30    public static func tagsMatch(
 31        _ sources: [AgendaSource], match: String, todoOnly: Bool = false, now: Date = Date(), calendar: Calendar = .current,
 32        options: AgendaOptions = AgendaOptions()
 33    ) -> [AgendaItem] {
 34        let matcher = TagsMatcher(match, todoOnly: todoOnly)
 35        let today = Days.absolute(now, calendar: calendar)
 36        var items: [AgendaItem] = []
 37        for source in sources {
 38            for (index, heading) in source.headings.enumerated() {
 39                if matcher.todoOnly, heading.todo == nil { continue }
 40                guard matcher.matches(heading, in: source, now: now, calendar: calendar), !heading.skipped else { continue }
 41                if matcher.todoOnly, options.tagsTodoHonorIgnoreOptions, ignoresTodo(source, index, options: options, today: today) { continue }
 42                items.append(format(
 43                    source, heading, kind: .tagsMatch, marker: heading.start, extra: "", dotime: nil, removing: nil,
 44                    trailing: "", prefix: options.prefix("tags"), urgency: { $0 }
 45                ))
 46            }
 47        }
 48        return sortByUrgency(markBlocked(items, options: options))
 49    }
 50
 51    /// `org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item` for the entry of heading
 52    /// `index`, from its heading line to the next heading. The searches go on from where the
 53    /// last one matched, as Org's do.
 54    static func ignoresTodo(_ source: AgendaSource, _ index: Int, options: AgendaOptions, today: Int) -> Bool {
 55        guard options.todoIgnoreWithDate || options.todoIgnoreScheduled != .off || options.todoIgnoreDeadlines != .off
 56            || options.todoIgnoreTimestamp != .off else { return false }
 57        let ns = source.text as NSString
 58        let start = source.headings[index].start
 59        let end = index + 1 < source.headings.count ? source.headings[index + 1].start : ns.length
 60        var point = start
 61        func search(_ regex: NSRegularExpression) -> String? {
 62            guard let m = regex.firstMatch(in: source.text, range: NSRange(location: point, length: end - point)) else { return nil }
 63            point = NSMaxRange(m.range)
 64            return ns.substring(with: m.range(at: 1))
 65        }
 66        func days(_ stamp: String) -> Int { (Days.absolute(of: stamp) ?? today) - today }
 67        func custom(_ stamp: String, _ n: Int) -> Bool { n >= 0 ? days(stamp) >= n : days(stamp) <= n }
 68        if options.todoIgnoreWithDate, search(Self.activeStampRegex) != nil { return true }
 69        if options.todoIgnoreScheduled != .off, let stamp = search(Self.scheduledRegex) {
 70            switch options.todoIgnoreScheduled {
 71            case .future: if days(stamp) > 0 { return true }
 72            case .past: if days(stamp) <= 0 { return true }
 73            case .days(let n): if custom(stamp, n) { return true }
 74            default: return true
 75            }
 76        }
 77        if options.todoIgnoreDeadlines != .off, let stamp = search(Self.deadlineRegex) {
 78            let close = days(stamp) <= Days.warningDays(stamp, delay: false, defaultDays: options.deadlineWarningDays) && !source.headings[index].isDone
 79            switch options.todoIgnoreDeadlines {
 80            case .all: return true
 81            case .far: if !close { return true }
 82            case .future: if days(stamp) > 0 { return true }
 83            case .past: if days(stamp) <= 0 { return true }
 84            case .days(let n): if custom(stamp, n) { return true }
 85            default: if close { return true }
 86            }
 87        }
 88        if options.todoIgnoreTimestamp != .off {
 89            // The other timestamps, without SCHEDULED and DEADLINE ones.
 90            let rest = Self.planningStampRegex.stringByReplacingMatches(in: ns.substring(with: NSRange(location: point, length: end - point)), range: NSRange(location: 0, length: end - point), withTemplate: "")
 91            guard let m = Self.activeStampRegex.firstMatch(in: rest, range: NSRange(location: 0, length: (rest as NSString).length)) else { return false }
 92            let stamp = (rest as NSString).substring(with: m.range(at: 1))
 93            switch options.todoIgnoreTimestamp {
 94            case .future: return days(stamp) > 0
 95            case .past: return days(stamp) <= 0
 96            case .days(let n): return custom(stamp, n)
 97            default: return true
 98            }
 99        }
100        return false
101    }
102
103    /// `org-ts-regexp`, `org-scheduled-time-regexp` and `org-deadline-time-regexp`.
104    static let activeStampRegex = try! NSRegularExpression(pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?)>")
105    static let scheduledRegex = try! NSRegularExpression(pattern: "\\bSCHEDULED: *<([^>]+)>")
106    static let deadlineRegex = try! NSRegularExpression(pattern: "\\bDEADLINE: *<([^>]+)>")
107    static let planningStampRegex = try! NSRegularExpression(pattern: "\\bSCHEDULED: *<[^>]+>|\\bDEADLINE: *<[^>]+>")
108
109    /// `org-search-view`: entries, heading and body, containing `string` as a phrase, or with
110    /// a leading `+`, `-` or `{` (or `searchAlwaysBoolean`) matching each of its snippets. A
111    /// leading `*` searches headlines only, `!` keeps unfinished TODO entries as `todoOnly`
112    /// does, and `:` matches whole words. Text before the first heading is not searched.
113    public static func textSearch(_ sources: [AgendaSource], string: String, todoOnly: Bool = false, options: AgendaOptions = AgendaOptions()) -> [AgendaItem] {
114        let query = SearchQuery(string, todoOnly: todoOnly, options: options)
115        // Org searches for the longest positive snippet, then checks the entry it is in.
116        var positive = query.positive
117        let first = positive.isEmpty ? nil : positive.removeFirst()
118        let patterns = positive.compactMap(\.regex)
119        let negative = query.negative.compactMap(\.regex)
120        guard let search = SearchQuery.compile(first.map { (query.headlinesOnly ? "^\\*+ .*?" : "") + $0.emacs } ?? "^\\*+ "),
121              patterns.count == positive.count, negative.count == query.negative.count else { return [] }
122        let headingLine = try! NSRegularExpression(pattern: "^\\*+ ", options: .anchorsMatchLines)
123        var items: [AgendaItem] = []
124        for source in sources {
125            let text = source.text
126            let ns = text as NSString
127            let length = ns.length
128            let starts = headingLine.matches(in: text, range: NSRange(location: 0, length: length)).map(\.range.location)
129            guard let firstHeading = starts.first else { continue }
130            let byStart = Dictionary(source.headings.map { ($0.start, $0) }, uniquingKeysWith: { a, _ in a })
131            var required = patterns
132            if query.todoOnly {
133                guard !source.notDoneKeywords.isEmpty else { continue }
134                let keywords = source.notDoneKeywords.map(SearchQuery.quote).joined(separator: "\\|")
135                required.insert(SearchQuery.compile("^\\*+[ \\t]+\\(" + keywords + "\\)")!, at: 0)
136            }
137            func lineStart(_ at: Int) -> Int {
138                let newline = ns.range(of: "\n", options: .backwards, range: NSRange(location: 0, length: at))
139                return newline.location == NSNotFound ? 0 : newline.location + 1
140            }
141            var at = max(0, firstHeading - 1)
142            while at <= length, let m = search.firstMatch(in: text, options: [.withoutAnchoringBounds, .withTransparentBounds], range: NSRange(location: at, length: length - at)) {
143                let matchEnd = NSMaxRange(m.range)
144                // `org-back-to-heading`, then `outline-next-heading`.
145                guard let index = starts.lastIndex(where: { $0 <= lineStart(matchEnd) }) else { break }
146                let beg = starts[index]
147                let end = index + 1 < starts.count ? starts[index + 1] : length
148                let next = max(end - 1, at + 1)
149                guard let entry = byStart[beg] else {
150                    at = next
151                    continue
152                }
153                if entry.skipped {
154                    // `org-agenda-skip` leaves point at the end of the subtree, before blank lines.
155                    var stop = starts[(index + 1)...].first { byStart[$0].map { $0.level <= entry.level } ?? false } ?? length
156                    if stop > 0, [10, 13].contains(ns.character(at: stop - 1)) {
157                        stop -= 1
158                        while stop > beg, [9, 10, 13, 32].contains(ns.character(at: stop - 1)) { stop -= 1 }
159                    }
160                    at = max(stop, at + 1)
161                    continue
162                }
163                let lineEnd = ns.range(of: "\n", range: NSRange(location: beg, length: length - beg)).location
164                let stop = query.headlinesOnly && lineEnd != NSNotFound ? lineEnd : end
165                let entryText = ns.substring(with: NSRange(location: beg, length: stop - beg))
166                func found(_ regex: NSRegularExpression) -> Bool {
167                    regex.firstMatch(in: entryText, range: NSRange(location: 0, length: (entryText as NSString).length)) != nil
168                }
169                if !negative.contains(where: found), required.allSatisfy(found) {
170                    items.append(format(
171                        source, entry, kind: .search, marker: beg, extra: "", dotime: .headline, removing: nil,
172                        trailing: "", prefix: options.prefix("search"), urgency: { _ in 1000 }
173                    ))
174                    at = max(next, matchEnd)
175                } else {
176                    at = next
177                }
178            }
179        }
180        return items
181    }
182
183    /// An `org-search-view` string read into regexps, in Emacs syntax and compiled.
184    struct SearchQuery {
185        struct Pattern {
186            let emacs: String
187            let regex: NSRegularExpression?
188        }
189
190        let headlinesOnly: Bool
191        let todoOnly: Bool
192        let boolean: Bool
193        /// Longest first, as Org sorts them.
194        let positive: [Pattern]
195        let negative: [Pattern]
196
197        init(_ string: String, todoOnly: Bool, options: AgendaOptions) {
198            var words = Substring(string)
199            headlinesOnly = words.first == "*"
200            if headlinesOnly { words.removeFirst() }
201            var todo = todoOnly
202            if words.first == "!" {
203                todo = true
204                words.removeFirst()
205            }
206            self.todoOnly = todo
207            var fullWords = options.searchForceFullWords
208            if words.first == ":" {
209                fullWords = true
210                words.removeFirst()
211            }
212            boolean = options.searchAlwaysBoolean || ["-", "+", "{"].contains(words.first)
213
214            // `split-string`, then words ending in `\` joined to the next, and `{…}` kept whole.
215            var pending = words.split(whereSeparator: { " \u{0C}\t\n\r\u{0B}".contains($0) }).map(String.init)
216            var joined: [String] = []
217            while !pending.isEmpty {
218                var w = pending.removeFirst()
219                while w.hasSuffix("\\"), !pending.isEmpty { w = String(w.dropLast()) + " " + pending.removeFirst() }
220                joined.append(w)
221            }
222            pending = joined
223            joined = []
224            while !pending.isEmpty {
225                var w = pending.removeFirst()
226                if w.range(of: "^[-+]?\\{", options: .regularExpression) != nil, !w.hasSuffix("}") {
227                    while let next = pending.first, !next.hasSuffix("}") { w += " " + pending.removeFirst() }
228                    w += " " + (pending.isEmpty ? "" : pending.removeFirst())
229                }
230                joined.append(w)
231            }
232            if boolean {
233                pending = joined
234                joined = []
235                while !pending.isEmpty {
236                    var w = pending.removeFirst()
237                    let chars = Array(w)
238                    if chars[0] == "\"" || (chars.count > 1 && "+-".contains(chars[0]) && chars[1] == "\"") {
239                        while !pending.isEmpty, !w.hasSuffix("\"") { w += " " + pending.removeFirst() }
240                    }
241                    w = w.replacingOccurrences(of: "^([-+]?)\"", with: "$1", options: .regularExpression)
242                    if w.hasSuffix("\"") { w.removeLast() }
243                    joined.append(w)
244                }
245            }
246
247            var positive: [String] = []
248            var negative: [String] = []
249            if boolean {
250                for word in joined {
251                    var w = Substring(word)
252                    let negated = w.first == "-"
253                    if negated || w.first == "+" { w = w.dropFirst() }
254                    let re: String
255                    if w.count >= 2, w.first == "{", w.last == "}" {
256                        re = String(w.dropFirst().dropLast())
257                    } else {
258                        re = fullWords ? "\\<" + Self.quote(w.lowercased()) + "\\>" : Self.quote(w.lowercased())
259                    }
260                    if negated { negative.insert(re, at: 0) } else { positive.insert(re, at: 0) }
261                }
262            } else {
263                positive = [joined.map(Self.quote).joined(separator: "\\s-+")]
264            }
265            // `sort` is stable; the snippets were pushed, so the last comes first among equals.
266            self.positive = positive.enumerated().sorted { a, b in
267                a.element.count != b.element.count ? a.element.count > b.element.count : a.offset < b.offset
268            }.map { Pattern(emacs: $0.element, regex: Self.compile($0.element)) }
269            self.negative = negative.map { Pattern(emacs: $0, regex: Self.compile($0)) }
270        }
271
272        /// `regexp-quote`.
273        static func quote(_ s: String) -> String {
274            var out = ""
275            for c in s {
276                if "[*.\\?+^$".contains(c) { out.append("\\") }
277                out.append(c)
278            }
279            return out
280        }
281
282        /// Case-insensitive, as Org binds `case-fold-search`, with `^` and `$` at each line.
283        static func compile(_ emacs: String) -> NSRegularExpression? {
284            try? NSRegularExpression(pattern: EmacsRegex.translate(emacs, search: true), options: [.caseInsensitive, .anchorsMatchLines])
285        }
286    }
287
288    /// `(urgency-down category-keep)`, stably.
289    static func sortByUrgency(_ items: [AgendaItem]) -> [AgendaItem] {
290        items.enumerated().sorted { a, b in
291            a.element.urgency != b.element.urgency ? a.element.urgency > b.element.urgency : a.offset < b.offset
292        }.map(\.element)
293    }
294}
295
296/// `org-make-tags-matcher`: `+work-boss|LEVEL>2+TODO="WAIT"/!NEXT`.
297public struct TagsMatcher: Sendable {
298    static let slashesRegex = try! NSRegularExpression(pattern: "/+")
299
300    indirect enum Term: Sendable {
301        case tag(String)
302        case tagRegex(String)
303        case property(name: String, op: String, value: Value, needsValue: Bool)
304        case not(Term)
305    }
306
307    enum Value: Sendable {
308        case regex(String)
309        case string(String)
310        case time(String)
311        case number(Double)
312    }
313
314    /// Alternatives of conjunctions; nil matches everything.
315    let tags: [[Term]]?
316    let todo: [[(regex: Bool, keyword: String, negated: Bool)]]?
317    let todoOnly: Bool
318
319    static let term = try! NSRegularExpression(pattern:
320        "^&?([-+:])?(\\{[^}]+\\}|(?:((?:[\\p{L}\\p{N}_]|\\\\[^\\s])+)([<=>]=?|[!/]=|<>)(\\*)?(\\{[^}]+\\}|\"[^\"]*\"|-?[.0-9]+(?:[eE][-+]?[0-9]+)?))|[\\p{L}\\p{N}_@#%]+)"
321    )
322    static let timeValue = try! NSRegularExpression(pattern: "^\"[\\[<](?:[0-9]+|now|today|tomorrow|[+-][0-9]+[dmwy]).*[\\]>]\"$")
323
324    public init(_ match: String, todoOnly: Bool = false) {
325        var only = todoOnly
326        var tagsPart = match
327        var todoPart: String?
328        let ns = match as NSString
329        let slashes = Self.slashesRegex
330        if let last = slashes.matches(in: match, range: NSRange(location: 0, length: ns.length)).last,
331           !ns.substring(from: last.range.location).contains("\"") {
332            tagsPart = ns.substring(to: last.range.location)
333            var rest = ns.substring(from: NSMaxRange(last.range))
334            if rest.hasPrefix("!") {
335                only = true
336                rest.removeFirst()
337            }
338            todoPart = rest.trimmingCharacters(in: .whitespaces).isEmpty ? nil : rest
339        }
340        self.todoOnly = only
341
342        func terms(_ s: String) -> [(sign: String?, match: NSTextCheckingResult, text: NSString)] {
343            var result: [(String?, NSTextCheckingResult, NSString)] = []
344            var rest = s
345            while let m = Self.term.firstMatch(in: rest, range: NSRange(location: 0, length: (rest as NSString).length)) {
346                let text = rest as NSString
347                let sign = m.range(at: 1).location != NSNotFound ? text.substring(with: m.range(at: 1)) : nil
348                result.append((sign, m, text))
349                rest = text.substring(from: NSMaxRange(m.range))
350                if m.range.length == 0 { break }
351            }
352            return result
353        }
354
355        if tagsPart.contains(where: { !$0.isWhitespace }) {
356            var alternatives: [[Term]] = []
357            let parts = Self.split(tagsPart)
358            var i = 0
359            while i < parts.count {
360                var part = parts[i]
361                // A `\|` inside a term is not a separator.
362                while part.hasSuffix("\\"), i + 1 < parts.count {
363                    i += 1
364                    part += "|" + parts[i]
365                }
366                var conjunction: [Term] = []
367                for (sign, m, text) in terms(part) {
368                    let whole = text.substring(with: m.range(at: 2))
369                    var term: Term
370                    if whole.hasPrefix("{") {
371                        term = .tagRegex(String(whole.dropFirst().dropLast()))
372                    } else if m.range(at: 3).location != NSNotFound {
373                        let name = text.substring(with: m.range(at: 3))
374                            .replacingOccurrences(of: "\\\\(.)", with: "$1", options: .regularExpression).uppercased()
375                        let raw = text.substring(with: m.range(at: 6))
376                        let value: Value
377                        if raw.hasPrefix("{") {
378                            value = .regex(String(raw.dropFirst().dropLast()))
379                        } else if raw.hasPrefix("\"") {
380                            let inner = String(raw.dropFirst().dropLast())
381                            let isTime = Self.timeValue.firstMatch(in: raw, range: NSRange(location: 0, length: (raw as NSString).length)) != nil
382                            value = isTime ? .time(inner) : .string(inner)
383                        } else {
384                            value = .number(Self.number(raw))
385                        }
386                        term = .property(name: name, op: text.substring(with: m.range(at: 4)), value: value, needsValue: m.range(at: 5).location != NSNotFound)
387                    } else {
388                        term = .tag(whole)
389                    }
390                    if sign == "-" { term = .not(term) }
391                    conjunction.append(term)
392                }
393                alternatives.append(conjunction)
394                i += 1
395            }
396            tags = alternatives
397        } else {
398            tags = nil
399        }
400
401        if let todoPart {
402            todo = Self.split(todoPart).map { part in
403                terms(part).map { sign, m, text in
404                    let keyword = text.substring(with: m.range(at: 2))
405                    return keyword.hasPrefix("{")
406                        ? (true, String(keyword.dropFirst().dropLast()), sign == "-")
407                        : (false, keyword, sign == "-")
408                }
409            }
410        } else {
411            todo = nil
412        }
413    }
414
415    /// `org-split-string` on `|`: empty strings between separators stay.
416    static func split(_ s: String) -> [String] {
417        var parts = s.components(separatedBy: "|")
418        if parts.first == "" { parts.removeFirst() }
419        if parts.last == "", !parts.isEmpty { parts.removeLast() }
420        return parts.isEmpty ? [""] : parts
421    }
422
423    /// `string-to-number`: the leading number, or 0.
424    static func number(_ s: String) -> Double {
425        let trimmed = s.drop { $0 == " " || $0 == "\t" }
426        guard let r = trimmed.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return 0 }
427        return Double(trimmed[r]) ?? 0
428    }
429
430    func matches(_ heading: AgendaSource.Heading, in source: AgendaSource, now: Date, calendar: Calendar) -> Bool {
431        let todoKeyword = heading.todo
432        if todoOnly {
433            guard let todoKeyword, !heading.isDone else { return false }
434            _ = todoKeyword
435        }
436        let tagList = heading.tags.map(\.name)
437        func value(_ name: String) -> String? {
438            switch name {
439            case "LEVEL": return String(heading.level)
440            case "CATEGORY": return heading.category
441            case "TODO": return heading.todo
442            case "ITEM": return heading.title
443            case "PRIORITY": return heading.priority ?? source.priorities.default
444            case "FILE": return source.path
445            case "TAGS": return heading.localTags.isEmpty ? nil : ":" + heading.localTags.joined(separator: ":") + ":"
446            case "ALLTAGS": return tagList.isEmpty ? nil : ":" + tagList.joined(separator: ":") + ":"
447            case "SCHEDULED", "DEADLINE", "CLOSED": return heading.planning[name]
448            case "TIMESTAMP": return heading.firstActive
449            case "TIMESTAMP_IA": return heading.firstInactive
450            default: return heading.matchProperties[name]
451            }
452        }
453        func evaluate(_ term: Term) -> Bool {
454            switch term {
455            case .not(let inner):
456                return !evaluate(inner)
457            case .tag(let tag):
458                return tagList.contains(tag)
459            case .tagRegex(let pattern):
460                return tagList.contains { EmacsRegex.matches(pattern, $0) }
461            case .property(let name, let op, let expected, let needsValue):
462                let found = value(name)
463                if needsValue, found == nil { return false }
464                let actual = found ?? ""
465                switch expected {
466                case .regex(let pattern):
467                    let hit = EmacsRegex.matches(pattern, actual)
468                    return op == "/=" ? !hit : hit
469                case .string(let string):
470                    return Self.compare(op, actual, string)
471                case .number(let number):
472                    return Self.compare(op, Self.number(actual), number)
473                case .time(let time):
474                    let a = Self.seconds(actual, now: now, calendar: calendar)
475                    let b = Self.matcherTime(time, now: now, calendar: calendar)
476                    guard a > 0, b > 0 else { return false }
477                    // `org-time<>` in Org 9.8.7 (org-macs.el) is `(\= a b)`, which reads as `=`:
478                    // `DEADLINE<>"<2026-10-07>"` keeps the entries due that day.
479                    // AgendaTests.listsMatchEmacs checks this against Emacs.
480                    return op == "<>" || op == "!=" || op == "/=" ? a == b : Self.compare(op, a, b)
481                }
482            }
483        }
484        if let tags, !tags.contains(where: { $0.allSatisfy(evaluate) }) { return false }
485        if let todo {
486            let ok = todo.contains { conjunction in
487                conjunction.allSatisfy { term in
488                    let hit = term.regex
489                        ? todoKeyword.map { EmacsRegex.matches(term.keyword, $0) } ?? false
490                        : todoKeyword == term.keyword
491                    return term.negated ? !hit : hit
492                }
493            }
494            if !ok { return false }
495        }
496        return true
497    }
498
499    static func compare<T: Comparable>(_ op: String, _ a: T, _ b: T) -> Bool {
500        switch op {
501        case "<": a < b
502        case ">": a > b
503        case "<=", "=<": a <= b
504        case ">=", "=>": a >= b
505        case "=", "==": a == b
506        default: a != b
507        }
508    }
509
510    /// `org-2ft`: a timestamp string as seconds, or 0.
511    static func seconds(_ s: String, now: Date, calendar: Calendar) -> Double {
512        let ns = s as NSString
513        guard let m = Days.dateRegex.firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) else { return 0 }
514        var c = DateComponents(year: Int(ns.substring(with: m.range(at: 1))), month: Int(ns.substring(with: m.range(at: 2))), day: Int(ns.substring(with: m.range(at: 3))))
515        let hour = Days.hour(of: s)
516        c.hour = hour
517        if let time = try? NSRegularExpression(pattern: " ([0-9]{1,2}):([0-9]{2})").firstMatch(in: s, range: NSRange(location: NSMaxRange(m.range), length: ns.length - NSMaxRange(m.range))), Int(ns.substring(with: time.range(at: 1))) == hour {
518            c.minute = Int(ns.substring(with: time.range(at: 2)))
519        }
520        return calendar.date(from: c)?.timeIntervalSince1970 ?? 0
521    }
522
523    /// `org-matcher-time`.
524    static func matcherTime(_ s: String, now: Date, calendar: Calendar) -> Double {
525        let today = calendar.startOfDay(for: now).timeIntervalSince1970
526        switch s {
527        case "<now>": return now.timeIntervalSince1970
528        case "<today>": return today
529        case "<tomorrow>": return today + 86400
530        case "<yesterday>": return today - 86400
531        default: break
532        }
533        let ns = s as NSString
534        if let m = try! NSRegularExpression(pattern: "^<([-+][0-9]+)([hdwmy])>$").firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) {
535            let n = Double(ns.substring(with: m.range(at: 1)))!
536            let unit = ns.substring(with: m.range(at: 2))
537            let size: Double = ["h": 3600, "d": 86400, "w": 604800, "m": 2678400, "y": 31557600][unit]!
538            return (unit == "h" ? now.timeIntervalSince1970 : today) + n * size
539        }
540        return seconds(s, now: now, calendar: calendar)
541    }
542}
543
544/// Emacs regular expressions run through ICU, case-insensitively as the matcher binds
545/// `case-fold-search`.
546enum EmacsRegex {
547    /// Characters without word syntax in an Org buffer under Emacs 31, as ranges: everything
548    /// else, `$`, `%` and `'` included, is a word character. Emacs also puts a word boundary
549    /// where the script changes, which this doesn't.
550    static let nonWord = ""
551        + "\\x{0}-\\x{23}\\x{26}\\x{28}-\\x{2f}\\x{3a}-\\x{40}\\x{5b}-\\x{60}\\x{7b}-\\x{7f}\\x{a0}-\\x{a4}"
552        + "\\x{a6}-\\x{b1}\\x{b4}\\x{b6}\\x{b8}\\x{ba}-\\x{bf}\\x{d7}\\x{f7}\\x{2c7}\\x{2c9}\\x{2d0}"
553        + "\\x{2d8}-\\x{2db}\\x{2dd}\\x{384}-\\x{385}\\x{5be}\\x{5c0}\\x{5c3}\\x{5c6}\\x{e2f}\\x{e3f}\\x{e46}"
554        + "\\x{e4f}\\x{e5a}-\\x{e5b}\\x{eaf}\\x{ec6}\\x{f00}-\\x{f0b}\\x{f0d}-\\x{f18}\\x{f1a}-\\x{f1f}\\x{f34}"
555        + "\\x{f36}\\x{f38}-\\x{f3f}\\x{f7f}\\x{f85}\\x{fbe}-\\x{fcf}\\x{1361}-\\x{1368}\\x{1800}-\\x{180a}"
556        + "\\x{2000}-\\x{2026}\\x{202f}-\\x{205f}\\x{207d}-\\x{207e}\\x{208d}-\\x{208e}\\x{20ac}\\x{2103}"
557        + "\\x{2109}\\x{2116}\\x{2121}-\\x{2122}\\x{2153}-\\x{2154}\\x{215b}-\\x{215e}\\x{2190}-\\x{244f}"
558        + "\\x{2460}-\\x{246e}\\x{2474}-\\x{24b5}\\x{2500}-\\x{254b}\\x{2592}\\x{25a0}-\\x{25a1}"
559        + "\\x{25a3}-\\x{25a9}\\x{25b2}-\\x{25b3}\\x{25b6}-\\x{25b7}\\x{25bc}-\\x{25bd}\\x{25c0}-\\x{25c1}"
560        + "\\x{25c6}-\\x{25c8}\\x{25cb}\\x{25ce}-\\x{25d1}\\x{25ef}\\x{2605}-\\x{2606}\\x{260e}-\\x{260f}"
561        + "\\x{261c}\\x{261e}\\x{2640}\\x{2642}\\x{2660}-\\x{2661}\\x{2663}-\\x{2665}\\x{2667}-\\x{266a}"
562        + "\\x{266c}-\\x{266d}\\x{266f}\\x{2768}-\\x{276d}\\x{2770}-\\x{2775}\\x{27e6}-\\x{27eb}"
563        + "\\x{2983}-\\x{2998}\\x{29fc}-\\x{29fd}\\x{2a00}-\\x{2bff}\\x{2e00}-\\x{2e7f}\\x{3000}-\\x{3003}"
564        + "\\x{3008}-\\x{301c}\\x{30fb}\\x{3200}-\\x{321c}\\x{3220}-\\x{3229}\\x{3260}-\\x{327b}"
565        + "\\x{327e}-\\x{327f}\\x{3380}-\\x{3384}\\x{3388}-\\x{33ca}\\x{33cf}-\\x{33d0}\\x{33d3}\\x{33d6}"
566        + "\\x{33d8}\\x{33db}-\\x{33dd}\\x{aadb}-\\x{aadf}\\x{fd3e}-\\x{fd3f}\\x{fe35}-\\x{fe44}"
567        + "\\x{fe59}-\\x{fe5e}\\x{ff01}-\\x{ff0f}\\x{ff1b}-\\x{ff20}\\x{ff3b}-\\x{ff40}\\x{ff5b}-\\x{ff65}"
568        + "\\x{ffe0}-\\x{ffe3}\\x{ffe5}\\x{11660}-\\x{1166c}\\x{1fb00}-\\x{1fbff}"
569    /// `search` uses `org-search-view`'s syntax table, where `'` is punctuation.
570    static func translate(_ pattern: String, search: Bool = false) -> String {
571        let nonWord = search ? Self.nonWord + "'" : Self.nonWord
572        let word = "[^" + nonWord + "]"
573        var out = ""
574        var chars = Array(pattern)
575        var i = 0
576        var inClass = false
577        while i < chars.count {
578            let c = chars[i]
579            if inClass {
580                if c == "]" { inClass = false }
581                if c == "[" , i + 1 < chars.count, chars[i + 1] == ":" {
582                    // `[:alpha:]` passes through.
583                    if let end = String(chars[i...]).range(of: ":]") {
584                        let length = String(chars[i...]).distance(from: String(chars[i...]).startIndex, to: end.upperBound)
585                        out += String(chars[i..<(i + length)])
586                        i += length
587                        continue
588                    }
589                }
590                out += c == "\\" ? "\\\\" : String(c)
591                i += 1
592                continue
593            }
594            if c == "\\", i + 1 < chars.count {
595                let n = chars[i + 1]
596                switch n {
597                case "(":
598                    if i + 3 < chars.count, chars[i + 2] == "?", chars[i + 3] == ":" {
599                        out += "(?:"
600                        i += 4
601                        continue
602                    }
603                    out += "("
604                case ")": out += ")"
605                case "|": out += "|"
606                case "{": out += "{"
607                case "}": out += "}"
608                case "s" where i + 2 < chars.count && chars[i + 2] == "-",
609                     "S" where i + 2 < chars.count && chars[i + 2] == "-":
610                    // Whitespace syntax in Org buffers.
611                    out += n == "s" ? "[\\t\\n\\f\\r \\u00a0]" : "[^\\t\\n\\f\\r \\u00a0]"
612                    i += 3
613                    continue
614                case "<": out += "(?<!\(word))(?=\(word))"
615                case ">": out += "(?<=\(word))(?!\(word))"
616                case "b": out += "(?:(?<!\(word))(?=\(word))|(?<=\(word))(?!\(word)))"
617                case "B": out += "(?:(?<=\(word))(?=\(word))|(?<!\(word))(?!\(word)))"
618                case "`": out += "^"
619                case "'": out += "$"
620                case "w": out += word
621                case "W": out += "[" + nonWord + "]"
622                default: out += "\\" + String(n)
623                }
624                i += 2
625                continue
626            }
627            switch c {
628            case "(", ")", "|", "{", "}": out += "\\" + String(c)
629            case "[":
630                inClass = true
631                out += "["
632                if i + 1 < chars.count, chars[i + 1] == "^" { out += "^"; i += 1 }
633                if i + 1 < chars.count, chars[i + 1] == "]" { out += "\\]"; i += 1 }
634            default: out += String(c)
635            }
636            i += 1
637        }
638        chars = []
639        return out
640    }
641
642    static func matches(_ pattern: String, _ string: String) -> Bool {
643        guard let regex = try? NSRegularExpression(pattern: translate(pattern), options: .caseInsensitive) else { return false }
644        return regex.firstMatch(in: string, range: NSRange(location: 0, length: (string as NSString).length)) != nil
645    }
646}