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