Tests/OrgCoreTests/KeymapTests.swift

9abba9cfc504b344b7d267978a97f1c925a1d5dd
orgstar/Tests/OrgCoreTests/KeymapTests.swift history · blame · raw

206 lines · 9364 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 reportsErrorsWithLines() {
 43        #expect(throws: TOML.ParseError(line: 2, message: "unclosed string")) { try TOML.parse("[[bind]]\nkeys = \"C-c") }
 44        #expect(throws: TOML.ParseError(line: 1, message: "expected key = value")) { try TOML.parse("keys") }
 45        #expect(throws: TOML.ParseError(line: 2, message: "duplicate key a")) { try TOML.parse("a = 1\na = 2") }
 46    }
 47}
 48
 49struct KeymapTests {
 50    func map(_ toml: String) throws -> (Keymap, [String]) {
 51        var problems: [String] = []
 52        let keymap = try Keymap(toml: toml, problems: &problems)
 53        return (keymap, problems)
 54    }
 55
 56    @Test func skipsBadEntries() throws {
 57        let (keymap, problems) = try map("""
 58            [[bind]]
 59            keys = "C-c C-t"
 60            command = "org.todo.cycle"
 61            [[bind]]
 62            keys = "Q-x"
 63            command = "a"
 64            [[bind]]
 65            keys = "TAB"
 66            command = "a"
 67            when = "nowhere"
 68            [other]
 69            """)
 70        #expect(keymap.bindings.count == 1)
 71        #expect(problems.count == 3)
 72    }
 73
 74    @Test func laterLayersWinAndCanUnbind() throws {
 75        let preset = KeymapPreset.emacs.keymap
 76        let (user, _) = try map("""
 77            [[bind]]
 78            keys = "C-c C-t"
 79            command = "org.priority.up"
 80            [[bind]]
 81            keys = "C-k"
 82            command = "none"
 83            """)
 84        let keymap = Keymap.layered([preset, user])
 85        #expect(keymap.candidates(for: KeySequence.parse("C-c C-t")!).first?.command == "org.priority.up")
 86        #expect(keymap.candidates(for: KeySequence.parse("C-k")!).isEmpty)
 87        #expect(keymap.keys(for: "org.todo.next").map(KeySequence.format) == "S-<right>")
 88    }
 89
 90    @Test func keyLabelsForMenus() {
 91        let emacs = KeymapPreset.emacs.keymap
 92        #expect(emacs.keyLabels(for: "org.todo.cycle") == ["C-c C-t"])
 93        #expect(emacs.keyLabels(for: "org.todo.next") == ["S-<right>"])
 94        #expect(emacs.keyLabels(for: "org.schedule") == ["C-c C-s"])
 95        let doom = KeymapPreset.doom.keymap
 96        let labels = doom.keyLabels(for: "org.todo.cycle", modes: ["normal", "insert"])
 97        #expect(labels == ["C-c C-t", "SPC m t"])
 98        #expect(doom.keyLabels(for: "app.quit", modes: ["normal", "insert"]) == ["SPC q q"])
 99        #expect(doom.keyLabels(for: "app.buffer.kill", modes: ["normal"], limit: 3) == ["C-x k", "SPC b d", "SPC b k"])
100        #expect(doom.keyLabels(for: "app.buffer.next", modes: ["normal"]) == ["] b", "C-x <right>"])
101        #expect(emacs.keyLabels(for: "app.buffer.switch") == ["C-x C-b", "C-x b"])
102        #expect(!emacs.keyLabels(for: "app.quick-open").contains("C-x b"))
103    }
104
105    /// Two bindings of the same keys in the same state, both always applying: the earlier one
106    /// can never run.
107    @Test func presetsBindEachKeyOnce() {
108        for preset in KeymapPreset.allCases {
109            var seen: [String: String] = [:]
110            for binding in preset.keymap.bindings where binding.when == nil && !binding.unbinds {
111                let key = "\(binding.mode ?? "-") \(KeySequence.format(binding.keys))"
112                #expect(seen[key] == nil, "\(preset): \(key) is \(seen[key] ?? "") and \(binding.command)")
113                seen[key] = binding.command
114            }
115        }
116    }
117
118    @Test func shadowedBindingsShowNoKeys() throws {
119        var problems: [String] = []
120        let map = Keymap.layered([KeymapPreset.emacs.keymap, try Keymap(toml: "[[bind]]\nkeys = \"C-c C-t\"\ncommand = \"app.save\"\n", problems: &problems)])
121        #expect(!map.keyLabels(for: "org.todo.cycle").contains("C-c C-t"))
122        #expect(map.keyLabels(for: "app.save").contains("C-c C-t"))
123    }
124
125    @Test func dispatchesPrefixes() {
126        var dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
127        let c = KeyChord("c", .control), t = KeyChord("t", .control), z = KeyChord("z", .control)
128        #expect(dispatcher.feed(c) == .pending([c]))
129        guard case .complete(let keys, let candidates) = dispatcher.feed(t) else {
130            Issue.record("expected a binding")
131            return
132        }
133        #expect(keys == [c, t] && candidates.first?.command == "org.todo.cycle")
134        #expect(dispatcher.feed(c) == .pending([c]))
135        #expect(dispatcher.feed(z) == .undefined([c, z]))
136        #expect(dispatcher.feed(c) == .pending([c]))
137        #expect(dispatcher.feed(KeyDispatcher.quit) == .cancelled)
138        #expect(dispatcher.feed(KeyChord("z")) == .unbound)
139    }
140
141    @Test func continuationsListNextKeys() {
142        let keymap = KeymapPreset.emacs.keymap
143        let next = keymap.continuations(of: [KeyChord("x", .control)])
144        #expect(next.contains { $0.key == KeyChord("s", .control) && $0.command == "app.save" })
145        #expect(keymap.continuations(of: []).contains { $0.key == KeyChord("c", .control) && $0.command == nil })
146    }
147
148    @Test func contexts() {
149        let text = "* a\n| x |\n- item\n"
150        let tree = OrgParser.parse(text)
151        func holds(_ name: String, _ caret: Int, _ selection: Range<Int>? = nil) -> Bool {
152            KeyContext.holds(name, in: EditContext(revision: 0, text: text, tree: tree, selection: [selection ?? caret..<caret]))
153        }
154        #expect(holds("heading", 1) && !holds("heading", 5))
155        #expect(holds("table", 5) && !holds("table", 12))
156        #expect(holds("item", 12))
157        #expect(holds("region", 0, 0..<2) && !holds("region", 0))
158    }
159
160    @Test func presetsParse() {
161        for preset in KeymapPreset.allCases { #expect(!preset.keymap.bindings.isEmpty) }
162    }
163}
164
165struct ToggleKeyTests {
166    @Test func ctrlCStarAndMinusPreferTables() {
167        let keymap = KeymapPreset.emacs.keymap
168        let table = "| a |\n"
169        let tableContext = EditContext(revision: 0, text: table, tree: OrgParser.parse(table), selection: [2..<2])
170        let star = KeySequence.parse("C-c *")!
171        let minus = KeySequence.parse("C-c -")!
172        func first(_ keys: [KeyChord], _ context: EditContext) -> String? {
173            keymap.candidates(for: keys).first { $0.when.map { KeyContext.holds($0, in: context) } ?? true }?.command
174        }
175        #expect(first(star, tableContext) == "org.table.recalc")
176        #expect(first(minus, tableContext) == "org.table.insert-hline")
177        let text = "* a\nb\n"
178        let plain = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [5..<5])
179        #expect(first(star, plain) == "org.heading.toggle")
180        #expect(first(minus, plain) == "org.item.toggle")
181    }
182}
183
184struct DynamicBlockKeyTests {
185    @Test func ctrlCCtrlCUpdatesOnTheBeginLine() {
186        let keymap = KeymapPreset.emacs.keymap
187        let text = "#+BEGIN: clocktable :maxlevel 2\n#+END:\n* a\n"
188        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [3..<3])
189        let found = keymap.candidates(for: KeySequence.parse("C-c C-c")!).first { $0.when.map { KeyContext.holds($0, in: context) } ?? true }
190        #expect(found?.command == "org.dblock.update")
191    }
192}
193
194struct CtrlCCtrlCKeyTests {
195    @Test func headingsAndItemsGoThroughOrgCtrlCCtrlC() {
196        let keymap = KeymapPreset.emacs.keymap
197        let text = "* a\n- [ ] b\n| x |\n"
198        func command(at offset: Int) -> String? {
199            let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [offset..<offset])
200            return keymap.candidates(for: KeySequence.parse("C-c C-c")!).first { $0.when.map { KeyContext.holds($0, in: context) } ?? true }?.command
201        }
202        #expect(command(at: 1) == "org.ctrl-c-ctrl-c")
203        #expect(command(at: 5) == "org.ctrl-c-ctrl-c")
204        #expect(command(at: 13) == "org.table.align")
205    }
206}