Tests/OrgCoreTests/KeymapTests.swift

5b5584bafaafd3d627ecb2778987cef0e743de9c
orgstar/Tests/OrgCoreTests/KeymapTests.swift

355 lines · 17754 bytes

  1import Testing
  2@testable import OrgCore
  3
  4struct KeyNotationTests {
  5    @Test func parsesAndFormats() {
  6        #expect(KeySequence.parse("C-c C-x C-i").map(KeySequence.format) == "C-c C-x C-i")
  7        #expect(KeyChord.parse("C-M-x") == KeyChord("x", [.control, .meta]))
  8        #expect(KeyChord.parse("S-a") == KeyChord("A"))
  9        #expect(KeyChord.parse("S-TAB") == KeyChord("TAB", .shift))
 10        #expect(KeyChord.parse("<backtab>") == KeyChord("TAB", .shift))
 11        #expect(KeyChord.parse("C--") == KeyChord("-", .control))
 12        #expect(KeyChord.parse("M-<") == KeyChord("<", .meta))
 13        #expect(KeyChord.parse("s-<left>")?.description == "s-<left>")
 14        #expect(KeyChord.parse("<tab>") == KeyChord("TAB"))
 15        #expect(KeyChord.parse("X-a") == nil)
 16        #expect(KeyChord.parse("abc") == nil)
 17        #expect(KeySequence.parse("") == nil)
 18    }
 19}
 20
 21struct TOMLTests {
 22    @Test func parsesTables() throws {
 23        let tables = try TOML.parse("""
 24            top = 1 # comment
 25            [[bind]]
 26            keys = "C-c \\"x\\""
 27            when = 'heading'
 28            on = true
 29
 30            [options]
 31            name = "a\\u00e9"
 32            """)
 33        #expect(tables.count == 3)
 34        #expect(tables[0].values["top"] == .integer(1))
 35        #expect(tables[1].name == "bind" && tables[1].isArrayElement && tables[1].line == 2)
 36        #expect(tables[1].values["keys"] == .string("C-c \"x\""))
 37        #expect(tables[1].values["when"] == .string("heading"))
 38        #expect(tables[1].values["on"] == .bool(true))
 39        #expect(tables[2].values["name"] == .string("aé"))
 40    }
 41
 42    @Test func parsesArrays() throws {
 43        let tables = try TOML.parse("""
 44            one = ["a", 'b', 3, true, ["c"]]  # comment
 45            empty = []
 46            many = [
 47              "x",  # first
 48              "y]",
 49            ]
 50            after = 1
 51            """)
 52        #expect(tables[0].values["one"] == .array([.string("a"), .string("b"), .integer(3), .bool(true), .array([.string("c")])]))
 53        #expect(tables[0].values["empty"] == .array([]))
 54        #expect(tables[0].values["many"] == .array([.string("x"), .string("y]")]))
 55        #expect(tables[0].values["after"] == .integer(1))
 56        #expect(throws: TOML.ParseError(line: 1, message: "unclosed array")) { try TOML.parse("a = [\"x\",\nb = 1") }
 57        #expect(throws: TOML.ParseError(line: 1, message: "expected , or ] in array")) { try TOML.parse("a = [\"x\" \"y\"]") }
 58    }
 59
 60    @Test func reportsErrorsWithLines() {
 61        #expect(throws: TOML.ParseError(line: 2, message: "unclosed string")) { try TOML.parse("[[bind]]\nkeys = \"C-c") }
 62        #expect(throws: TOML.ParseError(line: 1, message: "expected key = value")) { try TOML.parse("keys") }
 63        #expect(throws: TOML.ParseError(line: 2, message: "duplicate key a")) { try TOML.parse("a = 1\na = 2") }
 64    }
 65}
 66
 67struct KeymapTests {
 68    func map(_ toml: String) throws -> (Keymap, [String]) {
 69        var problems: [String] = []
 70        let keymap = try Keymap(toml: toml, problems: &problems)
 71        return (keymap, problems)
 72    }
 73
 74    @Test func skipsBadEntries() throws {
 75        let (keymap, problems) = try map("""
 76            [[bind]]
 77            keys = "C-c C-t"
 78            command = "org.todo.cycle"
 79            [[bind]]
 80            keys = "Q-x"
 81            command = "a"
 82            [[bind]]
 83            keys = "TAB"
 84            command = "a"
 85            when = "nowhere"
 86            [other]
 87            """)
 88        #expect(keymap.bindings.count == 1)
 89        #expect(problems.count == 3)
 90    }
 91
 92    @Test func reportsUnknownModesAndCommands() throws {
 93        var problems: [String] = []
 94        let keymap = try Keymap(toml: """
 95            [[bind]]
 96            keys = "g x"
 97            command = "org.todo.cycle"
 98            mode = "visual-line"
 99            [[bind]]
100            keys = "g y"
101            command = "org.todo.cycel"
102            mode = "normal"
103            [[bind]]
104            keys = "g z"
105            command = "none"
106            mode = "visual"
107            [[bind]]
108            keys = "C-c x"
109            command = "org.todo.cycle"
110            """, problems: &problems, commands: ["org.todo.cycle"])
111        #expect(problems == ["line 1: unknown mode visual-line", "line 5: unknown command org.todo.cycel"])
112        #expect(keymap.bindings.map(\.command) == ["none", "org.todo.cycle"])
113        // Without a command list, ids aren't checked.
114        problems = []
115        _ = try Keymap(toml: "[[bind]]\nkeys = \"x\"\ncommand = \"anything\"\nmode = \"insert\"\n", problems: &problems)
116        #expect(problems.isEmpty)
117    }
118
119    @Test func laterLayersWinAndCanUnbind() throws {
120        let preset = KeymapPreset.emacs.keymap
121        let (user, _) = try map("""
122            [[bind]]
123            keys = "C-c C-t"
124            command = "org.priority.up"
125            [[bind]]
126            keys = "C-k"
127            command = "none"
128            """)
129        let keymap = Keymap.layered([preset, user])
130        #expect(keymap.candidates(for: KeySequence.parse("C-c C-t")!).first?.command == "org.priority.up")
131        #expect(keymap.candidates(for: KeySequence.parse("C-k")!).isEmpty)
132        #expect(keymap.keys(for: "org.todo.next").map(KeySequence.format) == "S-<right>")
133    }
134
135    @Test func keyLabelsForMenus() {
136        let emacs = KeymapPreset.emacs.keymap
137        #expect(emacs.keyLabels(for: "org.todo.cycle") == ["C-c C-t"])
138        #expect(emacs.keyLabels(for: "org.todo.next") == ["S-<right>"])
139        #expect(emacs.keyLabels(for: "org.schedule") == ["C-c C-s"])
140        let doom = KeymapPreset.doom.keymap
141        let labels = doom.keyLabels(for: "org.todo.cycle", modes: ["normal", "insert"])
142        #expect(labels == ["C-c C-t", "SPC m t"])
143        #expect(doom.keyLabels(for: "app.quit", modes: ["normal", "insert"]) == ["SPC q q"])
144        #expect(doom.keyLabels(for: "app.buffer.kill", modes: ["normal"], limit: 3) == ["C-x k", "SPC b d", "SPC b k"])
145        #expect(doom.keyLabels(for: "app.buffer.next", modes: ["normal"]) == ["] b", "C-x <right>"])
146        #expect(emacs.keyLabels(for: "app.buffer.switch") == ["C-x C-b", "C-x b"])
147        for (keys, command) in [("z C", "org.fold.close"), ("z O", "org.fold.open-subtree"), ("z R", "org.fold.open-all"), ("z M", "org.fold.close-all"),
148                                ("z r", "org.fold.more"), ("z m", "org.fold.less")] {
149            #expect(doom.candidates(for: KeySequence.parse(keys)!, mode: "normal").first?.command == command)
150        }
151        #expect(!emacs.keyLabels(for: "app.quick-open").contains("C-x b"))
152    }
153
154    /// Two bindings of the same keys in the same state, both always applying: the earlier one
155    /// can never run.
156    @Test func presetsBindEachKeyOnce() {
157        for preset in KeymapPreset.allCases {
158            var seen: [String: String] = [:]
159            for binding in preset.keymap.bindings where binding.when == nil && !binding.unbinds {
160                let key = "\(binding.mode ?? "-") \(KeySequence.format(binding.keys))"
161                #expect(seen[key] == nil, "\(preset): \(key) is \(seen[key] ?? "") and \(binding.command)")
162                seen[key] = binding.command
163            }
164        }
165    }
166
167    /// ⌃⌘Q locks the screen, ⌃⌘D looks up a word, ⌃⌘F toggles full screen and ⌃⌘Space opens
168    /// the character viewer: the app never sees them.
169    @Test func macPresetAvoidsSystemShortcuts() {
170        let reserved = ["q", "d", "f", "SPC"].map { KeyChord($0, [.control, .command]) }
171        for binding in KeymapPreset.mac.keymap.bindings {
172            #expect(!reserved.contains(binding.keys[0]), "\(KeySequence.format(binding.keys)) is \(binding.command)")
173        }
174        #expect(KeymapPreset.mac.keymap.keys(for: "org.tags.set") == [KeyChord("g", [.control, .command])])
175        #expect(KeymapPreset.mac.keymap.keys(for: "org.deadline") == [KeyChord("e", [.control, .command])])
176        // ⌃Space switches input sources, so Complete at Point is ⌥Esc, the system's completion key.
177        #expect(KeymapPreset.mac.keymap.keys(for: "editor.complete") == [KeyChord("ESC", [.meta])])
178    }
179
180    /// The Mac preset reaches links, clocking, export and act-at-point without the palette.
181    @Test func macPresetCoversOrgAreas() {
182        let mac = KeymapPreset.mac.keymap
183        let expected: [(String, String)] = [
184            ("org.ctrl-c-ctrl-c", "C-s-x"), ("org.link.insert", "s-k"), ("org.link.open", "C-s-o"), ("org.link.store", "C-s-l"),
185            ("app.clock.in", "C-s-i"), ("app.clock.out", "C-s-I"), ("app.clock.goto", "C-s-j"), ("app.export-dialog", "s-E"),
186            ("org.narrow.toggle", "C-s-n"), ("org.sort", "C-s-S"), ("org.property.read-and-set", "C-s-P"),
187            ("org.footnote.action", "C-s-F"), ("org.edit-special", "C-s-'"), ("org.todo.next", "C-S-s-<right>"),
188            ("org.heading.forward-same-level", "M-S-s-<down>"), ("org.effort.set", "C-s-E"), ("org.priority.set", "C-s-,"),
189            ("org.babel.tangle", "C-s-v"), ("org.babel.tangle-block", "C-s-V"), ("org.babel.tangle-target", "C-M-s-v"),
190            ("app.clock.cancel", "C-s-k"), ("org.table.recalc", "C-s-*"),
191        ]
192        for (command, keys) in expected {
193            #expect(mac.keys(for: command).map(KeySequence.format) == keys, "\(command)")
194        }
195    }
196
197    /// A binding whose keys start a longer live binding never runs: the dispatcher waits for more.
198    @Test func presetsBindNoPrefixes() {
199        for preset in KeymapPreset.allCases {
200            let keymap = preset.keymap
201            for binding in keymap.bindings where !binding.unbinds && keymap.isLive(binding) {
202                #expect(!keymap.isPrefix(binding.keys, mode: binding.mode),
203                        "\(preset): \(KeySequence.format(binding.keys)) (\(binding.command)) is also a prefix")
204            }
205        }
206    }
207
208    @Test func structureCommandsAreBound() {
209        let emacs = KeymapPreset.emacs.keymap, doom = KeymapPreset.doom.keymap
210        for (command, keys) in [("org.drawer.insert", "C-c C-x d"), ("app.refile.copy", "C-c M-w"), ("app.refile.goto", "C-u C-c C-w"),
211                                ("org.element.drag-forward", "M-<down>"), ("org.item.bullet-next", "S-<right>"),
212                                ("org.schedule.remove", "C-u C-c C-s"), ("org.deadline.remove", "C-u C-c C-d")] {
213            #expect(emacs.keyLabels(for: command).contains(keys), "\(command)")
214        }
215        #expect(doom.keyLabels(for: "app.refile.goto", modes: ["normal"]).contains("SPC u SPC m r r"))
216        #expect(doom.keyLabels(for: "org.schedule.remove", modes: ["normal"]).contains("SPC u SPC m d s"))
217        #expect(doom.keyLabels(for: "org.deadline.remove", modes: ["normal"]).contains("SPC u SPC m d d"))
218        let mac = KeymapPreset.mac.keymap
219        #expect(mac.keyLabels(for: "org.schedule.remove").contains("C-M-s-s") && mac.keyLabels(for: "org.deadline.remove").contains("C-M-s-e"))
220        #expect(doom.keyLabels(for: "org.element.drag-backward", modes: ["normal"]).contains("M-k"))
221        let labels = doom.keyLabels(for: "org.item.bullet-previous", modes: ["normal"], limit: 5)
222        #expect(labels.contains("C-H"), "\(labels)")
223        #expect(doom.keyLabels(for: "app.refile.copy", modes: ["normal"]).contains("C-c M-w"))
224    }
225
226    @Test func shadowedBindingsShowNoKeys() throws {
227        var problems: [String] = []
228        let map = Keymap.layered([KeymapPreset.emacs.keymap, try Keymap(toml: "[[bind]]\nkeys = \"C-c C-t\"\ncommand = \"app.save\"\n", problems: &problems)])
229        #expect(!map.keyLabels(for: "org.todo.cycle").contains("C-c C-t"))
230        #expect(map.keyLabels(for: "app.save").contains("C-c C-t"))
231    }
232
233    @Test func dispatchesPrefixes() {
234        var dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
235        let c = KeyChord("c", .control), t = KeyChord("t", .control), z = KeyChord("z", .control)
236        #expect(dispatcher.feed(c) == .pending([c]))
237        guard case .complete(let keys, let candidates) = dispatcher.feed(t) else {
238            Issue.record("expected a binding")
239            return
240        }
241        #expect(keys == [c, t] && candidates.first?.command == "org.todo.cycle")
242        #expect(dispatcher.feed(c) == .pending([c]))
243        #expect(dispatcher.feed(z) == .undefined([c, z]))
244        #expect(dispatcher.feed(c) == .pending([c]))
245        #expect(dispatcher.feed(KeyDispatcher.quit) == .cancelled)
246        #expect(dispatcher.feed(KeyChord("z")) == .unbound)
247    }
248
249    /// C-u is `universal-argument` where no binding starts with the keys typed.
250    @Test func universalArgument() {
251        var dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
252        func feed(_ keys: String) -> KeyDispatcher.Outcome {
253            var outcome = KeyDispatcher.Outcome.unbound
254            for key in KeySequence.parse(keys)! { outcome = dispatcher.feed(key) }
255            return outcome
256        }
257        let callMacro = { (outcome: KeyDispatcher.Outcome) in
258            if case .complete(let keys, let found) = outcome { return keys == KeySequence.parse("C-x e") && found.first?.command == "macro.call" }
259            return false
260        }
261        #expect(callMacro(feed("C-u 1 2 C-x e")))
262        #expect(dispatcher.argument == 12)
263        #expect(callMacro(feed("C-u C-u C-x e")))
264        #expect(dispatcher.argument == 16)
265        #expect(callMacro(feed("C-x e")))
266        #expect(dispatcher.argument == nil)
267        // Bindings that start with C-u keep it, with no argument.
268        guard case .complete(let keys, _) = feed("C-u C-c C-w") else {
269            Issue.record("expected a binding")
270            return
271        }
272        #expect(keys == KeySequence.parse("C-u C-c C-w") && dispatcher.argument == nil)
273        #expect(feed("C-u 3 C-g") == .cancelled)
274        #expect(feed("C-u C-z") == .undefined(KeySequence.parse("C-u C-z")!))
275    }
276
277    @Test func continuationsListNextKeys() {
278        let keymap = KeymapPreset.emacs.keymap
279        let next = keymap.continuations(of: [KeyChord("x", .control)])
280        #expect(next.contains { $0.key == KeyChord("s", .control) && $0.command == "app.save" })
281        #expect(keymap.continuations(of: []).contains { $0.key == KeyChord("c", .control) && $0.command == nil })
282    }
283
284    @Test func continuationsFollowContext() {
285        let keymap = KeymapPreset.emacs.keymap
286        let text = "* a\n#+begin_src sh\necho\n#+end_src\n"
287        func hint(at caret: Int) -> String?? {
288            let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
289            return keymap.continuations(of: [KeyChord("c", .control)]) { binding in
290                binding.when.map { KeyContext.holds($0, in: context) } ?? true
291            }.first { $0.key == KeyChord("c", .control) }?.command
292        }
293        #expect(hint(at: 1) == "org.ctrl-c-ctrl-c")
294        #expect(hint(at: 20) == "org.babel.execute")
295    }
296
297    @Test func contexts() {
298        let text = "* a\n| x |\n- item\n"
299        let tree = OrgParser.parse(text)
300        func holds(_ name: String, _ caret: Int, _ selection: Range<Int>? = nil) -> Bool {
301            KeyContext.holds(name, in: EditContext(revision: 0, text: text, tree: tree, selection: [selection ?? caret..<caret]))
302        }
303        #expect(holds("heading", 1) && !holds("heading", 5))
304        #expect(holds("table", 5) && !holds("table", 12))
305        #expect(holds("item", 12))
306        #expect(holds("region", 0, 0..<2) && !holds("region", 0))
307    }
308
309    @Test func presetsParse() {
310        for preset in KeymapPreset.allCases { #expect(!preset.keymap.bindings.isEmpty) }
311    }
312}
313
314struct ToggleKeyTests {
315    @Test func ctrlCStarAndMinusPreferTables() {
316        let keymap = KeymapPreset.emacs.keymap
317        let table = "| a |\n"
318        let tableContext = EditContext(revision: 0, text: table, tree: OrgParser.parse(table), selection: [2..<2])
319        let star = KeySequence.parse("C-c *")!
320        let minus = KeySequence.parse("C-c -")!
321        func first(_ keys: [KeyChord], _ context: EditContext) -> String? {
322            keymap.candidates(for: keys).first { $0.when.map { KeyContext.holds($0, in: context) } ?? true }?.command
323        }
324        #expect(first(star, tableContext) == "org.table.recalc")
325        #expect(first(minus, tableContext) == "org.table.insert-hline")
326        let text = "* a\nb\n"
327        let plain = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [5..<5])
328        #expect(first(star, plain) == "org.heading.toggle")
329        #expect(first(minus, plain) == "org.item.toggle")
330    }
331}
332
333struct DynamicBlockKeyTests {
334    @Test func ctrlCCtrlCUpdatesOnTheBeginLine() {
335        let keymap = KeymapPreset.emacs.keymap
336        let text = "#+BEGIN: clocktable :maxlevel 2\n#+END:\n* a\n"
337        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [3..<3])
338        let found = keymap.candidates(for: KeySequence.parse("C-c C-c")!).first { $0.when.map { KeyContext.holds($0, in: context) } ?? true }
339        #expect(found?.command == "org.dblock.update")
340    }
341}
342
343struct CtrlCCtrlCKeyTests {
344    @Test func headingsAndItemsGoThroughOrgCtrlCCtrlC() {
345        let keymap = KeymapPreset.emacs.keymap
346        let text = "* a\n- [ ] b\n| x |\n"
347        func command(at offset: Int) -> String? {
348            let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [offset..<offset])
349            return keymap.candidates(for: KeySequence.parse("C-c C-c")!).first { $0.when.map { KeyContext.holds($0, in: context) } ?? true }?.command
350        }
351        #expect(command(at: 1) == "org.ctrl-c-ctrl-c")
352        #expect(command(at: 5) == "org.ctrl-c-ctrl-c")
353        #expect(command(at: 13) == "org.ctrl-c-ctrl-c")
354    }
355}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form