Sources/OrgstarMobile/MobileEditor+Macros.swift
314 lines · 13811 bytes
17 symbols in this file
1#if os(iOS)
2import OrgCore
3import UIKit
4
5/// Keyboard macros with a hardware keyboard, as on the Mac: keys are recorded as they reach
6/// `handleChord` and replayed through it; a prompt opened while replaying reads its answer from
7/// the macro's keys, and a command that fails stops the macro. Keys the text system types are
8/// typed by the editor while replaying.
9extension MobileEditor {
10 /// The macro being recorded and the last one, shared by every editor as Emacs's are.
11 static var kmacro = MacroRecorder()
12
13 /// Shows `message`; while a macro replays, it is an error that stops it.
14 func fail(_ message: String) {
15 onMessage?(message)
16 if kmacroDepth > 0, macroError == nil { macroError = message }
17 }
18
19 /// Asks through `onPrompt`, recording the answer while a macro records. While one replays,
20 /// the answer comes from its keys.
21 func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
22 if kmacroDepth > 0 {
23 guard let (answer, used) = MacroRecorder.reply(from: macroKeys) else {
24 macroKeys = []
25 onPrompt?(prompt, reply)
26 return
27 }
28 macroKeys.removeFirst(used)
29 switch answer {
30 case .answer(let text): reply(text)
31 case .quit:
32 macroError = "Quit"
33 reply(nil)
34 }
35 return
36 }
37 let records = Self.kmacro.isRecording
38 onPrompt?(prompt) { answer in
39 if records { Self.kmacro.record(answer: answer) }
40 reply(answer)
41 }
42 }
43
44 /// The count a macro command runs with: the prefix argument of the keys that ran it, or 1.
45 private var macroCount: Int { commandKeys == nil ? 1 : dispatcher.argument ?? 1 }
46
47 func macroCommand(_ id: String) {
48 let byKey = commandKeys != nil
49 do {
50 switch id {
51 case "macro.start":
52 try startMacro()
53 case "macro.end":
54 try endMacro(byKey: byKey)
55 case "macro.call":
56 if Self.kmacro.isRecording { try endMacro(byKey: byKey) }
57 callLastMacro(count: macroCount, repeatKey: commandKeys.flatMap { $0.count > 1 ? $0.last : nil })
58 case "macro.start-or-insert-counter":
59 if Self.kmacro.isRecording || kmacroDepth > 0 { textView.insertText(Self.kmacro.insertCounter()) } else { try startMacro() }
60 case "macro.end-or-call":
61 if Self.kmacro.isRecording { try endMacro(byKey: byKey) } else { callLastMacro(count: macroCount, repeatKey: nil) }
62 case "macro.name":
63 nameLastMacro()
64 case "macro.run":
65 runNamedMacro(count: macroCount)
66 default:
67 let name = String(id.dropFirst(NamedMacros.commandPrefix.count))
68 guard id.hasPrefix(NamedMacros.commandPrefix), let keys = namedMacros.keys(name) else {
69 return fail("No macro named \(name)")
70 }
71 playMacro(keys, count: macroCount)
72 }
73 } catch let failure as MacroRecorder.Failure {
74 fail(failure.message)
75 } catch {
76 fail("\(error)")
77 }
78 }
79
80 private func startMacro() throws {
81 guard kmacroDepth == 0 else { return }
82 try Self.kmacro.start()
83 onMessage?("Defining keyboard macro…")
84 }
85
86 private func endMacro(byKey: Bool) throws {
87 guard kmacroDepth == 0 else { return }
88 onMessage?(try Self.kmacro.end(byKey: byKey))
89 }
90
91 func callLastMacro(count: Int, repeatKey: KeyChord?) {
92 let completed: Bool
93 do {
94 completed = playMacro(try Self.kmacro.lastMacro(), count: count)
95 } catch let failure as MacroRecorder.Failure {
96 return fail(failure.message)
97 } catch {
98 return
99 }
100 guard completed, kmacroDepth == 0, let repeatKey else { return }
101 macroRepeatKey = repeatKey
102 onMessage?("(Type \(repeatKey) to repeat macro)")
103 }
104
105 /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a
106 /// round changes nothing. False when a command failed.
107 /// A key that starts a user command leaves the replay waiting until the command has
108 /// finished; it goes on from there.
109 @discardableResult
110 func playMacro(_ keys: [KeyChord], count: Int) -> Bool {
111 guard kmacroDepth < 20 else {
112 fail("Keyboard macros nest too deeply")
113 return false
114 }
115 let replay = MacroReplay(keys: keys, count: count, outer: macroKeys)
116 let outermost = kmacroDepth == 0
117 kmacroDepth += 1
118 switch replayMacro(replay) {
119 case .ended(let error):
120 return error == nil
121 case .waiting(let wait):
122 // A replay this one runs in waits for the rest of it.
123 let rest = resumeMacro(replay, after: wait)
124 if !outermost { macroWait = rest }
125 return true
126 }
127 }
128
129 /// Goes on with `replay` each time the work it waits for has finished.
130 private func resumeMacro(_ replay: MacroReplay, after wait: MacroWait) -> MacroWait {
131 let rest = MacroWait()
132 Task { [weak self] in
133 var wait = wait
134 while true {
135 let failure = await wait.value
136 guard let self else { return rest.finish("") }
137 if let failure, self.macroError == nil { self.macroError = failure }
138 switch self.replayMacro(replay) {
139 case .ended(let error): return rest.finish(error)
140 case .waiting(let next): wait = next
141 }
142 }
143 }
144 return rest
145 }
146
147 /// A macro being replayed: the rounds run, and the state the current round started from,
148 /// nil between rounds.
149 final class MacroReplay {
150 let keys: [KeyChord]
151 let count: Int
152 /// The keys left in the replay this one runs in.
153 let outer: [KeyChord]
154 var rounds = 0
155 var before: (Int, NSRange)?
156
157 init(keys: [KeyChord], count: Int, outer: [KeyChord]) {
158 self.keys = keys
159 self.count = count
160 self.outer = outer
161 }
162 }
163
164 /// Feeds `replay`'s keys through `handleChord` until it ends with the error that stopped it,
165 /// nil when it ran through, or until a key leaves `macroWait` set: the replay waits for
166 /// that work and goes on with the next key.
167 private func replayMacro(_ replay: MacroReplay) -> MacroStep {
168 while true {
169 if replay.before == nil {
170 guard replay.count == 0 ? replay.rounds < 100_000 : replay.rounds < replay.count else { return endReplay(replay) }
171 replay.rounds += 1
172 replay.before = (document.revision, textView.selectedRange)
173 macroKeys = replay.keys
174 }
175 while !macroKeys.isEmpty, macroError == nil {
176 let key = macroKeys.removeFirst()
177 macroWait = nil
178 if !handleChord(key) { typeUnhandled(key) }
179 if let wait = macroWait {
180 macroWait = nil
181 return .waiting(wait)
182 }
183 }
184 if macroError != nil { return endReplay(replay) }
185 if replay.count == 0, let before = replay.before, before == (document.revision, textView.selectedRange) { return endReplay(replay) }
186 replay.before = nil
187 }
188 }
189
190 private func endReplay(_ replay: MacroReplay) -> MacroStep {
191 let error = macroError
192 kmacroDepth -= 1
193 macroKeys = replay.outer
194 if kmacroDepth == 0 { macroError = nil }
195 return .ended(error)
196 }
197
198 /// A replayed key that `handleChord` left to the text system: typed here.
199 private func typeUnhandled(_ key: KeyChord) {
200 if modal { return insertTyped(key) }
201 if let command = keymap.candidates(for: [key]).first?.command, command.hasPrefix("edit.") {
202 return replayEdit(command)
203 }
204 let ns = textView.textStorage.string as NSString
205 let selected = textView.selectedRange
206 switch (key.key, key.modifiers) {
207 case ("DEL", []): textView.deleteBackward()
208 case ("<delete>", []):
209 if selected.length > 0 { textView.insertText("") } else if selected.location < ns.length {
210 replace(ns.rangeOfComposedCharacterSequence(at: selected.location), with: "")
211 }
212 case ("<left>", []): replayEdit("edit.backward-char")
213 case ("<right>", []): replayEdit("edit.forward-char")
214 case ("<up>", []): replayEdit("edit.previous-line")
215 case ("<down>", []): replayEdit("edit.next-line")
216 default:
217 let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
218 guard key.modifiers.isEmpty || key.modifiers == [.shift], text.count == 1 else { return fail("\(key) is undefined") }
219 textView.insertText(text)
220 }
221 }
222
223 private func replace(_ range: NSRange, with text: String) {
224 textView.selectedRange = range
225 textView.insertText(text)
226 }
227
228 private func setCaret(to offset: Int) {
229 textView.selectedRange = NSRange(location: offset, length: 0)
230 textView.scrollRangeToVisible(textView.selectedRange)
231 }
232
233 /// The text system's editing keys (C-f, C-n, C-k and the like), which it has while typing.
234 /// Moves that can't move are errors, as in Emacs.
235 private func replayEdit(_ id: String) {
236 let ns = textView.textStorage.string as NSString
237 let caret = textView.selectedRange.location
238 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
239 var lineEnd = 0
240 ns.getLineStart(nil, end: nil, contentsEnd: &lineEnd, for: line)
241 let column = caret - line.location
242 switch id {
243 case "edit.forward-char":
244 guard caret < ns.length else { return fail("End of buffer") }
245 setCaret(to: NSMaxRange(ns.rangeOfComposedCharacterSequence(at: caret)))
246 case "edit.backward-char":
247 guard caret > 0 else { return fail("Beginning of buffer") }
248 setCaret(to: ns.rangeOfComposedCharacterSequence(at: caret - 1).location)
249 case "edit.next-line":
250 guard NSMaxRange(line) < ns.length || (NSMaxRange(line) == ns.length && lineEnd < NSMaxRange(line)) else {
251 setCaret(to: ns.length)
252 return fail("End of buffer")
253 }
254 let next = ns.lineRange(for: NSRange(location: NSMaxRange(line), length: 0))
255 var nextEnd = 0
256 ns.getLineStart(nil, end: nil, contentsEnd: &nextEnd, for: next)
257 setCaret(to: min(next.location + column, nextEnd))
258 case "edit.previous-line":
259 guard line.location > 0 else {
260 setCaret(to: 0)
261 return fail("Beginning of buffer")
262 }
263 let previous = ns.lineRange(for: NSRange(location: line.location - 1, length: 0))
264 setCaret(to: min(previous.location + column, line.location - 1))
265 case "edit.beginning-of-line": setCaret(to: line.location)
266 case "edit.end-of-line": setCaret(to: lineEnd)
267 case "edit.beginning-of-buffer": setCaret(to: 0)
268 case "edit.end-of-buffer": setCaret(to: ns.length)
269 case "edit.forward-word", "edit.backward-word":
270 let forward = id == "edit.forward-word"
271 guard let start = textView.selectedTextRange?.end,
272 let position = textView.tokenizer.position(from: start, toBoundary: .word, inDirection: .storage(forward ? .forward : .backward))
273 else { return }
274 setCaret(to: textView.offset(from: textView.beginningOfDocument, to: position))
275 case "edit.delete-char":
276 guard caret < ns.length else { return fail("End of buffer") }
277 replace(ns.rangeOfComposedCharacterSequence(at: caret), with: "")
278 case "edit.kill-line":
279 guard caret < ns.length else { return fail("End of buffer") }
280 replace(NSRange(location: caret, length: caret < lineEnd ? lineEnd - caret : NSMaxRange(line) - caret), with: "")
281 default:
282 fail(Self.unavailable(command: id))
283 }
284 }
285
286 /// `kmacro-name-last-macro`, with the name saved in `macros.toml`.
287 private func nameLastMacro() {
288 guard let keys = Self.kmacro.last else { return fail("No keyboard macro defined") }
289 ask(Prompt(key: "macro-name", message: "Name for last kbd macro:")) { [weak self] answer in
290 guard let self, let answer else { return }
291 let name = answer.trimmingCharacters(in: .whitespaces)
292 guard NamedMacros.isValidName(name) else {
293 return self.fail(name.isEmpty ? "No command name given" : "A macro name has letters, digits, - and _ only")
294 }
295 do {
296 try self.namedMacros.name(name, keys)
297 self.onMessage?("Macro \(name) saved in \(NamedMacros.fileName)")
298 } catch {
299 self.fail("\(NamedMacros.fileName) wasn't written: \(error.localizedDescription)")
300 }
301 }
302 }
303
304 private func runNamedMacro(count: Int) {
305 let names = namedMacros.names
306 guard !names.isEmpty else { return fail("No named macros") }
307 ask(Prompt(key: "macro", message: "Run macro:", choices: names)) { [weak self] answer in
308 guard let self, let answer else { return }
309 guard let keys = self.namedMacros.keys(answer) else { return self.fail("No macro named \(answer)") }
310 self.playMacro(keys, count: count)
311 }
312 }
313}
314#endif