Sources/OrgCore/Agenda/AgendaSearch.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgCore/Agenda/AgendaSearch.swift history · blame · raw

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