Sources/OrgstarMobile/MobileEditor+Macros.swift
255 lines · 11289 bytes
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 @discardableResult
108 func playMacro(_ keys: [KeyChord], count: Int) -> Bool {
109 guard kmacroDepth < 20 else {
110 fail("Keyboard macros nest too deeply")
111 return false
112 }
113 let outer = macroKeys
114 kmacroDepth += 1
115 defer {
116 kmacroDepth -= 1
117 macroKeys = outer
118 if kmacroDepth == 0 { macroError = nil }
119 }
120 var rounds = 0
121 var failed = false
122 while count == 0 ? rounds < 100_000 : rounds < count {
123 rounds += 1
124 let before = (document.revision, textView.selectedRange)
125 macroKeys = keys
126 while !macroKeys.isEmpty, macroError == nil {
127 let key = macroKeys.removeFirst()
128 if !handleChord(key) { typeUnhandled(key) }
129 }
130 if macroError != nil {
131 failed = true
132 break
133 }
134 if count == 0, before == (document.revision, textView.selectedRange) { break }
135 }
136 return !failed
137 }
138
139 /// A replayed key that `handleChord` left to the text system: typed here.
140 private func typeUnhandled(_ key: KeyChord) {
141 if modal { return insertTyped(key) }
142 if let command = keymap.candidates(for: [key]).first?.command, command.hasPrefix("edit.") {
143 return replayEdit(command)
144 }
145 let ns = textView.textStorage.string as NSString
146 let selected = textView.selectedRange
147 switch (key.key, key.modifiers) {
148 case ("DEL", []): textView.deleteBackward()
149 case ("<delete>", []):
150 if selected.length > 0 { textView.insertText("") } else if selected.location < ns.length {
151 replace(ns.rangeOfComposedCharacterSequence(at: selected.location), with: "")
152 }
153 case ("<left>", []): replayEdit("edit.backward-char")
154 case ("<right>", []): replayEdit("edit.forward-char")
155 case ("<up>", []): replayEdit("edit.previous-line")
156 case ("<down>", []): replayEdit("edit.next-line")
157 default:
158 let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
159 guard key.modifiers.isEmpty || key.modifiers == [.shift], text.count == 1 else { return fail("\(key) is undefined") }
160 textView.insertText(text)
161 }
162 }
163
164 private func replace(_ range: NSRange, with text: String) {
165 textView.selectedRange = range
166 textView.insertText(text)
167 }
168
169 private func setCaret(to offset: Int) {
170 textView.selectedRange = NSRange(location: offset, length: 0)
171 textView.scrollRangeToVisible(textView.selectedRange)
172 }
173
174 /// The text system's editing keys (C-f, C-n, C-k and the like), which it has while typing.
175 /// Moves that can't move are errors, as in Emacs.
176 private func replayEdit(_ id: String) {
177 let ns = textView.textStorage.string as NSString
178 let caret = textView.selectedRange.location
179 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
180 var lineEnd = 0
181 ns.getLineStart(nil, end: nil, contentsEnd: &lineEnd, for: line)
182 let column = caret - line.location
183 switch id {
184 case "edit.forward-char":
185 guard caret < ns.length else { return fail("End of buffer") }
186 setCaret(to: NSMaxRange(ns.rangeOfComposedCharacterSequence(at: caret)))
187 case "edit.backward-char":
188 guard caret > 0 else { return fail("Beginning of buffer") }
189 setCaret(to: ns.rangeOfComposedCharacterSequence(at: caret - 1).location)
190 case "edit.next-line":
191 guard NSMaxRange(line) < ns.length || (NSMaxRange(line) == ns.length && lineEnd < NSMaxRange(line)) else {
192 setCaret(to: ns.length)
193 return fail("End of buffer")
194 }
195 let next = ns.lineRange(for: NSRange(location: NSMaxRange(line), length: 0))
196 var nextEnd = 0
197 ns.getLineStart(nil, end: nil, contentsEnd: &nextEnd, for: next)
198 setCaret(to: min(next.location + column, nextEnd))
199 case "edit.previous-line":
200 guard line.location > 0 else {
201 setCaret(to: 0)
202 return fail("Beginning of buffer")
203 }
204 let previous = ns.lineRange(for: NSRange(location: line.location - 1, length: 0))
205 setCaret(to: min(previous.location + column, line.location - 1))
206 case "edit.beginning-of-line": setCaret(to: line.location)
207 case "edit.end-of-line": setCaret(to: lineEnd)
208 case "edit.beginning-of-buffer": setCaret(to: 0)
209 case "edit.end-of-buffer": setCaret(to: ns.length)
210 case "edit.forward-word", "edit.backward-word":
211 let forward = id == "edit.forward-word"
212 guard let start = textView.selectedTextRange?.end,
213 let position = textView.tokenizer.position(from: start, toBoundary: .word, inDirection: .storage(forward ? .forward : .backward))
214 else { return }
215 setCaret(to: textView.offset(from: textView.beginningOfDocument, to: position))
216 case "edit.delete-char":
217 guard caret < ns.length else { return fail("End of buffer") }
218 replace(ns.rangeOfComposedCharacterSequence(at: caret), with: "")
219 case "edit.kill-line":
220 guard caret < ns.length else { return fail("End of buffer") }
221 replace(NSRange(location: caret, length: caret < lineEnd ? lineEnd - caret : NSMaxRange(line) - caret), with: "")
222 default:
223 fail(Self.unavailable(command: id))
224 }
225 }
226
227 /// `kmacro-name-last-macro`, with the name saved in `macros.toml`.
228 private func nameLastMacro() {
229 guard let keys = Self.kmacro.last else { return fail("No keyboard macro defined") }
230 ask(Prompt(key: "macro-name", message: "Name for last kbd macro:")) { [weak self] answer in
231 guard let self, let answer else { return }
232 let name = answer.trimmingCharacters(in: .whitespaces)
233 guard NamedMacros.isValidName(name) else {
234 return self.fail(name.isEmpty ? "No command name given" : "A macro name has letters, digits, - and _ only")
235 }
236 do {
237 try self.namedMacros.name(name, keys)
238 self.onMessage?("Macro \(name) saved in \(NamedMacros.fileName)")
239 } catch {
240 self.fail("\(NamedMacros.fileName) wasn't written: \(error.localizedDescription)")
241 }
242 }
243 }
244
245 private func runNamedMacro(count: Int) {
246 let names = namedMacros.names
247 guard !names.isEmpty else { return fail("No named macros") }
248 ask(Prompt(key: "macro", message: "Run macro:", choices: names)) { [weak self] answer in
249 guard let self, let answer else { return }
250 guard let keys = self.namedMacros.keys(answer) else { return self.fail("No macro named \(answer)") }
251 self.playMacro(keys, count: count)
252 }
253 }
254}
255#endif