Sources/OrgEditorAppKit/OrgEditor+Macros.swift
294 lines · 12976 bytes
16 symbols in this file
1#if os(macOS)
2import AppKit
3import OrgCore
4
5/// Keyboard macros as Emacs's kmacro has them, in every preset: keys are recorded as they reach
6/// `handleChord`, as the Doom preset's `q` records them, and replayed through it. A prompt
7/// opened while replaying reads its answer from the macro's keys; a command that fails stops
8/// the macro.
9extension OrgEditor {
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 public func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
22 if kmacroDepth > 0 {
23 guard let (answer, used) = MacroRecorder.reply(from: macroKeys) else {
24 // The rest of the macro doesn't answer it: it is the person's to answer.
25 macroKeys = []
26 onPrompt?(prompt, reply)
27 return
28 }
29 macroKeys.removeFirst(used)
30 switch answer {
31 case .answer(let text): reply(text)
32 case .quit:
33 macroError = "Quit"
34 reply(nil)
35 }
36 return
37 }
38 let records = Self.kmacro.isRecording
39 onPrompt?(prompt) { answer in
40 if records { Self.kmacro.record(answer: answer) }
41 reply(answer)
42 }
43 }
44
45 /// The count a macro command runs with: the prefix argument of the keys that ran it, or 1.
46 private var macroCount: Int { commandKeys == nil ? 1 : dispatcher.argument ?? 1 }
47
48 func macroCommand(_ id: String) {
49 let byKey = commandKeys != nil
50 do {
51 switch id {
52 case "macro.start":
53 try startMacro()
54 case "macro.end":
55 try endMacro(byKey: byKey)
56 case "macro.call":
57 // `kmacro-end-and-call-macro`: e runs it again, as C-x e's last key.
58 if Self.kmacro.isRecording { try endMacro(byKey: byKey) }
59 let key = commandKeys.flatMap { $0.count > 1 ? $0.last : nil }
60 callLastMacro(count: macroCount, repeatKey: key)
61 case "macro.start-or-insert-counter":
62 if Self.kmacro.isRecording || kmacroDepth > 0 {
63 textView.insertText(Self.kmacro.insertCounter(), replacementRange: textView.selectedRange())
64 } else {
65 try startMacro()
66 }
67 case "macro.end-or-call":
68 if Self.kmacro.isRecording { try endMacro(byKey: byKey) } else { callLastMacro(count: macroCount, repeatKey: nil) }
69 case "macro.name":
70 nameLastMacro()
71 case "macro.run":
72 runNamedMacro(count: macroCount)
73 default:
74 let name = String(id.dropFirst(NamedMacros.commandPrefix.count))
75 guard id.hasPrefix(NamedMacros.commandPrefix), let keys = namedMacros.keys(name) else {
76 return fail("No macro named \(name)")
77 }
78 playMacro(keys, count: macroCount)
79 }
80 } catch let failure as MacroRecorder.Failure {
81 fail(failure.message)
82 } catch {
83 fail("\(error)")
84 }
85 }
86
87 private func startMacro() throws {
88 // A macro that starts one while replaying does nothing, as in Emacs.
89 guard kmacroDepth == 0 else { return }
90 try Self.kmacro.start()
91 onMessage?("Defining keyboard macro…")
92 }
93
94 private func endMacro(byKey: Bool) throws {
95 guard kmacroDepth == 0 else { return }
96 onMessage?(try Self.kmacro.end(byKey: byKey))
97 }
98
99 func callLastMacro(count: Int, repeatKey: KeyChord?) {
100 let completed: Bool
101 do {
102 completed = playMacro(try Self.kmacro.lastMacro(), count: count)
103 } catch let failure as MacroRecorder.Failure {
104 return fail(failure.message)
105 } catch {
106 return
107 }
108 guard completed, kmacroDepth == 0, let repeatKey else { return }
109 macroRepeatKey = repeatKey
110 onMessage?("(Type \(repeatKey) to repeat macro)")
111 }
112
113 /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a
114 /// round changes nothing. False when a command failed.
115 /// A key that starts a user command leaves the replay waiting until the command has
116 /// finished; it goes on from there.
117 @discardableResult
118 func playMacro(_ keys: [KeyChord], count: Int) -> Bool {
119 guard kmacroDepth < 20 else {
120 fail("Keyboard macros nest too deeply")
121 return false
122 }
123 let replay = MacroReplay(keys: keys, count: count, outer: macroKeys)
124 let outermost = kmacroDepth == 0
125 kmacroDepth += 1
126 switch replayMacro(replay) {
127 case .ended(let error):
128 return error == nil
129 case .waiting(let wait):
130 // A replay this one runs in waits for the rest of it.
131 let rest = resumeMacro(replay, after: wait)
132 if !outermost { macroWait = rest }
133 return true
134 }
135 }
136
137 /// Goes on with `replay` each time the work it waits for has finished.
138 private func resumeMacro(_ replay: MacroReplay, after wait: MacroWait) -> MacroWait {
139 let rest = MacroWait()
140 Task { [weak self] in
141 var wait = wait
142 while true {
143 let failure = await wait.value
144 guard let self else { return rest.finish("") }
145 if let failure, self.macroError == nil { self.macroError = failure }
146 switch self.replayMacro(replay) {
147 case .ended(let error): return rest.finish(error)
148 case .waiting(let next): wait = next
149 }
150 }
151 }
152 return rest
153 }
154
155 /// A macro being replayed: the rounds run, and the state the current round started from,
156 /// nil between rounds.
157 final class MacroReplay {
158 let keys: [KeyChord]
159 let count: Int
160 /// The keys left in the replay this one runs in.
161 let outer: [KeyChord]
162 var rounds = 0
163 var before: (Int, NSRange)?
164
165 init(keys: [KeyChord], count: Int, outer: [KeyChord]) {
166 self.keys = keys
167 self.count = count
168 self.outer = outer
169 }
170 }
171
172 /// Feeds `replay`'s keys through `handleChord` until it ends with the error that stopped it,
173 /// nil when it ran through, or until a key leaves `macroWait` set: the replay waits for
174 /// that work and goes on with the next key.
175 private func replayMacro(_ replay: MacroReplay) -> MacroStep {
176 while true {
177 if replay.before == nil {
178 guard replay.count == 0 ? replay.rounds < 100_000 : replay.rounds < replay.count else { return endReplay(replay) }
179 replay.rounds += 1
180 replay.before = (document.revision, textView.selectedRange())
181 macroKeys = replay.keys
182 }
183 while !macroKeys.isEmpty, macroError == nil {
184 let key = macroKeys.removeFirst()
185 macroWait = nil
186 if !handleChord(key) { typeUnhandled(key) }
187 if let wait = macroWait {
188 macroWait = nil
189 return .waiting(wait)
190 }
191 }
192 if macroError != nil { return endReplay(replay) }
193 if replay.count == 0, let before = replay.before, before == (document.revision, textView.selectedRange()) { return endReplay(replay) }
194 replay.before = nil
195 }
196 }
197
198 private func endReplay(_ replay: MacroReplay) -> MacroStep {
199 let error = macroError
200 kmacroDepth -= 1
201 macroKeys = replay.outer
202 if kmacroDepth == 0 { macroError = nil }
203 return .ended(error)
204 }
205
206 /// A replayed key that `handleChord` left to the text system, which gets it as an event.
207 /// ⌘ keys go to the menus.
208 private func typeUnhandled(_ key: KeyChord) {
209 if modal { return insertTyped(key) }
210 guard let event = Self.event(for: key, window: textView.window) else { return }
211 if key.modifiers.contains(.command) {
212 if NSApp.mainMenu?.performKeyEquivalent(with: event) != true { fail("\(key) is undefined") }
213 } else {
214 textView.interpretKeyEvents([event])
215 }
216 }
217
218 /// A key-down event for `key`, the reverse of `KeyEvents.chord`.
219 static func event(for key: KeyChord, window: NSWindow?) -> NSEvent? {
220 let functionKeys: [String: Int] = [
221 "<delete>": NSDeleteFunctionKey, "<left>": NSLeftArrowFunctionKey, "<right>": NSRightArrowFunctionKey,
222 "<up>": NSUpArrowFunctionKey, "<down>": NSDownArrowFunctionKey, "<home>": NSHomeFunctionKey,
223 "<end>": NSEndFunctionKey, "<prior>": NSPageUpFunctionKey, "<next>": NSPageDownFunctionKey,
224 ]
225 let named = ["TAB": "\t", "RET": "\r", "SPC": " ", "ESC": "\u{1b}", "DEL": "\u{7f}"]
226 let characters: String
227 if let text = named[key.key] {
228 characters = text
229 } else if let code = functionKeys[key.key] ?? key.key.firstMatch(of: /^<f(\d+)>$/).flatMap({ Int($0.1) }).map({ NSF1FunctionKey + $0 - 1 }),
230 let scalar = Unicode.Scalar(code) {
231 characters = String(Character(scalar))
232 } else if key.key.count == 1 {
233 characters = key.key
234 } else {
235 return nil
236 }
237 var flags: NSEvent.ModifierFlags = []
238 if key.modifiers.contains(.control) { flags.insert(.control) }
239 if key.modifiers.contains(.meta) { flags.insert(.option) }
240 if key.modifiers.contains(.shift) || (key.key.count == 1 && key.key.uppercased() == key.key && key.key.lowercased() != key.key) { flags.insert(.shift) }
241 if key.modifiers.contains(.command) { flags.insert(.command) }
242 let code = KeyEvents.named.first { $0.value == key.key }?.key ?? 0
243 return NSEvent.keyEvent(
244 with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: window?.windowNumber ?? 0,
245 context: nil, characters: characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: code
246 )
247 }
248
249 /// While replaying, C-f, C-b, C-n and C-p that can't move are errors, as in Emacs.
250 func checkMovement(_ id: String, from before: NSRange) {
251 let after = textView.selectedRange()
252 let ns = textView.string as NSString
253 let lineStart = { (offset: Int) in ns.lineRange(for: NSRange(location: offset, length: 0)).location }
254 switch id {
255 case "edit.forward-char" where after == before: fail("End of buffer")
256 case "edit.backward-char" where after == before: fail("Beginning of buffer")
257 case "edit.next-line" where NSMaxRange(after) == ns.length && (after == before || lineStart(NSMaxRange(before)) == lineStart(ns.length)):
258 fail("End of buffer")
259 case "edit.previous-line" where after.location == 0 && (after == before || lineStart(before.location) == 0):
260 fail("Beginning of buffer")
261 default: break
262 }
263 }
264
265 /// `kmacro-name-last-macro`, with the name saved in `macros.toml`.
266 private func nameLastMacro() {
267 guard let keys = Self.kmacro.last else { return fail("No keyboard macro defined") }
268 ask(Prompt(key: "macro-name", message: "Name for last kbd macro:")) { [weak self] answer in
269 guard let self, let answer else { return }
270 let name = answer.trimmingCharacters(in: .whitespaces)
271 guard NamedMacros.isValidName(name) else {
272 return self.fail(name.isEmpty ? "No command name given" : "A macro name has letters, digits, - and _ only")
273 }
274 do {
275 try self.namedMacros.name(name, keys)
276 self.onMessage?("Macro \(name) saved in \(NamedMacros.fileName)")
277 } catch {
278 self.fail("\(NamedMacros.fileName) wasn't written: \(error.localizedDescription)")
279 }
280 }
281 }
282
283 /// Runs a named macro picked by name.
284 private func runNamedMacro(count: Int) {
285 let names = namedMacros.names
286 guard !names.isEmpty else { return fail("No named macros") }
287 ask(Prompt(key: "macro", message: "Run macro:", choices: names)) { [weak self] answer in
288 guard let self, let answer else { return }
289 guard let keys = self.namedMacros.keys(answer) else { return self.fail("No macro named \(answer)") }
290 self.playMacro(keys, count: count)
291 }
292 }
293}
294#endif