Sources/OrgCore/Commands/FastSelection.swift
244 lines · 10446 bytes
1import Foundation
2
3// Fast TODO and tag selection (`org-fast-todo-selection`, `org-fast-tag-selection`, Org 9.8.7)
4// with `org-use-fast-*-selection` `auto`, `org-fast-tag-selection-single-key` nil and no TODO
5// keywords among the tags. The editor shows the keys; the answer is the keys pressed, which
6// `FastSelection` replays as org does.
7
8/// What a fast selection prompt shows and how its keys act.
9public struct FastSelection: Sendable, Equatable {
10 public enum Item: Sendable, Equatable {
11 case option(key: Character, name: String)
12 /// `{`: the options up to `endGroup` exclude each other (tags).
13 case startGroup
14 case endGroup
15 /// `[`, `]` and `:` of a group tag; shown, without effect on selection.
16 case startTagGroup, endTagGroup, groupTags
17 case newline
18 }
19
20 public let items: [Item]
21 /// Tags: keys toggle until Return. TODO keywords: one key answers.
22 public let multiple: Bool
23 public let current: [String]
24 public let inherited: [String]
25
26 public init(items: [Item], multiple: Bool, current: [String] = [], inherited: [String] = []) {
27 self.items = items
28 self.multiple = multiple
29 self.current = current
30 self.inherited = inherited
31 }
32
33 public var options: [(key: Character, name: String)] {
34 items.compactMap { if case .option(let key, let name) = $0 { (key, name) } else { nil } }
35 }
36
37 /// The `{ }` groups' members.
38 var groups: [[String]] {
39 var groups: [[String]] = []
40 var inGroup = false
41 for item in items {
42 switch item {
43 case .startGroup: groups.append([]); inGroup = true
44 case .endGroup: inGroup = false
45 case .option(_, let name) where inGroup: groups[groups.count - 1].append(name)
46 default: break
47 }
48 }
49 return groups
50 }
51
52 /// A key pressed in a tag selection, or a tag typed after Tab.
53 public enum Input: Sendable, Equatable {
54 case key(Character)
55 case typed(String)
56 }
57
58 /// The answer a prompt sends: keys as themselves, a typed tag between Tab and newline.
59 public static func encode(_ inputs: [Input]) -> String {
60 inputs.map { input in
61 switch input {
62 case .key(let c): String(c)
63 case .typed(let tag): "\t" + tag + "\n"
64 }
65 }.joined()
66 }
67
68 public static func decode(_ answer: String) -> [Input] {
69 var inputs: [Input] = []
70 var rest = Substring(answer)
71 while let c = rest.first {
72 rest = rest.dropFirst()
73 if c == "\t" {
74 let tag = rest.prefix { $0 != "\n" }
75 inputs.append(.typed(String(tag)))
76 rest = rest.dropFirst(tag.count + 1)
77 } else {
78 inputs.append(.key(c))
79 }
80 }
81 return inputs
82 }
83
84 /// The tags after `inputs`, or nil when they quit (`q` with no binding, or C-g).
85 public func tags(after inputs: [Input]) -> [String]? {
86 var current = self.current
87 var groupsOn = true
88 let order = options.map(\.name)
89 for input in inputs {
90 switch input {
91 case .key("!"): groupsOn.toggle()
92 case .key(" "): current = []
93 case .key("\u{7}"): return nil
94 case .key(let c):
95 if let tag = options.first(where: { $0.key == c })?.name {
96 current = Self.toggle(tag, current, groups: groupsOn ? groups : [])
97 } else if c == "q" {
98 return nil
99 }
100 case .typed(let tag):
101 guard tag.contains(where: { !$0.isWhitespace }) else { continue }
102 current = Self.toggle(tag, current, groups: groupsOn ? groups : [])
103 }
104 // Sorted by the table's order; tags not in it keep theirs, after.
105 current = current.enumerated().sorted { a, b in
106 let ia = order.firstIndex(of: a.element) ?? Int.max
107 let ib = order.firstIndex(of: b.element) ?? Int.max
108 return ia != ib ? ia < ib : a.offset < b.offset
109 }.map(\.element)
110 }
111 return current
112 }
113
114 /// `org--add-or-remove-tag`.
115 static func toggle(_ tag: String, _ current: [String], groups: [[String]]) -> [String] {
116 if current.contains(tag) { return current.filter { $0 != tag } }
117 var current = current
118 for group in groups where group.contains(tag) { current.removeAll { group.contains($0) } }
119 return [tag] + current
120 }
121
122 // MARK: - TODO keywords
123
124 /// `org-todo-key-alist` after `org-assign-fast-keys`, when any keyword has a key.
125 static func todo(_ settings: OrgSettings) -> FastSelection? {
126 guard settings.todoSequences.contains(where: { ($0.active + $0.done).contains { $0.fastKey != nil } }) else { return nil }
127 var items: [Item] = []
128 let all = settings.todoSequences.flatMap { $0.active + $0.done }
129 var used = Set(all.compactMap(\.fastKey))
130 var assigned: [Character] = []
131 var alternative = Character("0")
132 for keyword in all {
133 if let key = keyword.fastKey { assigned.append(key); continue }
134 var letters = Array(keyword.name.lowercased())
135 if letters.first == "@" { letters.removeFirst() }
136 let key = letters.first { !used.contains($0) } ?? {
137 while used.contains(alternative) { alternative = Character(UnicodeScalar(alternative.unicodeScalars.first!.value + 1)!) }
138 return alternative
139 }()
140 used.insert(key)
141 assigned.append(key)
142 }
143 var index = 0
144 for sequence in settings.todoSequences {
145 items.append(.startGroup)
146 for keyword in sequence.active + sequence.done {
147 items.append(.option(key: assigned[index], name: keyword.name))
148 index += 1
149 }
150 items.append(.endGroup)
151 }
152 return FastSelection(items: items, multiple: false)
153 }
154
155 /// The keyword for `key`, preferring the sequence of `current`; `.some(nil)` clears it,
156 /// nil quits.
157 func keyword(for key: Character, current: String?) -> String?? {
158 if key == " " { return .some(nil) }
159 var sequences: [[(key: Character, name: String)]] = []
160 for item in items {
161 switch item {
162 case .startGroup: sequences.append([])
163 case .option(let k, let name): sequences[sequences.count - 1].append((k, name))
164 default: break
165 }
166 }
167 if let current, let preferred = sequences.first(where: { $0.contains { $0.name == current } }),
168 let match = preferred.first(where: { $0.key == key }) {
169 return .some(match.name)
170 }
171 return options.first { $0.key == key }.map { .some($0.name) } ?? nil
172 }
173
174 // MARK: - Tags
175
176 /// `org-tag-string-to-alist` of the file's `#+TAGS` lines, or nil without any.
177 static func tagTable(_ text: String) -> [Item]? {
178 let regex = try! NSRegularExpression(pattern: "^[ \\t]*#\\+TAGS:[ \\t]*(.*?)[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
179 let ns = text as NSString
180 let lines = regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { ns.substring(with: $0.range(at: 1)) }
181 guard !lines.isEmpty else { return nil }
182 var items: [Item] = []
183 var names: Set<String> = []
184 var inGroup = false
185 for line in lines.joined(separator: "\n").split(separator: "\n", omittingEmptySubsequences: true) {
186 items.append(.newline)
187 let tokens = line.split(whereSeparator: \.isWhitespace).map(String.init)
188 for (i, token) in tokens.enumerated() {
189 switch token {
190 case "{":
191 items.append(.startGroup)
192 if i + 2 < tokens.count, tokens[i + 2] == ":" { inGroup = true }
193 case "}": items.append(.endGroup); inGroup = false
194 case "[":
195 items.append(.startTagGroup)
196 if i + 2 < tokens.count, tokens[i + 2] == ":" { inGroup = true }
197 case "]": items.append(.endTagGroup); inGroup = false
198 case ":": items.append(.groupTags)
199 default:
200 guard let match = token.firstMatch(of: /^([\p{L}\p{N}_@#%]+|\{.+?\})(?:\((.)\))?$/) else { continue }
201 let name = String(match.1)
202 if inGroup || !names.contains(name) {
203 names.insert(name)
204 items.append(.option(key: match.2.flatMap(\.first) ?? "\0", name: name))
205 }
206 }
207 }
208 }
209 items.removeFirst()
210 return items
211 }
212
213 /// The selection `org-fast-tag-selection` shows for `table` (keys given as `\0` are
214 /// assigned), or nil when no tag in the table has a key.
215 static func tags(table: [Item], current: [String], inherited: [String]) -> FastSelection? {
216 let given = table.compactMap { if case .option(let key, _) = $0, key != "\0" { key } else { nil } }
217 guard !given.isEmpty else { return nil }
218 let pool = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~")
219 var spare = pool[...]
220 var assigned: [Character] = []
221 var items: [Item] = []
222 for item in table {
223 guard case .option(let key, let name) = item else { items.append(item); continue }
224 if key != "\0" {
225 assigned.append(key)
226 items.append(item)
227 continue
228 }
229 var letters = Array(name.lowercased())
230 if letters.first == "@" { letters.removeFirst() }
231 let taken = { (c: Character) in given.contains(c) || assigned.contains(c) }
232 var chosen: Character = " "
233 if let first = letters.first, !taken(first) {
234 chosen = first
235 } else {
236 while let c = spare.first, taken(c) { spare = spare.dropFirst() }
237 chosen = spare.first ?? " "
238 }
239 assigned.append(chosen)
240 items.append(.option(key: chosen, name: name))
241 }
242 return FastSelection(items: items, multiple: true, current: current, inherited: inherited)
243 }
244}