Sources/OrgEditorAppKit/OrgEditor+Macros.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgEditorAppKit/OrgEditor+Macros.swift

235 lines · 10447 bytes

12 symbols in this file
  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4
  5/// Keyboard macros as Emacs's kmacro has them, in every preset: keys are recorded as they reach
  6/// `handleChord`, as the Doom preset's `q` records them, and replayed through it. A prompt
  7/// opened while replaying reads its answer from the macro's keys; a command that fails stops
  8/// the macro.
  9extension OrgEditor {
 10    /// The macro being recorded and the last one, shared by every editor as Emacs's are.
 11    static var kmacro = MacroRecorder()
 12
 13    /// Shows `message`; while a macro replays, it is an error that stops it.
 14    func fail(_ message: String) {
 15        onMessage?(message)
 16        if kmacroDepth > 0, macroError == nil { macroError = message }
 17    }
 18
 19    /// Asks through `onPrompt`, recording the answer while a macro records. While one replays,
 20    /// the answer comes from its keys.
 21    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
 22        if kmacroDepth > 0 {
 23            guard let (answer, used) = MacroRecorder.reply(from: macroKeys) else {
 24                // The rest of the macro doesn't answer it: it is the person's to answer.
 25                macroKeys = []
 26                onPrompt?(prompt, reply)
 27                return
 28            }
 29            macroKeys.removeFirst(used)
 30            switch answer {
 31            case .answer(let text): reply(text)
 32            case .quit:
 33                macroError = "Quit"
 34                reply(nil)
 35            }
 36            return
 37        }
 38        let records = Self.kmacro.isRecording
 39        onPrompt?(prompt) { answer in
 40            if records { Self.kmacro.record(answer: answer) }
 41            reply(answer)
 42        }
 43    }
 44
 45    /// The count a macro command runs with: the prefix argument of the keys that ran it, or 1.
 46    private var macroCount: Int { commandKeys == nil ? 1 : dispatcher.argument ?? 1 }
 47
 48    func macroCommand(_ id: String) {
 49        let byKey = commandKeys != nil
 50        do {
 51            switch id {
 52            case "macro.start":
 53                try startMacro()
 54            case "macro.end":
 55                try endMacro(byKey: byKey)
 56            case "macro.call":
 57                // `kmacro-end-and-call-macro`: e runs it again, as C-x e's last key.
 58                if Self.kmacro.isRecording { try endMacro(byKey: byKey) }
 59                let key = commandKeys.flatMap { $0.count > 1 ? $0.last : nil }
 60                callLastMacro(count: macroCount, repeatKey: key)
 61            case "macro.start-or-insert-counter":
 62                if Self.kmacro.isRecording || kmacroDepth > 0 {
 63                    textView.insertText(Self.kmacro.insertCounter(), replacementRange: textView.selectedRange())
 64                } else {
 65                    try startMacro()
 66                }
 67            case "macro.end-or-call":
 68                if Self.kmacro.isRecording { try endMacro(byKey: byKey) } else { callLastMacro(count: macroCount, repeatKey: nil) }
 69            case "macro.name":
 70                nameLastMacro()
 71            case "macro.run":
 72                runNamedMacro(count: macroCount)
 73            default:
 74                let name = String(id.dropFirst(NamedMacros.commandPrefix.count))
 75                guard id.hasPrefix(NamedMacros.commandPrefix), let keys = namedMacros.keys(name) else {
 76                    return fail("No macro named \(name)")
 77                }
 78                playMacro(keys, count: macroCount)
 79            }
 80        } catch let failure as MacroRecorder.Failure {
 81            fail(failure.message)
 82        } catch {
 83            fail("\(error)")
 84        }
 85    }
 86
 87    private func startMacro() throws {
 88        // A macro that starts one while replaying does nothing, as in Emacs.
 89        guard kmacroDepth == 0 else { return }
 90        try Self.kmacro.start()
 91        onMessage?("Defining keyboard macro…")
 92    }
 93
 94    private func endMacro(byKey: Bool) throws {
 95        guard kmacroDepth == 0 else { return }
 96        onMessage?(try Self.kmacro.end(byKey: byKey))
 97    }
 98
 99    func callLastMacro(count: Int, repeatKey: KeyChord?) {
100        let completed: Bool
101        do {
102            completed = playMacro(try Self.kmacro.lastMacro(), count: count)
103        } catch let failure as MacroRecorder.Failure {
104            return fail(failure.message)
105        } catch {
106            return
107        }
108        guard completed, kmacroDepth == 0, let repeatKey else { return }
109        macroRepeatKey = repeatKey
110        onMessage?("(Type \(repeatKey) to repeat macro)")
111    }
112
113    /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a
114    /// round changes nothing. False when a command failed.
115    @discardableResult
116    func playMacro(_ keys: [KeyChord], count: Int) -> Bool {
117        guard kmacroDepth < 20 else {
118            fail("Keyboard macros nest too deeply")
119            return false
120        }
121        let outer = macroKeys
122        kmacroDepth += 1
123        defer {
124            kmacroDepth -= 1
125            macroKeys = outer
126            if kmacroDepth == 0 { macroError = nil }
127        }
128        var rounds = 0
129        var failed = false
130        while count == 0 ? rounds < 100_000 : rounds < count {
131            rounds += 1
132            let before = (document.revision, textView.selectedRange())
133            macroKeys = keys
134            while !macroKeys.isEmpty, macroError == nil {
135                let key = macroKeys.removeFirst()
136                if !handleChord(key) { typeUnhandled(key) }
137            }
138            if macroError != nil {
139                failed = true
140                break
141            }
142            if count == 0, before == (document.revision, textView.selectedRange()) { break }
143        }
144        return !failed
145    }
146
147    /// A replayed key that `handleChord` left to the text system, which gets it as an event.
148    /// ⌘ keys go to the menus.
149    private func typeUnhandled(_ key: KeyChord) {
150        if modal { return insertTyped(key) }
151        guard let event = Self.event(for: key, window: textView.window) else { return }
152        if key.modifiers.contains(.command) {
153            if NSApp.mainMenu?.performKeyEquivalent(with: event) != true { fail("\(key) is undefined") }
154        } else {
155            textView.interpretKeyEvents([event])
156        }
157    }
158
159    /// A key-down event for `key`, the reverse of `KeyEvents.chord`.
160    static func event(for key: KeyChord, window: NSWindow?) -> NSEvent? {
161        let functionKeys: [String: Int] = [
162            "<delete>": NSDeleteFunctionKey, "<left>": NSLeftArrowFunctionKey, "<right>": NSRightArrowFunctionKey,
163            "<up>": NSUpArrowFunctionKey, "<down>": NSDownArrowFunctionKey, "<home>": NSHomeFunctionKey,
164            "<end>": NSEndFunctionKey, "<prior>": NSPageUpFunctionKey, "<next>": NSPageDownFunctionKey,
165        ]
166        let named = ["TAB": "\t", "RET": "\r", "SPC": " ", "ESC": "\u{1b}", "DEL": "\u{7f}"]
167        let characters: String
168        if let text = named[key.key] {
169            characters = text
170        } else if let code = functionKeys[key.key] ?? key.key.firstMatch(of: /^<f(\d+)>$/).flatMap({ Int($0.1) }).map({ NSF1FunctionKey + $0 - 1 }),
171                  let scalar = Unicode.Scalar(code) {
172            characters = String(Character(scalar))
173        } else if key.key.count == 1 {
174            characters = key.key
175        } else {
176            return nil
177        }
178        var flags: NSEvent.ModifierFlags = []
179        if key.modifiers.contains(.control) { flags.insert(.control) }
180        if key.modifiers.contains(.meta) { flags.insert(.option) }
181        if key.modifiers.contains(.shift) || (key.key.count == 1 && key.key.uppercased() == key.key && key.key.lowercased() != key.key) { flags.insert(.shift) }
182        if key.modifiers.contains(.command) { flags.insert(.command) }
183        let code = KeyEvents.named.first { $0.value == key.key }?.key ?? 0
184        return NSEvent.keyEvent(
185            with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: window?.windowNumber ?? 0,
186            context: nil, characters: characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: code
187        )
188    }
189
190    /// While replaying, C-f, C-b, C-n and C-p that can't move are errors, as in Emacs.
191    func checkMovement(_ id: String, from before: NSRange) {
192        let after = textView.selectedRange()
193        let ns = textView.string as NSString
194        let lineStart = { (offset: Int) in ns.lineRange(for: NSRange(location: offset, length: 0)).location }
195        switch id {
196        case "edit.forward-char" where after == before: fail("End of buffer")
197        case "edit.backward-char" where after == before: fail("Beginning of buffer")
198        case "edit.next-line" where NSMaxRange(after) == ns.length && (after == before || lineStart(NSMaxRange(before)) == lineStart(ns.length)):
199            fail("End of buffer")
200        case "edit.previous-line" where after.location == 0 && (after == before || lineStart(before.location) == 0):
201            fail("Beginning of buffer")
202        default: break
203        }
204    }
205
206    /// `kmacro-name-last-macro`, with the name saved in `macros.toml`.
207    private func nameLastMacro() {
208        guard let keys = Self.kmacro.last else { return fail("No keyboard macro defined") }
209        ask(Prompt(key: "macro-name", message: "Name for last kbd macro:")) { [weak self] answer in
210            guard let self, let answer else { return }
211            let name = answer.trimmingCharacters(in: .whitespaces)
212            guard NamedMacros.isValidName(name) else {
213                return self.fail(name.isEmpty ? "No command name given" : "A macro name has letters, digits, - and _ only")
214            }
215            do {
216                try self.namedMacros.name(name, keys)
217                self.onMessage?("Macro \(name) saved in \(NamedMacros.fileName)")
218            } catch {
219                self.fail("\(NamedMacros.fileName) wasn't written: \(error.localizedDescription)")
220            }
221        }
222    }
223
224    /// Runs a named macro picked by name.
225    private func runNamedMacro(count: Int) {
226        let names = namedMacros.names
227        guard !names.isEmpty else { return fail("No named macros") }
228        ask(Prompt(key: "macro", message: "Run macro:", choices: names)) { [weak self] answer in
229            guard let self, let answer else { return }
230            guard let keys = self.namedMacros.keys(answer) else { return self.fail("No macro named \(answer)") }
231            self.playMacro(keys, count: count)
232        }
233    }
234}
235#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