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