Sources/OrgEditorAppKit/Modal.swift
314 lines · 14347 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 .undo(let count):
136 for _ in 0..<count { textView.undoManager?.undo() }
137 clampCaret()
138 case .redo(let count):
139 for _ in 0..<count { textView.undoManager?.redo() }
140 clampCaret()
141 case .setClipboard(let text):
142 NSPasteboard.general.clearContents()
143 NSPasteboard.general.setString(text, forType: .string)
144 case .prompt(let kind):
145 prompt(kind)
146 case .message(let text):
147 onMessage?(text)
148 case .setMark(let name, let offset):
149 vimMarks[name] = offset
150 case .jumped(let from):
151 // A new jump drops the ones C-o went back past.
152 jumpList = Array(jumpList.prefix(jumpIndex))
153 if jumpList.last != from { jumpList.append(from) }
154 if jumpList.count > 100 { jumpList.removeFirst(jumpList.count - 100) }
155 jumpIndex = jumpList.count
156 case .jumpBack(let count):
157 // Leaving the newest place keeps it, so C-i comes back to it.
158 if jumpIndex == jumpList.count {
159 jumpList.append(textView.selectedRange().location)
160 jumpIndex = jumpList.count - 1
161 }
162 guard jumpIndex - count >= 0 else { continue }
163 jumpIndex -= count
164 reveal(jumpList[jumpIndex])
165 case .jumpForward(let count):
166 guard jumpIndex + count < jumpList.count else { continue }
167 jumpIndex += count
168 reveal(jumpList[jumpIndex])
169 case .recordMacro(let name):
170 if let name {
171 recordingRegister = name
172 recordedKeys = []
173 onMessage?("Defining keyboard macro…")
174 } else if let register = recordingRegister {
175 // Without the `q` that ended it.
176 macros[register] = Array(recordedKeys.dropLast())
177 recordingRegister = nil
178 onMessage?("Keyboard macro defined")
179 }
180 case .playMacro(let name, let count):
181 guard let keys = macros[name], !keys.isEmpty else {
182 onMessage?("No macro in register \(name)")
183 continue
184 }
185 guard replayingMacro < 20 else { continue }
186 replayingMacro += 1
187 defer { replayingMacro -= 1 }
188 for _ in 0..<count {
189 for key in keys where !handleModal(key) {
190 // Printable keys in insert state type, as the text system would.
191 insertTyped(key)
192 }
193 }
194 case .selectBlock(let ranges):
195 textView.setSelectedRanges(ranges.map { NSValue(range: NSRange($0)) }, affinity: .downstream, stillSelecting: false)
196 }
197 }
198 }
199
200 private func clampCaret() {
201 guard vim.mode == .normal else { return }
202 let ns = document.text as NSString
203 let caret = min(textView.selectedRange().location, ns.length)
204 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
205 var end = 0
206 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line)
207 if caret >= end, end > line.location { setCaret(end - 1) }
208 }
209
210 /// `/`, `?` and `:` read their argument in the echo area.
211 private func prompt(_ kind: String) {
212 onPrompt?(Prompt(key: kind, message: kind)) { [weak self] answer in
213 guard let self, let answer, !answer.isEmpty else { return }
214 let caret = self.textView.selectedRange().location
215 let context = Vim.Context(text: self.document.text, caret: caret)
216 if kind == ":" {
217 self.ex(answer)
218 } else {
219 self.apply(self.vim.search(answer, forward: kind == "/", context))
220 }
221 self.updateCursor()
222 }
223 }
224
225 /// The ex commands people reach for: `:w`, `:q`, `:wq`, `:x`, `:N`, `:s`, `:%s`, `:e FILE`,
226 /// `:bn`, `:bp`, `:bd`, `:b` and `:ls`.
227 func ex(_ command: String) {
228 let trimmed = command.trimmingCharacters(in: .whitespaces)
229 if let m = trimmed.firstMatch(of: #/^e(?:dit)?!?\s+(.+)$/#) {
230 onOpenFile?(String(m.1).trimmingCharacters(in: .whitespaces))
231 return
232 }
233 switch trimmed {
234 case "w", "write": onAppCommand?("app.save")
235 case "bn", "bnext": onAppCommand?("app.buffer.next")
236 case "bp", "bprevious", "bN", "bNext": onAppCommand?("app.buffer.previous")
237 case "bd", "bdelete", "bd!", "bw", "bwipeout": onAppCommand?("app.buffer.kill")
238 case "b", "buffer", "ls", "buffers", "files": onAppCommand?("app.buffer.switch")
239 case "e", "edit", "e!", "edit!": onAppCommand?("app.revert")
240 case "q", "quit", "q!": textView.window?.performClose(nil)
241 case "wq", "x", "wq!":
242 onAppCommand?("app.save")
243 textView.window?.performClose(nil)
244 case "noh", "nohlsearch": break
245 default:
246 if let line = Int(trimmed) {
247 let ns = document.text as NSString
248 var offset = 0
249 for _ in 1..<max(1, line) {
250 let range = ns.lineRange(for: NSRange(location: offset, length: 0))
251 guard NSMaxRange(range) < ns.length else { break }
252 offset = NSMaxRange(range)
253 }
254 setCaret(offset)
255 textView.scrollRangeToVisible(NSRange(location: offset, length: 0))
256 return
257 }
258 if let m = trimmed.firstMatch(of: /^(%?)s\/((?:[^\/\\]|\\.)*)\/((?:[^\/\\]|\\.)*)\/?([gi]*)$/) {
259 substitute(whole: !m.1.isEmpty, pattern: String(m.2), replacement: String(m.3), flags: String(m.4))
260 return
261 }
262 onMessage?("Not an editor command: \(trimmed)")
263 }
264 }
265
266 private func substitute(whole: Bool, pattern: String, replacement: String, flags: String) {
267 let options: NSRegularExpression.Options = flags.contains("i") ? [.caseInsensitive] : []
268 guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
269 onMessage?("Invalid pattern: \(pattern)")
270 return
271 }
272 let ns = document.text as NSString
273 let caret = textView.selectedRange().location
274 let lines = whole ? NSRange(location: 0, length: ns.length) : ns.lineRange(for: NSRange(location: caret, length: 0))
275 var edits: [TextEdit] = []
276 var location = lines.location
277 while location < NSMaxRange(lines) {
278 let line = ns.lineRange(for: NSRange(location: location, length: 0))
279 let matches = regex.matches(in: ns as String, range: line)
280 for m in flags.contains("g") ? matches : Array(matches.prefix(1)) {
281 let template = regex.replacementString(for: m, in: ns as String, offset: 0, template: replacement.replacingOccurrences(of: "\\\\([0-9])", with: "\\$$1", options: .regularExpression))
282 edits.append(TextEdit(range: m.range.location..<NSMaxRange(m.range), replacement: template))
283 }
284 location = NSMaxRange(line)
285 }
286 guard !edits.isEmpty else {
287 onMessage?("Pattern not found: \(pattern)")
288 return
289 }
290 applyEdits(edits)
291 onMessage?("\(edits.count) substitution\(edits.count == 1 ? "" : "s")")
292 }
293
294 /// A block cursor in normal and visual states, a bar in insert state.
295 func updateCursor() {
296 let block = modal && vim.mode != .insert
297 (textView as? OrgTextView)?.blockCursor = block
298 dispatcher.mode = modal ? vim.mode.keymapMode : nil
299 let state = modal ? vim.mode.rawValue : nil
300 if state != reportedMode {
301 reportedMode = state
302 onModeChange?(state)
303 }
304 }
305
306 /// A mouse click leaves visual state, as in evil.
307 func modalMouseDown() {
308 guard modal else { return }
309 vim.reset()
310 visualCaret = nil
311 updateCursor()
312 }
313}
314#endif