Sources/OrgCore/Keymap/ISearch.swift
168 lines · 8251 bytes
1import Foundation
2
3/// Incremental search (isearch.el, Emacs 31.1) with its defaults: `isearch-lax-whitespace`
4/// with `search-whitespace-regexp` `[ \t]+`, `search-upper-case` `not-yanks` (an upper-case
5/// letter makes the search case-sensitive) and `isearch-wrap-pause` `t`. The editor feeds it
6/// keys; it says where point and the match are and what the echo area shows.
7public struct ISearch: Sendable, Equatable {
8 public struct State: Sendable, Equatable {
9 public var string: String
10 public var forward: Bool
11 /// Point: the match's end going forward, its start going back.
12 public var point: Int
13 public var match: Range<Int>?
14 public var failing: Bool
15 public var wrapped: Bool
16 /// Wrapped and gone past where the search began.
17 public var overwrapped: Bool
18 }
19
20 /// Where the search began, to go back to on C-g.
21 public let origin: Int
22 public private(set) var state: State
23 /// The states before, for DEL (`isearch-cmds`).
24 private var history: [State] = []
25 /// What a repeat with nothing typed searches for: the previous search.
26 public let previous: String?
27 /// `isearch-forward-regexp`: the string is an ICU regular expression.
28 public let regexp: Bool
29 /// `isearch-barrier`: a backward match may not end past it; where the search began, or
30 /// where it last changed direction.
31 private var barrier: Int
32
33 public init(origin: Int, forward: Bool, previous: String? = nil, regexp: Bool = false) {
34 self.origin = origin
35 self.previous = previous
36 self.regexp = regexp
37 barrier = origin
38 state = State(string: "", forward: forward, point: origin, match: nil, failing: false, wrapped: false, overwrapped: false)
39 }
40
41 public var string: String { state.string }
42 public var point: Int { state.point }
43 public var match: Range<Int>? { state.failing ? nil : state.match }
44
45 /// `isearch-message-prefix`.
46 public var message: String {
47 var prefix = ""
48 if state.failing { prefix += "Failing " }
49 if state.overwrapped { prefix += "overwrapped " } else if state.wrapped { prefix += "wrapped " }
50 prefix += regexp ? "regexp I-search" : "I-search"
51 if !state.forward { prefix += " backward" }
52 prefix = prefix.prefix(1).uppercased() + prefix.dropFirst()
53 return prefix + ": " + state.string
54 }
55
56 /// The search string as a regular expression: spaces match runs of spaces and tabs; with
57 /// `regexp`, as it is. An invalid one is nil, and fails.
58 public static func pattern(_ string: String, regexp: Bool = false) -> NSRegularExpression? {
59 if regexp { return try? NSRegularExpression(pattern: string, options: string.contains { $0.isUppercase } ? [] : [.caseInsensitive]) }
60 let parts = string.split(separator: " ", omittingEmptySubsequences: false).map { NSRegularExpression.escapedPattern(for: String($0)) }
61 let caseSensitive = string.contains { $0.isUppercase }
62 return try? NSRegularExpression(pattern: parts.joined(separator: "[ \\t]+"), options: caseSensitive ? [] : [.caseInsensitive])
63 }
64
65 /// The first match starting at or after `from` going forward; going back, the last one
66 /// ending at or before `from`.
67 static func find(_ string: String, in text: String, from: Int, forward: Bool, regexp: Bool = false) -> Range<Int>? {
68 guard !string.isEmpty, let regex = pattern(string, regexp: regexp) else { return nil }
69 let length = (text as NSString).length
70 if forward {
71 guard from <= length, let m = regex.firstMatch(in: text, range: NSRange(location: from, length: length - from)) else { return nil }
72 return m.range.location..<NSMaxRange(m.range)
73 }
74 // `re-search-backward`: the match starting nearest before `from`, ending by it.
75 var start = min(from, length)
76 while start >= 0 {
77 if let m = regex.firstMatch(in: text, options: .anchored, range: NSRange(location: start, length: min(from, length) - start)), m.range.length > 0 {
78 return m.range.location..<NSMaxRange(m.range)
79 }
80 start -= 1
81 }
82 return nil
83 }
84
85 private mutating func found(_ range: Range<Int>?) {
86 if let range {
87 state.match = range
88 state.point = state.forward ? range.upperBound : range.lowerBound
89 state.failing = false
90 if state.wrapped, state.forward ? range.lowerBound >= origin : range.upperBound <= origin { state.overwrapped = true }
91 } else {
92 state.failing = true
93 }
94 }
95
96 /// A character typed: the search goes on with it, from the current match's start (its end
97 /// going back), so the match grows in place when it can.
98 public mutating func add(_ characters: String, in text: String) {
99 history.append(state)
100 state.string += characters
101 if state.failing { return }
102 if state.forward {
103 found(Self.find(state.string, in: text, from: state.match?.lowerBound ?? state.point, forward: true, regexp: regexp))
104 } else {
105 // `looking-at` at point first, as long as the match ends by the origin; otherwise
106 // back from just past the current match's end.
107 let start = state.point
108 let limit = min(origin, barrier)
109 if let regex = Self.pattern(state.string, regexp: regexp), start <= (text as NSString).length,
110 let m = regex.firstMatch(in: text, options: .anchored, range: NSRange(location: start, length: (text as NSString).length - start)), m.range.length > 0,
111 NSMaxRange(m.range) <= limit {
112 found(m.range.location..<NSMaxRange(m.range))
113 } else {
114 let from = state.match.map { min(limit, $0.upperBound + 1) } ?? state.point
115 found(Self.find(state.string, in: text, from: from, forward: false, regexp: regexp))
116 }
117 }
118 }
119
120 /// C-s and C-r (`isearch-repeat`): the next match, the previous search when nothing is
121 /// typed yet, the other end of the match when the direction changes, and the other end of
122 /// the buffer after a failing search.
123 public mutating func again(forward: Bool, in text: String) {
124 history.append(state)
125 if state.string.isEmpty {
126 state.forward = forward
127 guard let previous, !previous.isEmpty else { return }
128 state.string = previous
129 found(Self.find(previous, in: text, from: state.point, forward: forward, regexp: regexp))
130 return
131 }
132 if forward != state.forward {
133 state.forward = forward
134 barrier = state.point
135 guard let match = state.match else { return }
136 found(Self.find(state.string, in: text, from: forward ? match.lowerBound : match.upperBound, forward: forward, regexp: regexp))
137 return
138 }
139 if state.failing {
140 state.wrapped = true
141 found(Self.find(state.string, in: text, from: forward ? 0 : (text as NSString).length, forward: forward, regexp: regexp))
142 return
143 }
144 let from = state.point
145 var next = Self.find(state.string, in: text, from: from, forward: forward, regexp: regexp)
146 // An empty match at point would find itself again.
147 if let range = next, range.isEmpty { next = Self.find(state.string, in: text, from: forward ? from + 1 : from - 1, forward: forward, regexp: regexp) }
148 if next == nil {
149 state.failing = true
150 } else {
151 found(next)
152 }
153 }
154
155 /// DEL (`isearch-delete-char`): back to the state before the last key.
156 public mutating func delete() {
157 guard let last = history.popLast() else { return }
158 state = last
159 }
160
161 /// C-g (`isearch-abort`): with a failing search, the part that fails comes off and the
162 /// search goes on (true); otherwise the search is over, point back where it began (false).
163 public mutating func abort() -> Bool {
164 guard state.failing else { return false }
165 while state.failing, let last = history.popLast() { state = last }
166 return true
167 }
168}