Sources/OrgEditorAppKit/Modal.swift

d4c76b8503d7069cc3c2404db3cafc46defe1a9a
orgstar/Sources/OrgEditorAppKit/Modal.swift history · blame · raw

381 lines · 18398 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)?.title ?? $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                run(binding.command)
 38                updateCursor()
 39                return true
 40            }
 41            return feedVim(keys)
 42        case .undefined(let keys):
 43            onKeysPending?(nil, [])
 44            // The leader and Emacs prefixes (C-c, C-x) mean nothing to evil: the sequence is
 45            // undefined, as in Doom. Other prefixes (g, z, [, ]) are evil's too.
 46            if let first = keys.first, first == KeyChord("SPC") || !first.modifiers.isDisjoint(with: [.control, .meta]) {
 47                onMessage?("\(KeySequence.format(keys)) is undefined")
 48                return true
 49            }
 50            return feedVim(keys)
 51        case .unbound:
 52            return feedVim([chord])
 53        }
 54    }
 55
 56    /// Plays keys into the engine. False hands a single key in insert state to the text
 57    /// system.
 58    func feedVim(_ keys: [KeyChord]) -> Bool {
 59        for (index, key) in keys.enumerated() {
 60            if vim.mode == .insert, vim.passesThrough(key) {
 61                if keys.count == 1 { return electricPair(key) }
 62                if !electricPair(key) { insertTyped(key) }
 63                continue
 64            }
 65            let leaving = key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control)
 66            if vim.mode == .insert, leaving, let snapshot = insertSnapshot {
 67                // What was typed since insert state began, for `.`.
 68                if let edit = TextEdit.between(snapshot.text, document.text).first, edit.range.count == 0 {
 69                    vim.inserted(edit.replacement)
 70                }
 71            }
 72            let wasInsert = vim.mode == .insert
 73            let visual = vim.mode == .visual || vim.mode == .visualLine
 74            let caret = visual ? (visualCaret ?? textView.selectedRange().location) : textView.selectedRange().location
 75            if jumpToFileMark(key) { continue }
 76            let clipboard = NSPasteboard.general.string(forType: .string)
 77            var marks = vimMarks
 78            for (name, mark) in Self.fileMarks where mark.owner.editor === self { marks[name] = mark.offset }
 79            if jumpIndex > 0, jumpIndex <= jumpList.count { marks["'"] = jumpList[jumpIndex - 1] }
 80            vim.registers = Self.vimRegisters
 81            vim.clipboardRecord = Self.vimClipboardRecord
 82            let actions = vim.feed(key, Vim.Context(text: document.text, caret: caret, clipboard: clipboard, halfPage: halfPage, marks: marks, visible: visibleText, org: isOrg))
 83            Self.vimRegisters = vim.registers
 84            Self.vimClipboardRecord = vim.clipboardRecord
 85            apply(actions)
 86            if !wasInsert, vim.mode == .insert {
 87                insertSnapshot = (document.text, textView.selectedRange().location)
 88            } else if vim.mode != .insert {
 89                insertSnapshot = nil
 90            }
 91            _ = index
 92        }
 93        updateCursor()
 94        return true
 95    }
 96
 97    /// `'A` or `` `A `` for a file mark in another editor: that editor's buffer shows at the
 98    /// mark. True when the key went there.
 99    private func jumpToFileMark(_ key: KeyChord) -> Bool {
100        guard vim.mode == .normal, vim.pending.count == 1, let quote = vim.pending.first, quote == KeyChord("'") || quote == KeyChord("`"),
101              key.modifiers.isEmpty, key.key.count == 1, let name = key.key.first, name.isUppercase,
102              let mark = Self.fileMarks[name], let owner = mark.owner.editor, owner !== self else { return false }
103        vim.reset()
104        let ns = owner.document.text as NSString
105        var target = min(mark.offset, ns.length)
106        if quote == KeyChord("'") {
107            // The line's first non-blank.
108            target = ns.lineRange(for: NSRange(location: target, length: 0)).location
109            while target < ns.length, ns.character(at: target) == 32 || ns.character(at: target) == 9 { target += 1 }
110        }
111        onJumpToEditor?(owner, target)
112        return true
113    }
114
115    /// Moves marks and jump positions through an edit.
116    func mapVimPositions(through edit: TextEdit) {
117        let owned = Self.fileMarks.filter { $0.value.owner.editor === self }
118        guard !vimMarks.isEmpty || !jumpList.isEmpty || !owned.isEmpty else { return }
119        let names = Array(vimMarks.keys)
120        let fileNames = Array(owned.keys)
121        let positions = names.map { vimMarks[$0]! } + fileNames.map { owned[$0]!.offset } + jumpList
122        let mapped = ViewState(selection: positions.map { $0..<$0 }).mapped(through: [edit]).selection
123        for (i, name) in names.enumerated() { vimMarks[name] = mapped[i].lowerBound }
124        for (i, name) in fileNames.enumerated() { Self.fileMarks[name]?.offset = mapped[names.count + i].lowerBound }
125        jumpList = mapped.dropFirst(names.count + fileNames.count).map { $0.lowerBound }
126    }
127
128    func insertTyped(_ key: KeyChord) {
129        let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
130        guard key.modifiers.isEmpty, text.count == 1 else { return }
131        textView.insertText(text, replacementRange: textView.selectedRange())
132    }
133
134    var halfPage: Int {
135        guard let scroll = textView.enclosingScrollView, let font = textView.font else { return 15 }
136        let lineHeight = max(1, font.ascender - font.descender + font.leading)
137        return max(1, Int(scroll.contentView.bounds.height / lineHeight / 2))
138    }
139
140    /// The text the window shows, from the line at its top to the line at its bottom.
141    var visibleText: Range<Int>? {
142        guard let layout = textView.textLayoutManager, let content = layout.textContentManager, let scroll = textView.enclosingScrollView else { return nil }
143        let bounds = scroll.contentView.bounds
144        let origin = textView.textContainerOrigin
145        let start = content.documentRange.location
146        guard let top = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, bounds.minY - origin.y))) else { return nil }
147        let lower = content.offset(from: start, to: top.rangeInElement.location)
148        let bottom = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, bounds.maxY - origin.y - 1)))
149        let upper = bottom.map { content.offset(from: start, to: $0.rangeInElement.endLocation) } ?? utf16Length
150        return lower..<max(lower, upper)
151    }
152
153    private func editContext() -> EditContext {
154        let selected = textView.selectedRange()
155        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [selected.location..<NSMaxRange(selected)], options: options)
156    }
157
158    private func modalRuns(_ binding: KeyBinding, in context: EditContext) -> Bool {
159        (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && commandApplies(binding.command, in: context)
160    }
161
162    private func commandApplies(_ id: String, in context: EditContext) -> Bool {
163        if !isOrg, id.hasPrefix("org.") { return false }
164        return switch EditorCommands.command(id)?.action {
165        case .text(let command): command.applies(in: context)
166        default: true
167        }
168    }
169
170    func apply(_ actions: [Vim.Action]) {
171        for action in actions {
172            switch action {
173            case .edit(let edits, let caret):
174                visualCaret = nil
175                guard textView.isEditable else {
176                    onMessage?("This file is read-only.")
177                    continue
178                }
179                applyEdits(edits)
180                setCaret(caret)
181                textView.scrollRangeToVisible(NSRange(location: min(caret, document.text.utf16.count), length: 0))
182            case .move(let caret):
183                setCaret(caret)
184                visualCaret = caret
185                textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
186            case .select(let range):
187                textView.setSelectedRange(NSRange(range))
188            case .command(let id):
189                run(id)
190            case .visualLines(let count):
191                for _ in 0..<abs(count) {
192                    if count > 0 { textView.moveDown(nil) } else { textView.moveUp(nil) }
193                }
194                clampCaret()
195            case .undo(let count):
196                for _ in 0..<count { textView.undoManager?.undo() }
197                clampCaret()
198            case .redo(let count):
199                for _ in 0..<count { textView.undoManager?.redo() }
200                clampCaret()
201            case .setClipboard(let text):
202                NSPasteboard.general.clearContents()
203                NSPasteboard.general.setString(text, forType: .string)
204            case .prompt(let kind):
205                prompt(kind)
206            case .ex(let command):
207                ex(command)
208            case .fill(let range, let keep):
209                visualCaret = nil
210                textView.setSelectedRange(NSRange(location: textView.selectedRange().location, length: 0))
211                _ = perform(FillRegion(range: range, keep: keep))
212                clampCaret()
213            case .message(let text):
214                onMessage?(text)
215            case .setMark(let name, let offset):
216                if name.isUppercase { Self.fileMarks[name] = (WeakEditor(editor: self), offset) } else { vimMarks[name] = offset }
217            case .jumped(let from):
218                // A new jump drops the ones C-o went back past.
219                jumpList = Array(jumpList.prefix(jumpIndex))
220                if jumpList.last != from { jumpList.append(from) }
221                if jumpList.count > 100 { jumpList.removeFirst(jumpList.count - 100) }
222                jumpIndex = jumpList.count
223            case .jumpBack(let count):
224                // Leaving the newest place keeps it, so C-i comes back to it.
225                if jumpIndex == jumpList.count {
226                    jumpList.append(textView.selectedRange().location)
227                    jumpIndex = jumpList.count - 1
228                }
229                guard jumpIndex - count >= 0 else { continue }
230                jumpIndex -= count
231                reveal(jumpList[jumpIndex])
232            case .jumpForward(let count):
233                guard jumpIndex + count < jumpList.count else { continue }
234                jumpIndex += count
235                reveal(jumpList[jumpIndex])
236            case .recordMacro(let name):
237                if let name {
238                    recordingRegister = name
239                    recordedKeys = []
240                    onMessage?("Defining keyboard macro…")
241                } else if let register = recordingRegister {
242                    // Without the `q` that ended it.
243                    Self.macros[register] = Array(recordedKeys.dropLast())
244                    recordingRegister = nil
245                    onMessage?("Keyboard macro defined")
246                }
247            case .playMacro(let name, let count):
248                guard let keys = Self.macros[name], !keys.isEmpty else {
249                    onMessage?("No macro in register \(name)")
250                    continue
251                }
252                guard replayingMacro < 20 else { continue }
253                replayingMacro += 1
254                defer { replayingMacro -= 1 }
255                for _ in 0..<count {
256                    for key in keys where !handleModal(key) {
257                        // Printable keys in insert state type, as the text system would.
258                        insertTyped(key)
259                    }
260                }
261            case .selectBlock(let ranges):
262                textView.setSelectedRanges(ranges.map { NSValue(range: NSRange($0)) }, affinity: .downstream, stillSelecting: false)
263            }
264        }
265    }
266
267    private func clampCaret() {
268        guard vim.mode == .normal else { return }
269        let ns = document.text as NSString
270        let caret = min(textView.selectedRange().location, ns.length)
271        let line = ns.lineRange(for: NSRange(location: caret, length: 0))
272        var end = 0
273        ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line)
274        if caret >= end, end > line.location { setCaret(end - 1) }
275    }
276
277    /// `/`, `?` and `:` read their argument in the echo area.
278    private func prompt(_ kind: String) {
279        onPrompt?(Prompt(key: kind, message: kind)) { [weak self] answer in
280            guard let self, let answer, !answer.isEmpty else { return }
281            let caret = self.textView.selectedRange().location
282            let context = Vim.Context(text: self.document.text, caret: caret)
283            if kind == ":" {
284                self.ex(answer)
285            } else {
286                self.apply(self.vim.search(answer, forward: kind == "/", context))
287            }
288            self.updateCursor()
289        }
290    }
291
292    /// The ex commands people reach for: `:w`, `:q`, `:wq`, `:x`, `:N`, `:s`, `:%s`, `:e FILE`,
293    /// `:bn`, `:bp`, `:bd`, `:b` and `:ls`.
294    func ex(_ command: String) {
295        let trimmed = command.trimmingCharacters(in: .whitespaces)
296        if let m = trimmed.firstMatch(of: #/^e(?:dit)?!?\s+(.+)$/#) {
297            onOpenFile?(String(m.1).trimmingCharacters(in: .whitespaces))
298            return
299        }
300        switch trimmed {
301        case "w", "write": onAppCommand?("app.save")
302        case "bn", "bnext": onAppCommand?("app.buffer.next")
303        case "bp", "bprevious", "bN", "bNext": onAppCommand?("app.buffer.previous")
304        case "bd", "bdelete", "bd!", "bw", "bwipeout": onAppCommand?("app.buffer.kill")
305        case "b", "buffer", "ls", "buffers", "files": onAppCommand?("app.buffer.switch")
306        case "e", "edit", "e!", "edit!": onAppCommand?("app.revert")
307        case "q", "quit", "q!": textView.window?.performClose(nil)
308        case "wq", "x", "wq!":
309            onAppCommand?("app.save")
310            textView.window?.performClose(nil)
311        case "noh", "nohlsearch": break
312        default:
313            if let line = Int(trimmed) {
314                let ns = document.text as NSString
315                var offset = 0
316                for _ in 1..<max(1, line) {
317                    let range = ns.lineRange(for: NSRange(location: offset, length: 0))
318                    guard NSMaxRange(range) < ns.length else { break }
319                    offset = NSMaxRange(range)
320                }
321                setCaret(offset)
322                textView.scrollRangeToVisible(NSRange(location: offset, length: 0))
323                return
324            }
325            if let m = trimmed.firstMatch(of: /^(%?)s\/((?:[^\/\\]|\\.)*)\/((?:[^\/\\]|\\.)*)\/?([gi]*)$/) {
326                substitute(whole: !m.1.isEmpty, pattern: String(m.2), replacement: String(m.3), flags: String(m.4))
327                return
328            }
329            onMessage?("Not an editor command: \(trimmed)")
330        }
331    }
332
333    private func substitute(whole: Bool, pattern: String, replacement: String, flags: String) {
334        let options: NSRegularExpression.Options = flags.contains("i") ? [.caseInsensitive] : []
335        guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
336            onMessage?("Invalid pattern: \(pattern)")
337            return
338        }
339        let ns = document.text as NSString
340        let caret = textView.selectedRange().location
341        let lines = whole ? NSRange(location: 0, length: ns.length) : ns.lineRange(for: NSRange(location: caret, length: 0))
342        var edits: [TextEdit] = []
343        var location = lines.location
344        while location < NSMaxRange(lines) {
345            let line = ns.lineRange(for: NSRange(location: location, length: 0))
346            let matches = regex.matches(in: ns as String, range: line)
347            for m in flags.contains("g") ? matches : Array(matches.prefix(1)) {
348                let template = regex.replacementString(for: m, in: ns as String, offset: 0, template: replacement.replacingOccurrences(of: "\\\\([0-9])", with: "\\$$1", options: .regularExpression))
349                edits.append(TextEdit(range: m.range.location..<NSMaxRange(m.range), replacement: template))
350            }
351            location = NSMaxRange(line)
352        }
353        guard !edits.isEmpty else {
354            onMessage?("Pattern not found: \(pattern)")
355            return
356        }
357        applyEdits(edits)
358        onMessage?("\(edits.count) substitution\(edits.count == 1 ? "" : "s")")
359    }
360
361    /// A block cursor in normal and visual states, a bar in insert state.
362    func updateCursor() {
363        let block = modal && vim.mode != .insert
364        (textView as? OrgTextView)?.blockCursor = block
365        dispatcher.mode = modal ? vim.mode.keymapMode : nil
366        let state = modal ? vim.mode.rawValue : nil
367        if state != reportedMode {
368            reportedMode = state
369            onModeChange?(state)
370        }
371    }
372
373    /// A mouse click leaves visual state, as in evil.
374    func modalMouseDown() {
375        guard modal else { return }
376        vim.reset()
377        visualCaret = nil
378        updateCursor()
379    }
380}
381#endif