Sources/OrgEditorAppKit/Modal.swift
484 lines · 24553 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgDocument
5
6/// An editor a file mark is in, gone when its buffer closes.
7struct WeakEditor {
8 weak var editor: OrgEditor?
9}
10
11/// Modal editing: keys go to the keymap for the current evil state first (leader keys,
12/// evil-org's org keys), then to `Vim`.
13extension OrgEditor {
14 func handleModal(_ chord: KeyChord) -> Bool {
15 // ⌘ shortcuts stay with the menus.
16 if chord.modifiers.contains(.command) { return false }
17 if recordingRegister != nil, replayingMacro == 0 { recordedKeys.append(chord) }
18 dispatcher.mode = vim.mode.keymapMode
19 if !vim.pending.isEmpty, vim.mode != .insert {
20 return feedVim([chord])
21 }
22 switch dispatcher.feed(chord) {
23 case .pending(let keys):
24 let context = editContext()
25 let next = keymap.continuations(of: keys, mode: dispatcher.mode) { modalRuns($0, in: context) }.map { item in
26 (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.localizedTitle ?? $0 } ?? "+prefix")
27 }
28 onKeysPending?(KeySequence.format(keys), next)
29 return true
30 case .cancelled:
31 onKeysPending?(nil, [])
32 return true
33 case .complete(let keys, let candidates):
34 if keys.count > 1 { onKeysPending?(nil, []) }
35 let context = editContext()
36 if let binding = candidates.first(where: { modalRuns($0, in: context) }) {
37 if binding.command == "org.fill-paragraph", vim.mode == .visual || vim.mode == .visualLine || vim.mode == .visualBlock {
38 fillVisual()
39 } else {
40 commandKeys = keys
41 defer { commandKeys = nil }
42 run(binding.command)
43 }
44 updateCursor()
45 return true
46 }
47 return feedVim(keys)
48 case .undefined(let keys):
49 onKeysPending?(nil, [])
50 // The leader and Emacs prefixes (C-c, C-x) mean nothing to evil: the sequence is
51 // undefined, as in Doom. Other prefixes (g, z, [, ]) are evil's too.
52 if let first = keys.first, first == KeyChord("SPC") || !first.modifiers.isDisjoint(with: [.control, .meta]) {
53 onMessage?("\(KeySequence.format(keys)) is undefined")
54 return true
55 }
56 return feedVim(keys)
57 case .unbound:
58 return feedVim([chord])
59 }
60 }
61
62 /// M-q in visual states: `org-fill-paragraph` on the region, the cursor kept. Evil turns
63 /// `transient-mark-mode` off in block state, so there it fills the paragraph at the cursor.
64 /// A change deactivates the region, which leaves visual state.
65 private func fillVisual() {
66 let selected = textView.selectedRanges
67 let cursor = visualCaret ?? textView.selectedRange().location
68 let text = document.text
69 if vim.mode == .visualBlock {
70 textView.setSelectedRange(NSRange(location: cursor, length: 0))
71 perform(FillParagraph())
72 } else {
73 perform(FillParagraph(point: cursor))
74 }
75 if document.text == text {
76 textView.selectedRanges = selected
77 visualCaret = cursor
78 } else {
79 vim.reset()
80 visualCaret = nil
81 clampCaret()
82 }
83 }
84
85 /// Plays keys into the engine. False hands a single key in insert state to the text
86 /// system.
87 func feedVim(_ keys: [KeyChord]) -> Bool {
88 for (index, key) in keys.enumerated() {
89 if vim.mode == .insert, vim.passesThrough(key) {
90 if keys.count == 1 { return electricPair(key) || autoFill(key) }
91 if !electricPair(key), !autoFill(key) { insertTyped(key) }
92 continue
93 }
94 let leaving = key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control)
95 if vim.mode == .insert, leaving, let snapshot = insertSnapshot {
96 // What was typed since insert state began, for `.`.
97 if let edit = TextEdit.between(snapshot.text, document.text).first, edit.range.count == 0 {
98 vim.inserted(edit.replacement)
99 }
100 }
101 let wasInsert = vim.mode == .insert
102 let visual = vim.mode == .visual || vim.mode == .visualLine || vim.mode == .visualBlock
103 let caret = visual ? (visualCaret ?? textView.selectedRange().location) : textView.selectedRange().location
104 if jumpToFileMark(key) { continue }
105 let clipboard = NSPasteboard.general.string(forType: .string)
106 var marks = vimMarks
107 for (name, mark) in Self.fileMarks where mark.owner.editor === self { marks[name] = mark.offset }
108 if jumpIndex > 0, jumpIndex <= jumpList.count { marks["'"] = jumpList[jumpIndex - 1] }
109 vim.registers = Self.vimRegisters
110 vim.clipboardRecord = Self.vimClipboardRecord
111 let actions = vim.feed(key, Vim.Context(text: document.text, caret: caret, clipboard: clipboard, halfPage: halfPage, marks: marks, visible: visibleText, org: isOrg,
112 fileName: fileName, lastEx: Self.promptHistory[":"]?.last))
113 Self.vimRegisters = vim.registers
114 Self.vimClipboardRecord = vim.clipboardRecord
115 apply(actions)
116 if !wasInsert, vim.mode == .insert {
117 insertSnapshot = (document.text, textView.selectedRange().location)
118 } else if vim.mode != .insert {
119 insertSnapshot = nil
120 }
121 _ = index
122 }
123 updateCursor()
124 return true
125 }
126
127 /// `'A` or `` `A `` for a file mark in another editor: that editor's buffer shows at the
128 /// mark. True when the key went there.
129 private func jumpToFileMark(_ key: KeyChord) -> Bool {
130 guard vim.mode == .normal, vim.pending.count == 1, let quote = vim.pending.first, quote == KeyChord("'") || quote == KeyChord("`"),
131 key.modifiers.isEmpty, key.key.count == 1, let name = key.key.first, name.isUppercase,
132 let mark = Self.fileMarks[name], let owner = mark.owner.editor, owner !== self else { return false }
133 vim.reset()
134 let ns = owner.document.text as NSString
135 var target = min(mark.offset, ns.length)
136 if quote == KeyChord("'") {
137 // The line's first non-blank.
138 target = ns.lineRange(for: NSRange(location: target, length: 0)).location
139 while target < ns.length, ns.character(at: target) == 32 || ns.character(at: target) == 9 { target += 1 }
140 }
141 onJumpToEditor?(owner, target)
142 return true
143 }
144
145 /// Moves marks and jump positions through an edit.
146 func mapVimPositions(through edit: TextEdit) {
147 let owned = Self.fileMarks.filter { $0.value.owner.editor === self }
148 guard !vimMarks.isEmpty || !jumpList.isEmpty || !owned.isEmpty else { return }
149 let names = Array(vimMarks.keys)
150 let fileNames = Array(owned.keys)
151 let positions = names.map { vimMarks[$0]! } + fileNames.map { owned[$0]!.offset } + jumpList
152 let mapped = ViewState(selection: positions.map { $0..<$0 }).mapped(through: [edit]).selection
153 for (i, name) in names.enumerated() { vimMarks[name] = mapped[i].lowerBound }
154 for (i, name) in fileNames.enumerated() { Self.fileMarks[name]?.offset = mapped[names.count + i].lowerBound }
155 jumpList = mapped.dropFirst(names.count + fileNames.count).map { $0.lowerBound }
156 }
157
158 func insertTyped(_ key: KeyChord) {
159 let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
160 guard key.modifiers.isEmpty, text.count == 1 else { return }
161 textView.insertText(text, replacementRange: textView.selectedRange())
162 }
163
164 var halfPage: Int {
165 guard let scroll = textView.enclosingScrollView, let font = textView.font else { return 15 }
166 let lineHeight = max(1, font.ascender - font.descender + font.leading)
167 return max(1, Int(scroll.contentView.bounds.height / lineHeight / 2))
168 }
169
170 /// The text the window shows, from the line at its top to the line at its bottom.
171 var visibleText: Range<Int>? {
172 guard let layout = textView.textLayoutManager, let content = layout.textContentManager, let scroll = textView.enclosingScrollView else { return nil }
173 let bounds = scroll.contentView.bounds
174 let origin = textView.textContainerOrigin
175 let start = content.documentRange.location
176 guard let top = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, bounds.minY - origin.y))) else { return nil }
177 let lower = content.offset(from: start, to: top.rangeInElement.location)
178 let bottom = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, bounds.maxY - origin.y - 1)))
179 let upper = bottom.map { content.offset(from: start, to: $0.rangeInElement.endLocation) } ?? utf16Length
180 return lower..<max(lower, upper)
181 }
182
183 private func editContext() -> EditContext {
184 let selected = textView.selectedRange()
185 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [selected.location..<NSMaxRange(selected)], options: options)
186 }
187
188 private func modalRuns(_ binding: KeyBinding, in context: EditContext) -> Bool {
189 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && commandApplies(binding.command, in: context)
190 }
191
192 private func commandApplies(_ id: String, in context: EditContext) -> Bool {
193 if !isOrg, id.hasPrefix("org.") { return false }
194 return switch EditorCommands.command(id)?.action {
195 case .text(let command): command.applies(in: context)
196 default: true
197 }
198 }
199
200 func apply(_ actions: [Vim.Action]) {
201 for action in actions {
202 switch action {
203 case .edit(let edits, let caret):
204 visualCaret = nil
205 guard textView.isEditable else {
206 onMessage?("This file is read-only.")
207 continue
208 }
209 applyEdits(edits)
210 setCaret(caret)
211 textView.scrollRangeToVisible(NSRange(location: min(caret, document.text.utf16.count), length: 0))
212 case .move(let caret):
213 setCaret(caret)
214 visualCaret = caret
215 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
216 case .select(let range):
217 textView.setSelectedRange(NSRange(range))
218 case .command(let id):
219 run(id)
220 case .visualLines(let count):
221 for _ in 0..<abs(count) {
222 if count > 0 { textView.moveDown(nil) } else { textView.moveUp(nil) }
223 }
224 clampCaret()
225 case .undo(let count):
226 for _ in 0..<count { textView.undoManager?.undo() }
227 clampCaret()
228 case .redo(let count):
229 for _ in 0..<count { textView.undoManager?.redo() }
230 clampCaret()
231 case .setClipboard(let text):
232 NSPasteboard.general.clearContents()
233 NSPasteboard.general.setString(text, forType: .string)
234 case .prompt(let kind):
235 prompt(kind)
236 case .ex(let command):
237 ex(command)
238 case .fill(let range, let keep):
239 visualCaret = nil
240 textView.setSelectedRange(NSRange(location: textView.selectedRange().location, length: 0))
241 _ = perform(FillRegion(range: range, keep: keep))
242 clampCaret()
243 case .message(let text):
244 onMessage?(text)
245 case .setMark(let name, let offset):
246 if name.isUppercase { Self.fileMarks[name] = (WeakEditor(editor: self), offset) } else { vimMarks[name] = offset }
247 case .jumped(let from):
248 // A new jump drops the ones C-o went back past.
249 jumpList = Array(jumpList.prefix(jumpIndex))
250 if jumpList.last != from { jumpList.append(from) }
251 if jumpList.count > 100 { jumpList.removeFirst(jumpList.count - 100) }
252 jumpIndex = jumpList.count
253 case .jumpBack(let count):
254 // Leaving the newest place keeps it, so C-i comes back to it.
255 if jumpIndex == jumpList.count {
256 jumpList.append(textView.selectedRange().location)
257 jumpIndex = jumpList.count - 1
258 }
259 guard jumpIndex - count >= 0 else { continue }
260 jumpIndex -= count
261 reveal(jumpList[jumpIndex])
262 case .jumpForward(let count):
263 guard jumpIndex + count < jumpList.count else { continue }
264 jumpIndex += count
265 reveal(jumpList[jumpIndex])
266 case .recordMacro(let name):
267 if let name {
268 recordingRegister = name
269 recordedKeys = []
270 onMessage?("Defining keyboard macro…")
271 } else if let register = recordingRegister {
272 // Without the `q` that ended it.
273 Self.macros[register] = Array(recordedKeys.dropLast())
274 recordingRegister = nil
275 onMessage?("Keyboard macro defined")
276 }
277 case .playMacro(let name, let count):
278 guard let keys = Self.macros[name], !keys.isEmpty else {
279 onMessage?("No macro in register \(name)")
280 continue
281 }
282 guard replayingMacro < 20 else { continue }
283 replayingMacro += 1
284 defer { replayingMacro -= 1 }
285 for _ in 0..<count {
286 for key in keys where !handleModal(key) {
287 // Printable keys in insert state type, as the text system would.
288 insertTyped(key)
289 }
290 }
291 case .selectBlock(let ranges):
292 textView.setSelectedRanges(ranges.map { NSValue(range: NSRange($0)) }, affinity: .downstream, stillSelecting: false)
293 case .scroll(let place):
294 scrollCaretLine(place)
295 case .scrollLines(let count):
296 scrollLines(count)
297 case .scrollColumns(let count, let halfWidths):
298 scrollColumns(count, halfWidths: halfWidths)
299 case .commandWindow(let kind):
300 prompt(kind, history: true)
301 }
302 }
303 }
304
305 private func clampCaret() {
306 guard vim.mode == .normal else { return }
307 let ns = document.text as NSString
308 let caret = min(textView.selectedRange().location, ns.length)
309 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
310 var end = 0
311 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line)
312 if caret >= end, end > line.location { setCaret(end - 1) }
313 }
314
315 /// `zz`, `zt` and `zb`: the window scrolled so the caret's screen line is in its middle,
316 /// at its top or at its bottom.
317 private func scrollCaretLine(_ place: Vim.ScrollLine) {
318 guard let scroll = textView.enclosingScrollView, let layout = textView.textLayoutManager, let content = layout.textContentManager else { return }
319 let caret = textView.selectedRange().location
320 guard let location = content.location(content.documentRange.location, offsetBy: caret) else { return }
321 layout.ensureLayout(for: NSTextRange(location: location))
322 guard let fragment = layout.textLayoutFragment(for: location) else { return }
323 let within = content.offset(from: fragment.rangeInElement.location, to: location)
324 let line = fragment.textLineFragments.first { $0.characterRange.contains(within) || $0.characterRange.upperBound == within } ?? fragment.textLineFragments.last
325 let lineFrame = line.map { $0.typographicBounds.offsetBy(dx: 0, dy: fragment.layoutFragmentFrame.minY) } ?? fragment.layoutFragmentFrame
326 let top = lineFrame.minY + textView.textContainerOrigin.y
327 let height = scroll.contentView.bounds.height
328 let y: CGFloat = switch place {
329 case .top: top
330 case .center: top + lineFrame.height / 2 - height / 2
331 case .bottom: top + lineFrame.height - height
332 }
333 let maxY = max(0, textView.frame.height - height)
334 scroll.contentView.scroll(to: NSPoint(x: scroll.contentView.bounds.origin.x, y: min(max(0, y), maxY)))
335 scroll.reflectScrolledClipView(scroll.contentView)
336 }
337
338 /// C-e and C-y: the window down or up by lines; the cursor stays in it, as in Emacs.
339 private func scrollLines(_ count: Int) {
340 guard let scroll = textView.enclosingScrollView, let font = textView.font else { return }
341 let lineHeight = max(1, font.ascender - font.descender + font.leading)
342 let bounds = scroll.contentView.bounds
343 let maxY = max(0, textView.frame.height - bounds.height)
344 scroll.contentView.scroll(to: NSPoint(x: bounds.origin.x, y: min(max(0, bounds.origin.y + CGFloat(count) * lineHeight), maxY)))
345 scroll.reflectScrolledClipView(scroll.contentView)
346 guard vim.mode == .normal, let visible = visibleText, !visible.isEmpty else { return }
347 let caret = textView.selectedRange().location
348 if caret < visible.lowerBound {
349 setCaret(visible.lowerBound)
350 } else if caret >= visible.upperBound {
351 setCaret((document.text as NSString).lineRange(for: NSRange(location: visible.upperBound - 1, length: 0)).location)
352 }
353 }
354
355 /// `zl`, `zh`, `zL` and `zH`: the window right or left by columns or half its width, which
356 /// moves nothing while lines wrap.
357 private func scrollColumns(_ count: Int, halfWidths: Bool) {
358 guard let scroll = textView.enclosingScrollView, let font = textView.font else { return }
359 let bounds = scroll.contentView.bounds
360 let step = halfWidths ? bounds.width / 2 : (" " as NSString).size(withAttributes: [.font: font]).width
361 let maxX = max(0, textView.frame.width - bounds.width)
362 scroll.contentView.scroll(to: NSPoint(x: min(max(0, bounds.origin.x + CGFloat(count) * step), maxX), y: bounds.origin.y))
363 scroll.reflectScrolledClipView(scroll.contentView)
364 }
365
366 /// `/`, `?` and `:` read their argument in the echo area; `history` (`q:`) offers the
367 /// earlier ones to pick and edit.
368 private func prompt(_ kind: String, history: Bool = false) {
369 // `/` and `?` search as you type.
370 if !history, kind == "/" || kind == "?" { return startISearch(forward: kind == "/", vim: true) }
371 let earlier = Array((Self.promptHistory[kind] ?? []).reversed())
372 let request = history ? Prompt(key: kind, message: kind, choices: earlier, requireMatch: false) : Prompt(key: kind, message: kind)
373 ask(request) { [weak self] answer in
374 guard let self, let answer, !answer.isEmpty else { return }
375 var list = Self.promptHistory[kind] ?? []
376 list.removeAll { $0 == answer }
377 list.append(answer)
378 Self.promptHistory[kind] = Array(list.suffix(100))
379 let caret = self.textView.selectedRange().location
380 let context = Vim.Context(text: self.document.text, caret: caret)
381 if kind == ":" {
382 self.ex(answer)
383 } else {
384 self.apply(self.vim.search(answer, forward: kind == "/", context))
385 }
386 self.updateCursor()
387 }
388 }
389
390 /// The ex commands people reach for: `:w`, `:q`, `:wq`, `:x`, `:N`, `:s`, `:%s`, `:e FILE`,
391 /// `:bn`, `:bp`, `:bd`, `:b` and `:ls`.
392 func ex(_ command: String) {
393 let trimmed = command.trimmingCharacters(in: .whitespaces)
394 if let m = trimmed.firstMatch(of: #/^e(?:dit)?!?\s+(.+)$/#) {
395 onOpenFile?(String(m.1).trimmingCharacters(in: .whitespaces))
396 return
397 }
398 switch trimmed {
399 case "w", "write": onAppCommand?("app.save")
400 case "bn", "bnext": onAppCommand?("app.buffer.next")
401 case "bp", "bprevious", "bN", "bNext": onAppCommand?("app.buffer.previous")
402 case "bd", "bdelete", "bd!", "bw", "bwipeout": onAppCommand?("app.buffer.kill")
403 case "b", "buffer", "ls", "buffers", "files": onAppCommand?("app.buffer.switch")
404 case "e", "edit", "e!", "edit!": onAppCommand?("app.revert")
405 case "q", "quit", "q!": textView.window?.performClose(nil)
406 case "wq", "x", "wq!":
407 onAppCommand?("app.save")
408 textView.window?.performClose(nil)
409 case "noh", "nohlsearch": break
410 case "s", "&", "&&", "%&&":
411 // The last substitution again; `&&` keeps its flags.
412 guard let last = Self.lastSubstitute else { return }
413 substitute(whole: trimmed.hasPrefix("%"), pattern: last.pattern, replacement: last.replacement, flags: trimmed.hasSuffix("&&") ? last.flags : "")
414 default:
415 if let line = Int(trimmed) {
416 let ns = document.text as NSString
417 var offset = 0
418 for _ in 1..<max(1, line) {
419 let range = ns.lineRange(for: NSRange(location: offset, length: 0))
420 guard NSMaxRange(range) < ns.length else { break }
421 offset = NSMaxRange(range)
422 }
423 setCaret(offset)
424 textView.scrollRangeToVisible(NSRange(location: offset, length: 0))
425 return
426 }
427 if let m = trimmed.firstMatch(of: /^(%?)s\/((?:[^\/\\]|\\.)*)\/((?:[^\/\\]|\\.)*)\/?([gi]*)$/) {
428 Self.lastSubstitute = (String(m.2), String(m.3), String(m.4))
429 substitute(whole: !m.1.isEmpty, pattern: String(m.2), replacement: String(m.3), flags: String(m.4))
430 return
431 }
432 onMessage?("Not an editor command: \(trimmed)")
433 }
434 }
435
436 private func substitute(whole: Bool, pattern: String, replacement: String, flags: String) {
437 let options: NSRegularExpression.Options = flags.contains("i") ? [.caseInsensitive] : []
438 guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
439 onMessage?("Invalid pattern: \(pattern)")
440 return
441 }
442 let ns = document.text as NSString
443 let caret = textView.selectedRange().location
444 let lines = whole ? NSRange(location: 0, length: ns.length) : ns.lineRange(for: NSRange(location: caret, length: 0))
445 var edits: [TextEdit] = []
446 var location = lines.location
447 while location < NSMaxRange(lines) {
448 let line = ns.lineRange(for: NSRange(location: location, length: 0))
449 let matches = regex.matches(in: ns as String, range: line)
450 for m in flags.contains("g") ? matches : Array(matches.prefix(1)) {
451 let template = regex.replacementString(for: m, in: ns as String, offset: 0, template: replacement.replacingOccurrences(of: "\\\\([0-9])", with: "\\$$1", options: .regularExpression))
452 edits.append(TextEdit(range: m.range.location..<NSMaxRange(m.range), replacement: template))
453 }
454 location = NSMaxRange(line)
455 }
456 guard !edits.isEmpty else {
457 onMessage?("Pattern not found: \(pattern)")
458 return
459 }
460 applyEdits(edits)
461 onMessage?("\(edits.count) substitution\(edits.count == 1 ? "" : "s")")
462 }
463
464 /// A block cursor in normal and visual states, a bar in insert state.
465 func updateCursor() {
466 let block = modal && vim.mode != .insert && vim.mode != .replace
467 for view in orgTextViews { view.blockCursor = block }
468 dispatcher.mode = modal ? vim.mode.keymapMode : nil
469 let state = modal ? vim.mode.rawValue : nil
470 if state != reportedMode {
471 reportedMode = state
472 onModeChange?(state)
473 }
474 }
475
476 /// A mouse click leaves visual state, as in evil.
477 func modalMouseDown() {
478 guard modal else { return }
479 vim.reset()
480 visualCaret = nil
481 updateCursor()
482 }
483}
484#endif