Tests/OrgEditorAppKitTests/MacroTests.swift
396 lines · 18766 bytes
23 symbols in this file
MacroTeststypeemacsrecordStopAndCallcountsendingWithCallRunsTheMacroOnceaFailingCommandStopsTheMacroerrorsAsInEmacspromptsAnswersAreRecordedAndReplayedf3InsertsTheCounterAndF4EndsOrCallsmenuCommandsKeepEveryKeymacPresetKeysdoomNormalStateKeysnamingSavesToTheFileAndLoadsBacknamedMacroBoundInKeymapparsingReportsBadEntriesanswerKeysRoundTripmacrosWaitForUserCommandssettledOracleCasereplayMatchesEmacsrunEmacsliteral
1import AppKit
2import Foundation
3import OrgCore
4import OrgDocument
5import Testing
6@testable import OrgApp
7@testable import OrgEditorAppKit
8
9/// Keyboard macros in the Emacs and Mac presets: C-x (, C-x ), C-x e and their counts, F3 and
10/// F4, prompts answered from the macro, errors that stop it, and named macros in macros.toml.
11@MainActor
12@Suite(.serialized)
13struct MacroTests {
14
15 /// Types `keys`, in the keymap's notation, as key events.
16 func type(_ h: Harness, _ keys: String) {
17 for key in KeySequence.parse(keys)! {
18 let event = OrgEditor.event(for: key, window: h.window)!
19 if key.modifiers.contains(.command) {
20 _ = h.textView.performKeyEquivalent(with: event)
21 } else {
22 h.textView.keyDown(with: event)
23 }
24 }
25 }
26
27 /// An editor with the Emacs keys, no macro recorded, and the messages it shows.
28 func emacs(_ text: String, caret: Int = 0) -> (Harness, () -> [String]) {
29 OrgEditor.kmacro = MacroRecorder()
30 let h = Harness(text)
31 var messages: [String] = []
32 h.editor.onMessage = { messages.append($0) }
33 h.caret(at: caret)
34 return (h, { messages })
35 }
36
37 @Test func recordStopAndCall() {
38 let (h, messages) = emacs("one\ntwo\nthree\nfour\n")
39 type(h, "C-x ( C-a * SPC C-n C-x )")
40 #expect(h.string == "* one\ntwo\nthree\nfour\n")
41 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-a * SPC C-n"))
42 #expect(messages() == ["Defining keyboard macro…", "Keyboard macro defined"])
43 type(h, "C-x e")
44 #expect(h.string == "* one\n* two\nthree\nfour\n")
45 #expect(messages().last == "(Type e to repeat macro)")
46 // e runs it again right after, and only then.
47 type(h, "e e")
48 #expect(h.string == "* one\n* two\n* three\n* four\n")
49 type(h, "C-a e")
50 #expect(h.string == "* one\n* two\n* three\n* four\ne")
51 }
52
53 @Test func counts() {
54 let (h, _) = emacs("a\nb\nc\nd\ne\nf\ng\nh\n")
55 type(h, "C-x ( C-a - SPC C-n C-x )")
56 type(h, "C-u 2 C-x e")
57 #expect(h.string == "- a\n- b\n- c\nd\ne\nf\ng\nh\n")
58 type(h, "C-u C-x e")
59 #expect(h.string == "- a\n- b\n- c\n- d\n- e\n- f\n- g\nh\n")
60 // 0 runs it until a command fails: C-n on the last line.
61 type(h, "C-u 0 C-x e")
62 #expect(h.string == "- a\n- b\n- c\n- d\n- e\n- f\n- g\n- h\n- ")
63 }
64
65 @Test func endingWithCallRunsTheMacroOnce() {
66 let (h, _) = emacs("x\n")
67 type(h, "C-x ( C-e ! C-x e")
68 #expect(h.string == "x!!\n")
69 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-e !"))
70 }
71
72 @Test func aFailingCommandStopsTheMacro() {
73 let (h, messages) = emacs("ab\ncd\n")
74 OrgEditor.kmacro.last = KeySequence.parse("C-f C-f C-f C-f C-f C-f C-f y")
75 type(h, "C-x e")
76 #expect(h.string == "ab\ncd\n")
77 #expect(h.textView.selectedRange().location == 6)
78 #expect(messages().last == "End of buffer")
79 // Nothing waits for e after an error.
80 type(h, "e")
81 #expect(h.string == "ab\ncd\ne")
82 // So does a key sequence nothing binds.
83 let (other, _) = emacs("text\n")
84 OrgEditor.kmacro.last = KeySequence.parse("C-c C-z z")
85 type(other, "C-x e")
86 #expect(other.string == "text\n")
87 }
88
89 @Test func errorsAsInEmacs() {
90 let (h, messages) = emacs("x\n")
91 type(h, "C-x e")
92 #expect(messages().last == "No kbd macro has been defined")
93 type(h, "C-x )")
94 #expect(messages().last == "Not defining kbd macro")
95 type(h, "C-x ( C-x )")
96 #expect(messages().last == "Ignore empty macro")
97 #expect(OrgEditor.kmacro.last == nil)
98 type(h, "C-x ( C-x (")
99 #expect(messages().last == "Already defining keyboard macro")
100 h.editor.run("macro.end")
101 // A prefix argument counts macros only.
102 type(h, "C-u 3 C-c C-t")
103 #expect(messages().last == "C-c C-t doesn't take a prefix argument")
104 type(h, "C-u C-e")
105 #expect(messages().last == "C-e doesn't take a prefix argument")
106 #expect(h.string == "x\n")
107 // Bindings that start with C-u keep it.
108 type(h, "C-u C-c C-w")
109 #expect(messages().last != "C-c C-w doesn't take a prefix argument")
110 }
111
112 @Test func promptsAnswersAreRecordedAndReplayed() {
113 let (h, _) = emacs("* a\n* b\n* c\n")
114 var asked = 0
115 h.editor.onPrompt = { prompt, reply in
116 asked += 1
117 #expect(prompt.key == "tags")
118 reply("foo:bar")
119 }
120 type(h, "C-x ( C-c C-q C-n C-x )")
121 #expect(asked == 1)
122 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-c C-q f o o : b a r RET C-n"))
123 type(h, "C-u 2 C-x e")
124 #expect(asked == 1)
125 #expect(h.string.components(separatedBy: "\n").filter { $0.hasSuffix(":foo:bar:") }.count == 3)
126 // A cancelled prompt records C-g, which stops the macro when replayed.
127 h.editor.onPrompt = { _, reply in reply(nil) }
128 h.caret(at: 0)
129 type(h, "C-x ( C-c C-q C-x )")
130 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-c C-q C-g"))
131 }
132
133 @Test func f3InsertsTheCounterAndF4EndsOrCalls() {
134 let (h, _) = emacs("")
135 type(h, "<f3> <f3> RET <f4>")
136 #expect(h.string == "0\n")
137 type(h, "<f4> <f4>")
138 #expect(h.string == "0\n1\n2\n")
139 type(h, "C-u <f4>")
140 #expect(h.string == "0\n1\n2\n3\n4\n5\n6\n")
141 }
142
143 @Test func menuCommandsKeepEveryKey() {
144 let (h, _) = emacs("abc\n")
145 h.editor.run("macro.start")
146 type(h, "C-f C-d")
147 h.editor.run("macro.end")
148 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-f C-d"))
149 h.editor.run("macro.call")
150 #expect(h.string == "ac")
151 }
152
153 @Test func macPresetKeys() {
154 let (h, _) = emacs("a\nb\nc\n")
155 h.editor.keymap = KeymapPreset.mac.keymap
156 type(h, "C-s-r - <down> <left> C-S-s-r")
157 #expect(OrgEditor.kmacro.last == KeySequence.parse("- <down> <left>"))
158 type(h, "C-s-m C-s-m")
159 #expect(h.string == "-a\n-b\n-c\n")
160 }
161
162 @Test func doomNormalStateKeys() {
163 let (h, _) = emacs("one two\nthree four\nfive six\n")
164 h.editor.keymap = KeymapPreset.doom.keymap
165 h.editor.modal = true
166 type(h, "C-x ( d w j C-x )")
167 #expect(OrgEditor.kmacro.last == KeySequence.parse("d w j"))
168 type(h, "C-x e e")
169 #expect(h.string == "two\nfour\nsix\n")
170 }
171
172 @Test func namingSavesToTheFileAndLoadsBack() throws {
173 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-macros-\(UUID().uuidString)")
174 defer { try? FileManager.default.removeItem(at: folder) }
175 let file = folder.appendingPathComponent(NamedMacros.fileName)
176 let store = NamedMacros()
177 #expect(MacroFile.load(into: store, from: file).isEmpty)
178 let (h, messages) = emacs("* a\n* b\n")
179 h.editor.namedMacros = store
180 var answers = ["x", "tags-and-next", "bad name"]
181 h.editor.onPrompt = { _, reply in reply(answers.removeFirst()) }
182 type(h, "C-x ( C-c C-q C-n C-x ) C-x C-k n")
183 #expect(messages().last == "Macro tags-and-next saved in macros.toml")
184 let text = try String(contentsOf: file, encoding: .utf8)
185 #expect(text.hasSuffix("[macros]\ntags-and-next = \"C-c C-q x RET C-n\"\n"), "\(text)")
186 type(h, "C-x C-k n")
187 #expect(messages().last == "A macro name has letters, digits, - and _ only")
188
189 let loaded = NamedMacros()
190 #expect(MacroFile.load(into: loaded, from: file).isEmpty)
191 #expect(loaded.names == ["tags-and-next"])
192 #expect(loaded.keys("tags-and-next") == KeySequence.parse("C-c C-q x RET C-n"))
193 // Naming another adds it, keeping the first.
194 try loaded.name("other", KeySequence.parse("C-e")!)
195 var problems: [String] = []
196 #expect(try NamedMacros.parse(String(contentsOf: file, encoding: .utf8), problems: &problems).keys.sorted() == ["other", "tags-and-next"])
197 #expect(problems.isEmpty)
198 }
199
200 @Test func namedMacroBoundInKeymap() throws {
201 let store = NamedMacros()
202 store.replace(["bang": KeySequence.parse("C-e ! C-n")!])
203 let known = Set((EditorCommands.builtIn + EditorCommands.namedMacros(store)).map(\.id))
204 var problems: [String] = []
205 let toml = "[[bind]]\nkeys = \"C-c m\"\ncommand = \"macro.named.bang\"\n[[bind]]\nkeys = \"C-c n\"\ncommand = \"macro.named.missing\"\n"
206 let user = try Keymap(toml: toml, problems: &problems, commands: known)
207 #expect(problems == ["line 4: unknown command macro.named.missing"])
208 let (h, messages) = emacs("a\nb\nc\n")
209 h.editor.namedMacros = store
210 h.editor.keymap = .layered([KeymapPreset.emacs.keymap, user])
211 type(h, "C-c m C-u 2 C-c m")
212 #expect(h.string == "a!\nb!\nc!\n")
213 h.editor.run("macro.named.missing")
214 #expect(messages().last == "No macro named missing")
215 // Run Macro… picks one by name.
216 h.caret(at: 0)
217 h.editor.onPrompt = { prompt, reply in
218 #expect(prompt.choices == ["bang"])
219 reply("bang")
220 }
221 h.editor.run("macro.run")
222 #expect(h.string == "a!!\nb!\nc!\n")
223 }
224
225 @Test func parsingReportsBadEntries() throws {
226 var problems: [String] = []
227 let macros = try NamedMacros.parse("[macros]\nok = \"C-a\"\nbad = \"C-\"\n[other]\nx = 1\n", problems: &problems)
228 #expect(macros == ["ok": [KeyChord("a", .control)]])
229 #expect(problems == ["bad: bad keys", "line 4: unknown table [other]"])
230 }
231
232 @Test func answerKeysRoundTrip() {
233 let text = "Tag one\tand\ntwo é"
234 let keys = MacroRecorder.keys(typing: text) + [KeyChord("RET")]
235 #expect(KeySequence.parse(KeySequence.format(keys)) == keys)
236 #expect(MacroRecorder.reply(from: keys)?.reply == .answer(text))
237 #expect(MacroRecorder.reply(from: KeySequence.parse("a b DEL c RET z")!)! == (.answer("ac"), 5))
238 #expect(MacroRecorder.reply(from: KeySequence.parse("a")!) == nil)
239 }
240
241 /// A keyboard macro records a user command's key and its prompt's answer; replaying waits
242 /// for the command to finish before the next key, and answers its prompt from the macro.
243 @Test func macrosWaitForUserCommands() async throws {
244 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
245 defer { try? FileManager.default.removeItem(at: folder) }
246 let modules = folder.appendingPathComponent("config/commands")
247 try FileManager.default.createDirectory(at: modules, withIntermediateDirectories: true)
248 try Data("""
249 export async function stamp(org) {
250 const word = await org.prompt("Word: ");
251 await new Promise(resolve => setTimeout(resolve, 100));
252 const { selection: [{ from }] } = await org.run("org.todo.cycle");
253 const heading = await org.heading();
254 return { edits: [{ from: heading.titleEnd, text: " " + word }], selection: from };
255 }
256 """.utf8).write(to: modules.appendingPathComponent("stamp.js"))
257 let file = folder.appendingPathComponent("a.org")
258 try Data("* one\n* two\n* three\n".utf8).write(to: file)
259 let shared = (UserCommands.shared.all, UserCommands.shared.folder)
260 defer { UserCommands.shared.replace(shared.0, folder: shared.1) }
261 UserCommands.shared.replace([UserCommand(name: "stamp", title: "Stamp", file: "stamp.js", function: "stamp")], folder: modules)
262 OrgEditor.kmacro = MacroRecorder()
263 defer { OrgEditor.kmacro = MacroRecorder() }
264
265 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
266 session.saveMode = .explicit
267 session.userCommands = UserCommands.shared
268 session.open(file.path)
269 let h = Harness(try #require(session.document))
270 h.editor.onChange = { [weak session] in session?.bufferChanged() }
271 session.attach(h.editor)
272 var problems: [String] = []
273 let toml = "[[bind]]\nkeys = \"C-c u\"\ncommand = \"user.stamp\"\n[[bind]]\nkeys = \"C-c m\"\ncommand = \"macro.named.stamp\"\n"
274 let user = try Keymap(toml: toml, problems: &problems, commands: Set(EditorCommands.all.map(\.id) + ["macro.named.stamp"]))
275 h.editor.keymap = .layered([KeymapPreset.emacs.keymap, user])
276 var asked = 0
277 h.editor.onPrompt = { _, reply in
278 asked += 1
279 reply("ok")
280 }
281 var messages: [String] = []
282 h.editor.onMessage = { messages.append($0) }
283 h.editor.onUserCommand = { [weak session, weak h] request, finished in
284 guard let session, let h else { return }
285 session.startUserCommand(request, context: h.editor.context(), file: "a.org", ask: h.editor.ask, report: { messages.append($0) }, finished: finished)
286 }
287 func settled() async throws {
288 for _ in 0..<250 where session.isRunningUserCommand || h.editor.kmacroDepth > 0 { try await Task.sleep(for: .milliseconds(20)) }
289 #expect(!session.isRunningUserCommand && h.editor.kmacroDepth == 0)
290 }
291 h.caret(at: 2)
292 type(h, "C-x ( C-c u")
293 try await settled()
294 type(h, "C-n C-x )")
295 #expect(h.string == "* TODO one ok\n* two\n* three\n")
296 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-c u o k RET C-n"))
297 #expect(asked == 1)
298
299 type(h, "C-u 2 C-x e")
300 try await settled()
301 #expect(h.string == "* TODO one ok\n* TODO two ok\n* TODO three ok\n")
302 #expect(asked == 1)
303 #expect(!messages.contains { $0.contains("undefined") })
304 h.checkInSync()
305 // Each run is one undo step.
306 h.textView.undoManager?.undo()
307 #expect(h.string == "* TODO one ok\n* TODO two ok\n* three\n")
308
309 // A macro waits for a named macro it runs that waits for a user command.
310 let store = NamedMacros()
311 store.replace(["stamp": try OrgEditor.kmacro.lastMacro()])
312 h.editor.namedMacros = store
313 OrgEditor.kmacro.last = KeySequence.parse("C-c m C-e !")
314 h.caret(at: 30)
315 type(h, "C-x e")
316 try await settled()
317 #expect(h.string == "* TODO one ok\n* TODO two ok\n* TODO three ok\n!")
318 #expect(asked == 1)
319 }
320
321 // MARK: - Emacs
322
323 struct OracleCase {
324 var text: String
325 var caret: Int
326 var keys: String
327 var count: Int
328 }
329
330 static let oracleCases = [
331 OracleCase(text: "one\ntwo\nthree\nfour", caret: 0, keys: "C-a * SPC C-n", count: 0),
332 OracleCase(text: "* a\n* b\n* c\n", caret: 0, keys: "C-c C-t C-n", count: 2),
333 OracleCase(text: "* a\n* b\n", caret: 0, keys: "C-c C-q f o o RET C-n", count: 2),
334 OracleCase(text: "ab\ncd", caret: 1, keys: "C-f C-f C-f C-f C-f C-f y", count: 1),
335 OracleCase(text: "- a\n- b\n", caret: 0, keys: "C-e SPC x C-n", count: 0),
336 OracleCase(text: "* TODO a\n", caret: 0, keys: "C-c C-t", count: 3),
337 OracleCase(text: "x", caret: 1, keys: "RET * SPC h", count: 2),
338 OracleCase(text: "a b c\nd e f\n", caret: 0, keys: "C-d C-f C-k C-n C-a", count: 4),
339 OracleCase(text: "first\nsecond\n", caret: 12, keys: "C-p C-p C-e .", count: 0),
340 ]
341
342 /// Each case run in Emacs with `execute-kbd-macro` and here with C-u N C-x e: the same
343 /// buffer and point.
344 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
345 func replayMatchesEmacs() throws {
346 let emacs = try Self.runEmacs(Self.oracleCases)
347 for (index, c) in Self.oracleCases.enumerated() {
348 let (h, _) = self.emacs(c.text, caret: c.caret)
349 OrgEditor.kmacro.last = KeySequence.parse(c.keys)
350 type(h, c.count == 1 ? "C-x e" : "C-u \(c.count) C-x e")
351 #expect(h.string == emacs[index].text, "\(c.keys)")
352 #expect(h.textView.selectedRange().location + 1 == emacs[index].point, "\(c.keys)")
353 }
354 }
355
356 static func runEmacs(_ cases: [OracleCase]) throws -> [(text: String, point: Int)] {
357 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-kmacro-\(UUID().uuidString)")
358 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
359 defer { try? FileManager.default.removeItem(at: folder) }
360 func literal(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
361 let forms = cases.map { "(orgstar-case \(literal($0.text)) \($0.caret + 1) \(literal($0.keys)) \($0.count))" }.joined(separator: "\n")
362 let output = folder.appendingPathComponent("out.json")
363 let script = folder.appendingPathComponent("kmacro.el")
364 try """
365 ;;; -*- lexical-binding: t -*-
366 (require 'org)
367 (require 'json)
368 (setq org-todo-keywords '((sequence "TODO" "DONE")) org-log-done nil org-tags-column -77)
369 (setq-default indent-tabs-mode nil)
370 (defvar orgstar-results nil)
371 (defun orgstar-case (text point keys count)
372 (let ((buffer (generate-new-buffer "case")))
373 ;; Keys run in the selected window's buffer.
374 (switch-to-buffer buffer)
375 (insert text)
376 (org-mode)
377 (goto-char point)
378 (condition-case nil (execute-kbd-macro (kbd keys) count) (error nil))
379 (push (list (buffer-substring-no-properties (point-min) (point-max)) (point)) orgstar-results)
380 (kill-buffer buffer)))
381 \(forms)
382 (with-temp-file \(literal(output.path))
383 (insert (json-encode (vconcat (nreverse orgstar-results)))))
384 """.write(to: script, atomically: true, encoding: .utf8)
385 let process = Process()
386 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
387 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "-l", script.path]
388 process.standardInput = FileHandle.nullDevice
389 process.standardOutput = FileHandle.nullDevice
390 process.standardError = FileHandle.nullDevice
391 try process.run()
392 process.waitUntilExit()
393 let results = try JSONSerialization.jsonObject(with: Data(contentsOf: output)) as! [[Any]]
394 return results.map { ($0[0] as! String, $0[1] as! Int) }
395 }
396}