Sources/OrgEditorAppKit/Modal.swift
319 lines · 14568 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgDocument
5
6/// Modal editing: keys go to the keymap for the current evil state first (leader keys,
7/// evil-org's org keys), then to `Vim`.
8extension OrgEditor {
9 func handleModal(_ chord: KeyChord) -> Bool {
10 // ⌘ shortcuts stay with the menus.
11 if chord.modifiers.contains(.command) { return false }
12 if recordingRegister != nil, replayingMacro == 0 { recordedKeys.append(chord) }
13 dispatcher.mode = vim.mode.keymapMode
14 if !vim.pending.isEmpty, vim.mode != .insert {
15 return feedVim([chord])
16 }
17 switch dispatcher.feed(chord) {
18 case .pending(let keys):
19 let next = keymap.continuations(of: keys, mode: dispatcher.mode).map { item in
20 (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
21 }
22 onKeysPending?(KeySequence.format(keys), next)
23 return true
24 case .cancelled:
25 onKeysPending?(nil, [])
26 return true
27 case .complete(let keys, let candidates):
28 if keys.count > 1 { onKeysPending?(nil, []) }
29 let context = editContext()
30 if let binding = candidates.first(where: { binding in
31 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && commandApplies(binding.command, in: context)
32 }) {
33 run(binding.command)
34 updateCursor()
35 return true
36 }
37 return feedVim(keys)
38 case .undefined(let keys):
39 onKeysPending?(nil, [])
40 return feedVim(keys)
41 case .unbound:
42 return feedVim([chord])
43 }
44 }
45
46 /// Plays keys into the engine. False hands a single key in insert state to the text
47 /// system.
48 func feedVim(_ keys: [KeyChord]) -> Bool {
49 for (index, key) in keys.enumerated() {
50 if vim.mode == .insert, vim.passesThrough(key) {
51 if keys.count == 1 { return false }
52 insertTyped(key)
53 continue
54 }
55 let leaving = key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control)
56 if vim.mode == .insert, leaving, let snapshot = insertSnapshot {
57 // What was typed since insert state began, for `.`.
58 if let edit = TextEdit.between(snapshot.text, document.text).first, edit.range.count == 0 {
59 vim.inserted(edit.replacement)
60 }
61 }
62 let wasInsert = vim.mode == .insert
63 let visual = vim.mode == .visual || vim.mode == .visualLine
64 let caret = visual ? (visualCaret ?? textView.selectedRange().location) : textView.selectedRange().location
65 let clipboard = NSPasteboard.general.string(forType: .string)
66 var marks = vimMarks
67 if jumpIndex > 0, jumpIndex <= jumpList.count { marks["'"] = jumpList[jumpIndex - 1] }
68 let actions = vim.feed(key, Vim.Context(text: document.text, caret: caret, clipboard: clipboard, halfPage: halfPage, marks: marks))
69 apply(actions)
70 if !wasInsert, vim.mode == .insert {
71 insertSnapshot = (document.text, textView.selectedRange().location)
72 } else if vim.mode != .insert {
73 insertSnapshot = nil
74 }
75 _ = index
76 }
77 updateCursor()
78 return true
79 }
80
81 /// Moves marks and jump positions through an edit.
82 func mapVimPositions(through edit: TextEdit) {
83 guard !vimMarks.isEmpty || !jumpList.isEmpty else { return }
84 let names = Array(vimMarks.keys)
85 let mapped = ViewState(selection: names.map { vimMarks[$0]!..<vimMarks[$0]! } + jumpList.map { $0..<$0 }).mapped(through: [edit]).selection
86 for (i, name) in names.enumerated() { vimMarks[name] = mapped[i].lowerBound }
87 jumpList = mapped.dropFirst(names.count).map { $0.lowerBound }
88 }
89
90 func insertTyped(_ key: KeyChord) {
91 let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
92 guard key.modifiers.isEmpty, text.count == 1 else { return }
93 textView.insertText(text, replacementRange: textView.selectedRange())
94 }
95
96 var halfPage: Int {
97 guard let scroll = textView.enclosingScrollView, let font = textView.font else { return 15 }
98 let lineHeight = max(1, font.ascender - font.descender + font.leading)
99 return max(1, Int(scroll.contentView.bounds.height / lineHeight / 2))
100 }
101
102 private func editContext() -> EditContext {
103 let selected = textView.selectedRange()
104 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [selected.location..<NSMaxRange(selected)], options: options)
105 }
106
107 private func commandApplies(_ id: String, in context: EditContext) -> Bool {
108 if !isOrg, id.hasPrefix("org.") { return false }
109 return switch EditorCommands.command(id)?.action {
110 case .text(let command): command.applies(in: context)
111 default: true
112 }
113 }
114
115 func apply(_ actions: [Vim.Action]) {
116 for action in actions {
117 switch action {
118 case .edit(let edits, let caret):
119 visualCaret = nil
120 guard textView.isEditable else {
121 onMessage?("This file is read-only.")
122 continue
123 }
124 applyEdits(edits)
125 setCaret(caret)
126 textView.scrollRangeToVisible(NSRange(location: min(caret, document.text.utf16.count), length: 0))
127 case .move(let caret):
128 setCaret(caret)
129 visualCaret = caret
130 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
131 case .select(let range):
132 textView.setSelectedRange(NSRange(range))
133 case .command(let id):
134 run(id)
135 case .visualLines(let count):
136 for _ in 0..<abs(count) {
137 if count > 0 { textView.moveDown(nil) } else { textView.moveUp(nil) }
138 }
139 clampCaret()
140 case .undo(let count):
141 for _ in 0..<count { textView.undoManager?.undo() }
142 clampCaret()
143 case .redo(let count):
144 for _ in 0..<count { textView.undoManager?.redo() }
145 clampCaret()
146 case .setClipboard(let text):
147 NSPasteboard.general.clearContents()
148 NSPasteboard.general.setString(text, forType: .string)
149 case .prompt(let kind):
150 prompt(kind)
151 case .message(let text):
152 onMessage?(text)
153 case .setMark(let name, let offset):
154 vimMarks[name] = offset
155 case .jumped(let from):
156 // A new jump drops the ones C-o went back past.
157 jumpList = Array(jumpList.prefix(jumpIndex))
158 if jumpList.last != from { jumpList.append(from) }
159 if jumpList.count > 100 { jumpList.removeFirst(jumpList.count - 100) }
160 jumpIndex = jumpList.count
161 case .jumpBack(let count):
162 // Leaving the newest place keeps it, so C-i comes back to it.
163 if jumpIndex == jumpList.count {
164 jumpList.append(textView.selectedRange().location)
165 jumpIndex = jumpList.count - 1
166 }
167 guard jumpIndex - count >= 0 else { continue }
168 jumpIndex -= count
169 reveal(jumpList[jumpIndex])
170 case .jumpForward(let count):
171 guard jumpIndex + count < jumpList.count else { continue }
172 jumpIndex += count
173 reveal(jumpList[jumpIndex])
174 case .recordMacro(let name):
175 if let name {
176 recordingRegister = name
177 recordedKeys = []
178 onMessage?("Defining keyboard macro…")
179 } else if let register = recordingRegister {
180 // Without the `q` that ended it.
181 macros[register] = Array(recordedKeys.dropLast())
182 recordingRegister = nil
183 onMessage?("Keyboard macro defined")
184 }
185 case .playMacro(let name, let count):
186 guard let keys = macros[name], !keys.isEmpty else {
187 onMessage?("No macro in register \(name)")
188 continue
189 }
190 guard replayingMacro < 20 else { continue }
191 replayingMacro += 1
192 defer { replayingMacro -= 1 }
193 for _ in 0..<count {
194 for key in keys where !handleModal(key) {
195 // Printable keys in insert state type, as the text system would.
196 insertTyped(key)
197 }
198 }
199 case .selectBlock(let ranges):
200 textView.setSelectedRanges(ranges.map { NSValue(range: NSRange($0)) }, affinity: .downstream, stillSelecting: false)
201 }
202 }
203 }
204
205 private func clampCaret() {
206 guard vim.mode == .normal else { return }
207 let ns = document.text as NSString
208 let caret = min(textView.selectedRange().location, ns.length)
209 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
210 var end = 0
211 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line)
212 if caret >= end, end > line.location { setCaret(end - 1) }
213 }
214
215 /// `/`, `?` and `:` read their argument in the echo area.
216 private func prompt(_ kind: String) {
217 onPrompt?(Prompt(key: kind, message: kind)) { [weak self] answer in
218 guard let self, let answer, !answer.isEmpty else { return }
219 let caret = self.textView.selectedRange().location
220 let context = Vim.Context(text: self.document.text, caret: caret)
221 if kind == ":" {
222 self.ex(answer)
223 } else {
224 self.apply(self.vim.search(answer, forward: kind == "/", context))
225 }
226 self.updateCursor()
227 }
228 }
229
230 /// The ex commands people reach for: `:w`, `:q`, `:wq`, `:x`, `:N`, `:s`, `:%s`, `:e FILE`,
231 /// `:bn`, `:bp`, `:bd`, `:b` and `:ls`.
232 func ex(_ command: String) {
233 let trimmed = command.trimmingCharacters(in: .whitespaces)
234 if let m = trimmed.firstMatch(of: #/^e(?:dit)?!?\s+(.+)$/#) {
235 onOpenFile?(String(m.1).trimmingCharacters(in: .whitespaces))
236 return
237 }
238 switch trimmed {
239 case "w", "write": onAppCommand?("app.save")
240 case "bn", "bnext": onAppCommand?("app.buffer.next")
241 case "bp", "bprevious", "bN", "bNext": onAppCommand?("app.buffer.previous")
242 case "bd", "bdelete", "bd!", "bw", "bwipeout": onAppCommand?("app.buffer.kill")
243 case "b", "buffer", "ls", "buffers", "files": onAppCommand?("app.buffer.switch")
244 case "e", "edit", "e!", "edit!": onAppCommand?("app.revert")
245 case "q", "quit", "q!": textView.window?.performClose(nil)
246 case "wq", "x", "wq!":
247 onAppCommand?("app.save")
248 textView.window?.performClose(nil)
249 case "noh", "nohlsearch": break
250 default:
251 if let line = Int(trimmed) {
252 let ns = document.text as NSString
253 var offset = 0
254 for _ in 1..<max(1, line) {
255 let range = ns.lineRange(for: NSRange(location: offset, length: 0))
256 guard NSMaxRange(range) < ns.length else { break }
257 offset = NSMaxRange(range)
258 }
259 setCaret(offset)
260 textView.scrollRangeToVisible(NSRange(location: offset, length: 0))
261 return
262 }
263 if let m = trimmed.firstMatch(of: /^(%?)s\/((?:[^\/\\]|\\.)*)\/((?:[^\/\\]|\\.)*)\/?([gi]*)$/) {
264 substitute(whole: !m.1.isEmpty, pattern: String(m.2), replacement: String(m.3), flags: String(m.4))
265 return
266 }
267 onMessage?("Not an editor command: \(trimmed)")
268 }
269 }
270
271 private func substitute(whole: Bool, pattern: String, replacement: String, flags: String) {
272 let options: NSRegularExpression.Options = flags.contains("i") ? [.caseInsensitive] : []
273 guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
274 onMessage?("Invalid pattern: \(pattern)")
275 return
276 }
277 let ns = document.text as NSString
278 let caret = textView.selectedRange().location
279 let lines = whole ? NSRange(location: 0, length: ns.length) : ns.lineRange(for: NSRange(location: caret, length: 0))
280 var edits: [TextEdit] = []
281 var location = lines.location
282 while location < NSMaxRange(lines) {
283 let line = ns.lineRange(for: NSRange(location: location, length: 0))
284 let matches = regex.matches(in: ns as String, range: line)
285 for m in flags.contains("g") ? matches : Array(matches.prefix(1)) {
286 let template = regex.replacementString(for: m, in: ns as String, offset: 0, template: replacement.replacingOccurrences(of: "\\\\([0-9])", with: "\\$$1", options: .regularExpression))
287 edits.append(TextEdit(range: m.range.location..<NSMaxRange(m.range), replacement: template))
288 }
289 location = NSMaxRange(line)
290 }
291 guard !edits.isEmpty else {
292 onMessage?("Pattern not found: \(pattern)")
293 return
294 }
295 applyEdits(edits)
296 onMessage?("\(edits.count) substitution\(edits.count == 1 ? "" : "s")")
297 }
298
299 /// A block cursor in normal and visual states, a bar in insert state.
300 func updateCursor() {
301 let block = modal && vim.mode != .insert
302 (textView as? OrgTextView)?.blockCursor = block
303 dispatcher.mode = modal ? vim.mode.keymapMode : nil
304 let state = modal ? vim.mode.rawValue : nil
305 if state != reportedMode {
306 reportedMode = state
307 onModeChange?(state)
308 }
309 }
310
311 /// A mouse click leaves visual state, as in evil.
312 func modalMouseDown() {
313 guard modal else { return }
314 vim.reset()
315 visualCaret = nil
316 updateCursor()
317 }
318}
319#endif