Sources/OrgCore/Agenda/AgendaSearch.swift

193155dbb22e3eff765a4ab8ea491811d4b51858
orgstar/Sources/OrgCore/Agenda/AgendaSearch.swift

646 lines · 33657 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                var item = 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                (item.tsDate, item.tsType) = AgendaSort.entryTimestamp(heading, strategy: options.strategy("todo"))
 24                item.tsType = "todo" + item.tsType
 25                items.append(item)
 26            }
 27        }
 28        return AgendaSort.sort(markBlocked(items, options: options), view: "todo", options: options)
 29    }
 30
 31    /// `org-tags-view`: entries matching a tags/property/TODO match string. `todoOnly` keeps
 32    /// unfinished TODO entries, as `M` does.
 33    public static func tagsMatch(
 34        _ sources: [AgendaSource], match: String, todoOnly: Bool = false, now: Date = Date(), calendar: Calendar = .current,
 35        options: AgendaOptions = AgendaOptions(), skip: ((AgendaSource, Int) -> Bool)? = nil
 36    ) -> [AgendaItem] {
 37        let matcher = TagsMatcher(match, todoOnly: todoOnly)
 38        let today = Days.absolute(now, calendar: calendar)
 39        var items: [AgendaItem] = []
 40        for source in sources {
 41            for (index, heading) in source.headings.enumerated() {
 42                if matcher.todoOnly, heading.todo == nil { continue }
 43                guard matcher.matches(heading, in: source, now: now, calendar: calendar), !heading.skipped else { continue }
 44                if let skip, skip(source, index) { continue }
 45                if matcher.todoOnly, options.tagsTodoHonorIgnoreOptions, ignoresTodo(source, index, options: options, today: today) { continue }
 46                var item = format(
 47                    source, heading, kind: .tagsMatch, marker: heading.start, extra: "", dotime: nil, removing: nil,
 48                    trailing: "", prefix: options.prefix("tags"), urgency: { $0 }
 49                )
 50                (item.tsDate, item.tsType) = AgendaSort.entryTimestamp(heading, strategy: options.strategy("tags"))
 51                item.tsType = "tagsmatch" + item.tsType
 52                items.append(item)
 53            }
 54        }
 55        return AgendaSort.sort(markBlocked(items, options: options), view: "tags", options: options)
 56    }
 57
 58    /// `org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item` for the entry of heading
 59    /// `index`, from its heading line to the next heading. The searches go on from where the
 60    /// last one matched, as Org's do.
 61    static func ignoresTodo(_ source: AgendaSource, _ index: Int, options: AgendaOptions, today: Int) -> Bool {
 62        guard options.todoIgnoreWithDate || options.todoIgnoreScheduled != .off || options.todoIgnoreDeadlines != .off
 63            || options.todoIgnoreTimestamp != .off else { return false }
 64        let ns = source.text as NSString
 65        let start = source.headings[index].start
 66        let end = index + 1 < source.headings.count ? source.headings[index + 1].start : ns.length
 67        var point = start
 68        func search(_ regex: NSRegularExpression) -> String? {
 69            guard let m = regex.firstMatch(in: source.text, range: NSRange(location: point, length: end - point)) else { return nil }
 70            point = NSMaxRange(m.range)
 71            return ns.substring(with: m.range(at: 1))
 72        }
 73        func days(_ stamp: String) -> Int { (Days.absolute(of: stamp) ?? today) - today }
 74        func custom(_ stamp: String, _ n: Int) -> Bool { n >= 0 ? days(stamp) >= n : days(stamp) <= n }
 75        if options.todoIgnoreWithDate, search(Self.activeStampRegex) != nil { return true }
 76        if options.todoIgnoreScheduled != .off, let stamp = search(Self.scheduledRegex) {
 77            switch options.todoIgnoreScheduled {
 78            case .future: if days(stamp) > 0 { return true }
 79            case .past: if days(stamp) <= 0 { return true }
 80            case .days(let n): if custom(stamp, n) { return true }
 81            default: return true
 82            }
 83        }
 84        if options.todoIgnoreDeadlines != .off, let stamp = search(Self.deadlineRegex) {
 85            let close = days(stamp) <= Days.warningDays(stamp, delay: false, defaultDays: options.deadlineWarningDays) && !source.headings[index].isDone
 86            switch options.todoIgnoreDeadlines {
 87            case .all: return true
 88            case .far: if !close { return true }
 89            case .future: if days(stamp) > 0 { return true }
 90            case .past: if days(stamp) <= 0 { return true }
 91            case .days(let n): if custom(stamp, n) { return true }
 92            default: if close { return true }
 93            }
 94        }
 95        if options.todoIgnoreTimestamp != .off {
 96            // The other timestamps, without SCHEDULED and DEADLINE ones.
 97            let rest = Self.planningStampRegex.stringByReplacingMatches(in: ns.substring(with: NSRange(location: point, length: end - point)), range: NSRange(location: 0, length: end - point), withTemplate: "")
 98            guard let m = Self.activeStampRegex.firstMatch(in: rest, range: NSRange(location: 0, length: (rest as NSString).length)) else { return false }
 99            let stamp = (rest as NSString).substring(with: m.range(at: 1))
100            switch options.todoIgnoreTimestamp {
101            case .future: return days(stamp) > 0
102            case .past: return days(stamp) <= 0
103            case .days(let n): return custom(stamp, n)
104            default: return true
105            }
106        }
107        return false
108    }
109
110    /// `org-ts-regexp`, `org-scheduled-time-regexp` and `org-deadline-time-regexp`.
111    static let activeStampRegex = try! NSRegularExpression(pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?)>")
112    static let scheduledRegex = try! NSRegularExpression(pattern: "\\bSCHEDULED: *<([^>]+)>")
113    static let deadlineRegex = try! NSRegularExpression(pattern: "\\bDEADLINE: *<([^>]+)>")
114    static let planningStampRegex = try! NSRegularExpression(pattern: "\\bSCHEDULED: *<[^>]+>|\\bDEADLINE: *<[^>]+>")
115
116    /// `org-search-view`: entries, heading and body, containing `string` as a phrase, or with
117    /// a leading `+`, `-` or `{` (or `searchAlwaysBoolean`) matching each of its snippets. A
118    /// leading `*` searches headlines only, `!` keeps unfinished TODO entries as `todoOnly`
119    /// does, and `:` matches whole words. Text before the first heading is not searched.
120    public static func textSearch(_ sources: [AgendaSource], string: String, todoOnly: Bool = false, options: AgendaOptions = AgendaOptions()) -> [AgendaItem] {
121        let query = SearchQuery(string, todoOnly: todoOnly, options: options)
122        // Org searches for the longest positive snippet, then checks the entry it is in.
123        var positive = query.positive
124        let first = positive.isEmpty ? nil : positive.removeFirst()
125        let patterns = positive.compactMap(\.regex)
126        let negative = query.negative.compactMap(\.regex)
127        guard let search = SearchQuery.compile(first.map { (query.headlinesOnly ? "^\\*+ .*?" : "") + $0.emacs } ?? "^\\*+ "),
128              patterns.count == positive.count, negative.count == query.negative.count else { return [] }
129        let headingLine = try! NSRegularExpression(pattern: "^\\*+ ", options: .anchorsMatchLines)
130        var items: [AgendaItem] = []
131        for source in sources {
132            let text = source.text
133            let ns = text as NSString
134            let length = ns.length
135            let starts = headingLine.matches(in: text, range: NSRange(location: 0, length: length)).map(\.range.location)
136            guard let firstHeading = starts.first else { continue }
137            let byStart = Dictionary(source.headings.map { ($0.start, $0) }, uniquingKeysWith: { a, _ in a })
138            var required = patterns
139            if query.todoOnly {
140                guard !source.notDoneKeywords.isEmpty else { continue }
141                let keywords = source.notDoneKeywords.map(SearchQuery.quote).joined(separator: "\\|")
142                required.insert(SearchQuery.compile("^\\*+[ \\t]+\\(" + keywords + "\\)")!, at: 0)
143            }
144            func lineStart(_ at: Int) -> Int {
145                let newline = ns.range(of: "\n", options: .backwards, range: NSRange(location: 0, length: at))
146                return newline.location == NSNotFound ? 0 : newline.location + 1
147            }
148            var at = max(0, firstHeading - 1)
149            while at <= length, let m = search.firstMatch(in: text, options: [.withoutAnchoringBounds, .withTransparentBounds], range: NSRange(location: at, length: length - at)) {
150                let matchEnd = NSMaxRange(m.range)
151                // `org-back-to-heading`, then `outline-next-heading`.
152                guard let index = starts.lastIndex(where: { $0 <= lineStart(matchEnd) }) else { break }
153                let beg = starts[index]
154                let end = index + 1 < starts.count ? starts[index + 1] : length
155                let next = max(end - 1, at + 1)
156                guard let entry = byStart[beg] else {
157                    at = next
158                    continue
159                }
160                if entry.skipped {
161                    // `org-agenda-skip` leaves point at the end of the subtree, before blank lines.
162                    var stop = starts[(index + 1)...].first { byStart[$0].map { $0.level <= entry.level } ?? false } ?? length
163                    if stop > 0, [10, 13].contains(ns.character(at: stop - 1)) {
164                        stop -= 1
165                        while stop > beg, [9, 10, 13, 32].contains(ns.character(at: stop - 1)) { stop -= 1 }
166                    }
167                    at = max(stop, at + 1)
168                    continue
169                }
170                let lineEnd = ns.range(of: "\n", range: NSRange(location: beg, length: length - beg)).location
171                let stop = query.headlinesOnly && lineEnd != NSNotFound ? lineEnd : end
172                let entryText = ns.substring(with: NSRange(location: beg, length: stop - beg))
173                func found(_ regex: NSRegularExpression) -> Bool {
174                    regex.firstMatch(in: entryText, range: NSRange(location: 0, length: (entryText as NSString).length)) != nil
175                }
176                if !negative.contains(where: found), required.allSatisfy(found) {
177                    items.append(format(
178                        source, entry, kind: .search, marker: beg, extra: "", dotime: .headline, removing: nil,
179                        trailing: "", prefix: options.prefix("search"), urgency: { _ in 1000 }
180                    ))
181                    at = max(next, matchEnd)
182                } else {
183                    at = next
184                }
185            }
186        }
187        return AgendaSort.sort(items, view: "search", options: options)
188    }
189
190    /// An `org-search-view` string read into regexps, in Emacs syntax and compiled.
191    struct SearchQuery {
192        struct Pattern {
193            let emacs: String
194            let regex: NSRegularExpression?
195        }
196
197        let headlinesOnly: Bool
198        let todoOnly: Bool
199        let boolean: Bool
200        /// Longest first, as Org sorts them.
201        let positive: [Pattern]
202        let negative: [Pattern]
203
204        init(_ string: String, todoOnly: Bool, options: AgendaOptions) {
205            var words = Substring(string)
206            headlinesOnly = words.first == "*"
207            if headlinesOnly { words.removeFirst() }
208            var todo = todoOnly
209            if words.first == "!" {
210                todo = true
211                words.removeFirst()
212            }
213            self.todoOnly = todo
214            var fullWords = options.searchForceFullWords
215            if words.first == ":" {
216                fullWords = true
217                words.removeFirst()
218            }
219            boolean = options.searchAlwaysBoolean || ["-", "+", "{"].contains(words.first)
220
221            // `split-string`, then words ending in `\` joined to the next, and `{…}` kept whole.
222            var pending = words.split(whereSeparator: { " \u{0C}\t\n\r\u{0B}".contains($0) }).map(String.init)
223            var joined: [String] = []
224            while !pending.isEmpty {
225                var w = pending.removeFirst()
226                while w.hasSuffix("\\"), !pending.isEmpty { w = String(w.dropLast()) + " " + pending.removeFirst() }
227                joined.append(w)
228            }
229            pending = joined
230            joined = []
231            while !pending.isEmpty {
232                var w = pending.removeFirst()
233                if w.range(of: "^[-+]?\\{", options: .regularExpression) != nil, !w.hasSuffix("}") {
234                    while let next = pending.first, !next.hasSuffix("}") { w += " " + pending.removeFirst() }
235                    w += " " + (pending.isEmpty ? "" : pending.removeFirst())
236                }
237                joined.append(w)
238            }
239            if boolean {
240                pending = joined
241                joined = []
242                while !pending.isEmpty {
243                    var w = pending.removeFirst()
244                    let chars = Array(w)
245                    if chars[0] == "\"" || (chars.count > 1 && "+-".contains(chars[0]) && chars[1] == "\"") {
246                        while !pending.isEmpty, !w.hasSuffix("\"") { w += " " + pending.removeFirst() }
247                    }
248                    w = w.replacingOccurrences(of: "^([-+]?)\"", with: "$1", options: .regularExpression)
249                    if w.hasSuffix("\"") { w.removeLast() }
250                    joined.append(w)
251                }
252            }
253
254            var positive: [String] = []
255            var negative: [String] = []
256            if boolean {
257                for word in joined {
258                    var w = Substring(word)
259                    let negated = w.first == "-"
260                    if negated || w.first == "+" { w = w.dropFirst() }
261                    let re: String
262                    if w.count >= 2, w.first == "{", w.last == "}" {
263                        re = String(w.dropFirst().dropLast())
264                    } else {
265                        re = fullWords ? "\\<" + Self.quote(w.lowercased()) + "\\>" : Self.quote(w.lowercased())
266                    }
267                    if negated { negative.insert(re, at: 0) } else { positive.insert(re, at: 0) }
268                }
269            } else {
270                positive = [joined.map(Self.quote).joined(separator: "\\s-+")]
271            }
272            // `sort` is stable; the snippets were pushed, so the last comes first among equals.
273            self.positive = positive.enumerated().sorted { a, b in
274                a.element.count != b.element.count ? a.element.count > b.element.count : a.offset < b.offset
275            }.map { Pattern(emacs: $0.element, regex: Self.compile($0.element)) }
276            self.negative = negative.map { Pattern(emacs: $0, regex: Self.compile($0)) }
277        }
278
279        /// `regexp-quote`.
280        static func quote(_ s: String) -> String {
281            var out = ""
282            for c in s {
283                if "[*.\\?+^$".contains(c) { out.append("\\") }
284                out.append(c)
285            }
286            return out
287        }
288
289        /// Case-insensitive, as Org binds `case-fold-search`, with `^` and `$` at each line.
290        static func compile(_ emacs: String) -> NSRegularExpression? {
291            try? NSRegularExpression(pattern: EmacsRegex.translate(emacs, search: true), options: [.caseInsensitive, .anchorsMatchLines])
292        }
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}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form