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