Tests/OrgEditorAppKitTests/ModalTests.swift

d4c76b8503d7069cc3c2404db3cafc46defe1a9a
orgstar/Tests/OrgEditorAppKitTests/ModalTests.swift history · blame · raw

300 lines · 11057 bytes

  1import AppKit
  2import OrgCore
  3import OrgPresentation
  4import Testing
  5@testable import OrgEditorAppKit
  6
  7/// The Doom preset in the editor: keys through the keymap and the modal engine.
  8@MainActor
  9struct ModalTests {
 10    func doom(_ text: String) -> Harness {
 11        let h = Harness(text)
 12        h.editor.keymap = KeymapPreset.doom.keymap
 13        h.editor.modal = true
 14        return h
 15    }
 16
 17    /// Types `keys` as key events: letters, `ESC`, `RET`, `TAB`, `SPC`.
 18    func type(_ h: Harness, _ keys: String) {
 19        let codes: [String: UInt16] = ["ESC": 53, "RET": 36, "TAB": 48, "SPC": 49]
 20        for token in keys.split(separator: " ") {
 21            let key = String(token)
 22            if key.hasPrefix("C-") {
 23                let letter = String(key.dropFirst(2))
 24                let named = codes[letter]
 25                let characters = named == nil ? letter : " "
 26                KeyTests().send(h, characters: characters, ignoring: characters, code: named ?? 0, flags: .control)
 27            } else if let code = codes[key] {
 28                let characters = key == "ESC" ? "\u{1b}" : key == "RET" ? "\r" : key == "TAB" ? "\t" : " "
 29                KeyTests().send(h, characters: characters, ignoring: characters, code: code)
 30            } else {
 31                let shifted = key.first!.isUppercase
 32                KeyTests().send(h, characters: key, ignoring: key, code: 0, flags: shifted ? .shift : [])
 33            }
 34        }
 35    }
 36
 37    @Test func normalStateEditsAndInsertTypes() {
 38        let h = doom("hello world\nsecond\n")
 39        h.caret(at: 0)
 40        type(h, "d w")
 41        #expect(h.editor.document.text == "world\nsecond\n")
 42        type(h, "c i w")
 43        #expect(h.editor.vim.mode == .insert)
 44        h.textView.insertText("planet", replacementRange: h.textView.selectedRange())
 45        type(h, "ESC")
 46        #expect(h.editor.document.text == "planet\nsecond\n")
 47        #expect(h.textView.selectedRange().location == 5)
 48        type(h, "j .")
 49        #expect(h.editor.document.text == "planet\nplanet\n")
 50    }
 51
 52    @Test func undo() {
 53        let h = doom("hello world\n")
 54        h.caret(at: 0)
 55        type(h, "d w")
 56        #expect(h.editor.document.text == "world\n")
 57        type(h, "u")
 58        #expect(h.editor.document.text == "hello world\n")
 59    }
 60
 61    @Test func leaderAndOrgKeys() {
 62        let h = doom("* TODO Task\n")
 63        var app: [String] = []
 64        h.editor.onAppCommand = { app.append($0) }
 65        h.caret(at: 2)
 66        type(h, "SPC f s")
 67        #expect(app == ["app.save"])
 68        type(h, "RET")
 69        #expect(h.editor.document.text == "* DONE Task\n")
 70        type(h, "SPC m t")
 71        #expect(h.editor.document.text == "* KILL Task\n" || h.editor.document.text.hasPrefix("* "))
 72        type(h, "TAB")
 73        #expect(h.editor.vim.mode == .normal)
 74    }
 75
 76    @Test func registersAndMacrosAreShared() {
 77        let a = doom("alpha beta\n")
 78        let b = doom("one\ntwo\n")
 79        a.caret(at: 0)
 80        type(a, "\" r y w")
 81        b.caret(at: 0)
 82        type(b, "\" r P")
 83        #expect(b.editor.document.text == "alpha one\ntwo\n")
 84        type(a, "q m A ! ESC q")
 85        type(b, "j @ m")
 86        #expect(b.editor.document.text == "alpha one\ntwo!\n")
 87    }
 88
 89    @Test func uppercaseMarksAreGlobal() {
 90        let a = doom("first\n  second\n")
 91        let b = doom("other\ntext\n")
 92        var jumps: [(OrgEditor, Int)] = []
 93        b.editor.onJumpToEditor = { jumps.append(($0, $1)) }
 94        a.caret(at: 10)
 95        type(a, "m Q m q")
 96        b.caret(at: 0)
 97        type(b, "' Q")
 98        #expect(jumps.count == 1 && jumps.first?.0 === a.editor && jumps.first?.1 == 8)
 99        type(b, "` Q")
100        #expect(jumps.last?.1 == 10)
101        // Lowercase marks stay in their buffer.
102        type(b, "j ' q")
103        #expect(b.textView.selectedRange().location == 6)
104        // In its own buffer the mark is an ordinary jump, and follows edits.
105        type(a, "g g O")
106        a.textView.insertText("new", replacementRange: a.textView.selectedRange())
107        type(a, "ESC ` Q")
108        #expect(a.textView.selectedRange().location == 14)
109    }
110
111    @Test func foldKeysToggleOpenAndClose() {
112        let h = doom("* A\nbody\n** B\nb body\n* C\n")
113        h.caret(at: 0)
114        type(h, "z c")
115        #expect(h.editor.foldState.folds == [0])
116        type(h, "z o")
117        #expect(h.editor.foldState.folds == [9])
118        type(h, "z o")
119        #expect(h.editor.foldState.folds == [9])
120        type(h, "z a")
121        #expect(h.editor.foldState.folds.contains(0))
122        type(h, "z a")
123        #expect(h.editor.foldState.folds == [9])
124        // za and zo act on a heading line; zc closes the subtree around the caret.
125        h.editor.setFolds(FoldState())
126        h.caret(at: 5)
127        type(h, "z a")
128        type(h, "z o")
129        #expect(h.editor.foldState.folds.isEmpty)
130        h.caret(at: 15)
131        type(h, "z c")
132        #expect(h.editor.foldState.folds == [9])
133    }
134
135    @Test func fillOperatorsInTheEditor() {
136        let h = doom("short\nlines\n\nnext\n")
137        h.caret(at: 7)
138        type(h, "g w a p")
139        #expect(h.editor.document.text == "short lines\n\nnext\n")
140        #expect(h.textView.selectedRange().location == 7)
141        type(h, "u")
142        #expect(h.editor.document.text == "short\nlines\n\nnext\n")
143    }
144
145    @Test func zzSavesAndClosesAsWq() {
146        let h = doom("text\n")
147        var app: [String] = []
148        h.editor.onAppCommand = { app.append($0) }
149        h.caret(at: 0)
150        type(h, "Z Q")
151        #expect(app.isEmpty)
152        type(h, "Z Z")
153        #expect(app == ["app.save"])
154    }
155
156    @Test func windowLinesInTheEditor() {
157        let h = doom("one\ntwo\nthree\nfour\nfive\n")
158        h.caret(at: 0)
159        type(h, "L")
160        #expect(h.textView.selectedRange().location == 19)
161        type(h, "M")
162        #expect(h.textView.selectedRange().location == 8)
163        type(h, "H")
164        #expect(h.textView.selectedRange().location == 0)
165    }
166
167    @Test func undefinedLeaderSequencesDoNothing() {
168        let h = doom("* Task\nbody text\n")
169        var messages: [String] = []
170        h.editor.onMessage = { messages.append($0) }
171        h.caret(at: 0)
172        type(h, "SPC m z")
173        #expect(messages.last == "SPC m z is undefined")
174        #expect(h.textView.selectedRange().location == 0)
175        // No mark z was set: a jump to it fails and the caret stays.
176        type(h, "j ' z")
177        #expect(h.textView.selectedRange().location == 7)
178        type(h, "C-c z")
179        #expect(messages.last == "C-c z is undefined")
180        #expect(h.editor.document.text == "* Task\nbody text\n")
181        // Evil's own prefixes still reach it.
182        type(h, "g g")
183        #expect(h.textView.selectedRange().location == 0)
184    }
185
186    @Test func keyHintsFollowContext() {
187        let h = doom("* a\n#+begin_src sh\necho\n#+end_src\n")
188        var hints: [(key: String, title: String)] = []
189        h.editor.onKeysPending = { _, next in if !next.isEmpty { hints = next } }
190        func hint() -> String? { hints.first { $0.key == "C-c" }?.title }
191        h.caret(at: 1)
192        type(h, "C-c")
193        #expect(hint() != nil && hint() != "Run Source Block")
194        type(h, "C-g")
195        h.caret(at: 20)
196        type(h, "C-c")
197        #expect(hint() == "Run Source Block")
198        type(h, "C-g")
199    }
200
201    @Test func visualSelection() {
202        let h = doom("one two three\n")
203        h.caret(at: 0)
204        type(h, "v e")
205        #expect(h.textView.selectedRange() == NSRange(location: 0, length: 3))
206        type(h, "d")
207        #expect(h.editor.document.text == " two three\n")
208        #expect(h.textView.selectedRange().length == 0)
209    }
210
211    func shiftTab(_ h: Harness) {
212        KeyTests().send(h, characters: "\u{19}", ignoring: "\u{19}", code: 48, flags: .shift)
213    }
214
215    @Test func insertStateTabFollowsDoom() {
216        let h = doom("* Top\n** Sub\n- one\n- item\n  - child\nbody\n")
217        h.caret(at: 8)
218        type(h, "i")
219        #expect(h.editor.vim.mode == .insert)
220        shiftTab(h)
221        #expect(h.editor.document.text.hasPrefix("* Top\n* Sub\n"))
222        type(h, "TAB")
223        #expect(h.editor.document.text.hasPrefix("* Top\n** Sub\n"))
224        let item = (h.editor.document.text as NSString).range(of: "- item").location
225        h.caret(at: item + 3)
226        type(h, "TAB")
227        #expect(h.editor.document.text.contains("- one\n  - item\n    - child\n"))
228        #expect(h.editor.vim.mode == .insert)
229    }
230
231    @Test func shiftTabCyclesInNormalState() {
232        let h = doom("* Top\nbody\n")
233        h.caret(at: 7)
234        let before = h.editor.document.text
235        shiftTab(h)
236        #expect(h.editor.document.text == before)
237        #expect(h.editor.vim.mode == .normal)
238    }
239
240    @Test func reportsStateAndQuits() {
241        let h = doom("text\n")
242        var states: [String?] = []
243        var app: [String] = []
244        h.editor.onModeChange = { states.append($0) }
245        h.editor.onAppCommand = { app.append($0) }
246        h.caret(at: 0)
247        type(h, "i")
248        type(h, "ESC")
249        type(h, "V")
250        type(h, "ESC")
251        type(h, "SPC q q")
252        #expect(states == ["insert", "normal", "visual-line", "normal"])
253        #expect(app == ["app.quit"])
254        h.editor.modal = false
255        #expect(states.last == .some(nil))
256    }
257
258    @Test func macrosReplayKeys() {
259        let h = doom("one two\nthree four\nfive six\nseven\n")
260        h.caret(at: 0)
261        type(h, "q a d w j q")
262        #expect(h.editor.document.text == "two\nthree four\nfive six\nseven\n")
263        type(h, "@ a")
264        #expect(h.editor.document.text == "two\nfour\nfive six\nseven\n")
265        type(h, "@ @")
266        #expect(h.editor.document.text == "two\nfour\nsix\nseven\n")
267        type(h, "g g q b A ! ESC j q 2 @ b")
268        #expect(h.editor.document.text == "two!\nfour!\nsix!\nseven\n", "\(h.editor.document.text.debugDescription)")
269    }
270
271    @Test func jumpsAndMarks() {
272        let h = doom("one\ntwo\nthree\nfour\n")
273        h.caret(at: 4)
274        type(h, "G")
275        #expect(h.textView.selectedRange().location == 19)
276        type(h, "C-o")
277        #expect(h.textView.selectedRange().location == 4)
278        type(h, "C-i")
279        #expect(h.textView.selectedRange().location == 19)
280        type(h, "g g m a G ' a")
281        #expect(h.textView.selectedRange().location == 0)
282        // Marks follow edits above them.
283        type(h, "G m b g g O")
284        h.textView.insertText("new", replacementRange: h.textView.selectedRange())
285        type(h, "ESC ` b")
286        #expect(h.textView.selectedRange().location == 23)
287    }
288}
289
290struct PresetCommandTests {
291    /// Every command a preset binds is one the editor runs, and every mode is a state.
292    @Test func presetsBindKnownCommands() throws {
293        let known = Set(EditorCommands.all.map(\.id))
294        for preset in KeymapPreset.allCases {
295            var problems: [String] = []
296            _ = try Keymap(toml: preset.toml, problems: &problems, commands: known)
297            #expect(problems.isEmpty, "\(preset): \(problems)")
298        }
299    }
300}