Sources/OrgEditorAppKit/Modal.swift

4b4dc0135e1d59d493a0a49865fcd155aeea59e0
orgstar/Sources/OrgEditorAppKit/Modal.swift history · blame · raw

243 lines · 10528 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4
  5/// Modal editing: keys go to the keymap for the current evil state first (leader keys,
  6/// evil-org's org keys), then to `Vim`.
  7extension OrgEditor {
  8    func handleModal(_ chord: KeyChord) -> Bool {
  9        // ⌘ shortcuts stay with the menus.
 10        if chord.modifiers.contains(.command) { return false }
 11        dispatcher.mode = vim.mode.keymapMode
 12        if !vim.pending.isEmpty, vim.mode != .insert {
 13            return feedVim([chord])
 14        }
 15        switch dispatcher.feed(chord) {
 16        case .pending(let keys):
 17            let next = keymap.continuations(of: keys, mode: dispatcher.mode).map { item in
 18                (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
 19            }
 20            onKeysPending?(KeySequence.format(keys), next)
 21            return true
 22        case .cancelled:
 23            onKeysPending?(nil, [])
 24            return true
 25        case .complete(let keys, let candidates):
 26            if keys.count > 1 { onKeysPending?(nil, []) }
 27            let context = editContext()
 28            if let binding = candidates.first(where: { binding in
 29                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && commandApplies(binding.command, in: context)
 30            }) {
 31                run(binding.command)
 32                updateCursor()
 33                return true
 34            }
 35            return feedVim(keys)
 36        case .undefined(let keys):
 37            onKeysPending?(nil, [])
 38            return feedVim(keys)
 39        case .unbound:
 40            return feedVim([chord])
 41        }
 42    }
 43
 44    /// Plays keys into the engine. False hands a single key in insert state to the text
 45    /// system.
 46    func feedVim(_ keys: [KeyChord]) -> Bool {
 47        for (index, key) in keys.enumerated() {
 48            if vim.mode == .insert, vim.passesThrough(key) {
 49                if keys.count == 1 { return false }
 50                insertTyped(key)
 51                continue
 52            }
 53            let leaving = key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control)
 54            if vim.mode == .insert, leaving, let snapshot = insertSnapshot {
 55                // What was typed since insert state began, for `.`.
 56                if let edit = TextEdit.between(snapshot.text, document.text).first, edit.range.count == 0 {
 57                    vim.inserted(edit.replacement)
 58                }
 59            }
 60            let wasInsert = vim.mode == .insert
 61            let visual = vim.mode == .visual || vim.mode == .visualLine
 62            let caret = visual ? (visualCaret ?? textView.selectedRange().location) : textView.selectedRange().location
 63            let clipboard = NSPasteboard.general.string(forType: .string)
 64            let actions = vim.feed(key, Vim.Context(text: document.text, caret: caret, clipboard: clipboard, halfPage: halfPage))
 65            apply(actions)
 66            if !wasInsert, vim.mode == .insert {
 67                insertSnapshot = (document.text, textView.selectedRange().location)
 68            } else if vim.mode != .insert {
 69                insertSnapshot = nil
 70            }
 71            _ = index
 72        }
 73        updateCursor()
 74        return true
 75    }
 76
 77    private func insertTyped(_ key: KeyChord) {
 78        let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
 79        guard key.modifiers.isEmpty, text.count == 1 else { return }
 80        textView.insertText(text, replacementRange: textView.selectedRange())
 81    }
 82
 83    var halfPage: Int {
 84        guard let scroll = textView.enclosingScrollView, let font = textView.font else { return 15 }
 85        let lineHeight = max(1, font.ascender - font.descender + font.leading)
 86        return max(1, Int(scroll.contentView.bounds.height / lineHeight / 2))
 87    }
 88
 89    private func editContext() -> EditContext {
 90        let selected = textView.selectedRange()
 91        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [selected.location..<NSMaxRange(selected)], options: options)
 92    }
 93
 94    private func commandApplies(_ id: String, in context: EditContext) -> Bool {
 95        if !isOrg, id.hasPrefix("org.") { return false }
 96        return switch EditorCommands.command(id)?.action {
 97        case .text(let command): command.applies(in: context)
 98        default: true
 99        }
100    }
101
102    func apply(_ actions: [Vim.Action]) {
103        for action in actions {
104            switch action {
105            case .edit(let edits, let caret):
106                visualCaret = nil
107                guard textView.isEditable else {
108                    onMessage?("This file is read-only.")
109                    continue
110                }
111                applyEdits(edits)
112                setCaret(caret)
113                textView.scrollRangeToVisible(NSRange(location: min(caret, document.text.utf16.count), length: 0))
114            case .move(let caret):
115                setCaret(caret)
116                visualCaret = caret
117                textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
118            case .select(let range):
119                textView.setSelectedRange(NSRange(range))
120            case .command(let id):
121                run(id)
122            case .undo(let count):
123                for _ in 0..<count { textView.undoManager?.undo() }
124                clampCaret()
125            case .redo(let count):
126                for _ in 0..<count { textView.undoManager?.redo() }
127                clampCaret()
128            case .setClipboard(let text):
129                NSPasteboard.general.clearContents()
130                NSPasteboard.general.setString(text, forType: .string)
131            case .prompt(let kind):
132                prompt(kind)
133            case .message(let text):
134                onMessage?(text)
135            }
136        }
137    }
138
139    private func clampCaret() {
140        guard vim.mode == .normal else { return }
141        let ns = document.text as NSString
142        let caret = min(textView.selectedRange().location, ns.length)
143        let line = ns.lineRange(for: NSRange(location: caret, length: 0))
144        var end = 0
145        ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line)
146        if caret >= end, end > line.location { setCaret(end - 1) }
147    }
148
149    /// `/`, `?` and `:` read their argument in the echo area.
150    private func prompt(_ kind: String) {
151        onPrompt?(Prompt(key: kind, message: kind)) { [weak self] answer in
152            guard let self, let answer, !answer.isEmpty else { return }
153            let caret = self.textView.selectedRange().location
154            let context = Vim.Context(text: self.document.text, caret: caret)
155            if kind == ":" {
156                self.ex(answer)
157            } else {
158                self.apply(self.vim.search(answer, forward: kind == "/", context))
159            }
160            self.updateCursor()
161        }
162    }
163
164    /// The ex commands people reach for: `:w`, `:q`, `:wq`, `:x`, `:N`, `:s` and `:%s`.
165    func ex(_ command: String) {
166        let trimmed = command.trimmingCharacters(in: .whitespaces)
167        switch trimmed {
168        case "w", "write": onAppCommand?("app.save")
169        case "q", "quit", "q!": textView.window?.performClose(nil)
170        case "wq", "x", "wq!":
171            onAppCommand?("app.save")
172            textView.window?.performClose(nil)
173        case "noh", "nohlsearch": break
174        default:
175            if let line = Int(trimmed) {
176                let ns = document.text as NSString
177                var offset = 0
178                for _ in 1..<max(1, line) {
179                    let range = ns.lineRange(for: NSRange(location: offset, length: 0))
180                    guard NSMaxRange(range) < ns.length else { break }
181                    offset = NSMaxRange(range)
182                }
183                setCaret(offset)
184                textView.scrollRangeToVisible(NSRange(location: offset, length: 0))
185                return
186            }
187            if let m = trimmed.firstMatch(of: /^(%?)s\/((?:[^\/\\]|\\.)*)\/((?:[^\/\\]|\\.)*)\/?([gi]*)$/) {
188                substitute(whole: !m.1.isEmpty, pattern: String(m.2), replacement: String(m.3), flags: String(m.4))
189                return
190            }
191            onMessage?("Not an editor command: \(trimmed)")
192        }
193    }
194
195    private func substitute(whole: Bool, pattern: String, replacement: String, flags: String) {
196        let options: NSRegularExpression.Options = flags.contains("i") ? [.caseInsensitive] : []
197        guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
198            onMessage?("Invalid pattern: \(pattern)")
199            return
200        }
201        let ns = document.text as NSString
202        let caret = textView.selectedRange().location
203        let lines = whole ? NSRange(location: 0, length: ns.length) : ns.lineRange(for: NSRange(location: caret, length: 0))
204        var edits: [TextEdit] = []
205        var location = lines.location
206        while location < NSMaxRange(lines) {
207            let line = ns.lineRange(for: NSRange(location: location, length: 0))
208            let matches = regex.matches(in: ns as String, range: line)
209            for m in flags.contains("g") ? matches : Array(matches.prefix(1)) {
210                let template = regex.replacementString(for: m, in: ns as String, offset: 0, template: replacement.replacingOccurrences(of: "\\\\([0-9])", with: "\\$$1", options: .regularExpression))
211                edits.append(TextEdit(range: m.range.location..<NSMaxRange(m.range), replacement: template))
212            }
213            location = NSMaxRange(line)
214        }
215        guard !edits.isEmpty else {
216            onMessage?("Pattern not found: \(pattern)")
217            return
218        }
219        applyEdits(edits)
220        onMessage?("\(edits.count) substitution\(edits.count == 1 ? "" : "s")")
221    }
222
223    /// A block cursor in normal and visual states, a bar in insert state.
224    func updateCursor() {
225        let block = modal && vim.mode != .insert
226        (textView as? OrgTextView)?.blockCursor = block
227        dispatcher.mode = modal ? vim.mode.keymapMode : nil
228        let state = modal ? vim.mode.rawValue : nil
229        if state != reportedMode {
230            reportedMode = state
231            onModeChange?(state)
232        }
233    }
234
235    /// A mouse click leaves visual state, as in evil.
236    func modalMouseDown() {
237        guard modal else { return }
238        vim.reset()
239        visualCaret = nil
240        updateCursor()
241    }
242}
243#endif