Sources/OrgEditorAppKit/Modal.swift

b043ff99fba99e1bab2208d64a2e1cd8fbf80c87
orgstar/Sources/OrgEditorAppKit/Modal.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form