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