Sources/OrgCore/Keymap/KeyboardMacros.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgCore/Keymap/KeyboardMacros.swift

212 lines · 7873 bytes

21 symbols in this file
  1import Foundation
  2
  3/// Emacs's keyboard macros (kmacro): the keys typed while recording, as they reach the keymap,
  4/// with each prompt's answer kept as the keys typed into it and RET. Replaying feeds the keys
  5/// to the same dispatch, and a prompt opened on the way reads its answer from them.
  6public struct MacroRecorder: Sendable {
  7    public struct Failure: Error, Equatable {
  8        public let message: String
  9    }
 10
 11    /// An answer read from a macro's keys.
 12    public enum Reply: Equatable, Sendable {
 13        case answer(String)
 14        /// C-g.
 15        case quit
 16    }
 17
 18    public private(set) var isRecording = false
 19    public private(set) var keys: [KeyChord] = []
 20    /// Where the key sequence being typed began in `keys`.
 21    private var sequenceStart = 0
 22    /// `last-kbd-macro`.
 23    public var last: [KeyChord]?
 24    /// `kmacro-counter`, which F3 inserts and steps while recording or replaying.
 25    public private(set) var counter = 0
 26
 27    public init() {}
 28
 29    /// `kmacro-start-macro`: recording starts, and the counter is 0 again.
 30    public mutating func start() throws {
 31        if isRecording { throw Failure(message: "Already defining keyboard macro") }
 32        isRecording = true
 33        keys = []
 34        sequenceStart = 0
 35        counter = 0
 36    }
 37
 38    /// A key typed while recording; `begins` when it starts a key sequence.
 39    public mutating func record(_ key: KeyChord, begins: Bool) {
 40        guard isRecording else { return }
 41        if begins { sequenceStart = keys.count }
 42        keys.append(key)
 43    }
 44
 45    /// A prompt's answer while recording: its text as typed and RET, or C-g for none.
 46    public mutating func record(answer: String?) {
 47        guard isRecording else { return }
 48        keys += answer.map { Self.keys(typing: $0) + [KeyChord("RET")] } ?? [KeyDispatcher.quit]
 49    }
 50
 51    /// `kmacro-end-macro`. With `byKey`, the key sequence that ended it is left out. The message
 52    /// to show.
 53    public mutating func end(byKey: Bool) throws -> String {
 54        guard isRecording else { throw Failure(message: "Not defining kbd macro") }
 55        isRecording = false
 56        if byKey { keys.removeSubrange(min(sequenceStart, keys.count)...) }
 57        defer { keys = [] }
 58        guard !keys.isEmpty else { return "Ignore empty macro" }
 59        last = keys
 60        return "Keyboard macro defined"
 61    }
 62
 63    /// The last macro, to replay.
 64    public func lastMacro() throws -> [KeyChord] {
 65        guard let last else { throw Failure(message: "No kbd macro has been defined") }
 66        return last
 67    }
 68
 69    /// `kmacro-insert-counter`: the counter's text; the counter steps by one.
 70    public mutating func insertCounter() -> String {
 71        defer { counter += 1 }
 72        return String(counter)
 73    }
 74
 75    /// The keys that type `text`.
 76    public static func keys(typing text: String) -> [KeyChord] {
 77        text.map { character in
 78            switch character {
 79            case " ": KeyChord("SPC")
 80            case "\t": KeyChord("TAB")
 81            case "\n": KeyChord("j", .control)
 82            default: KeyChord(String(character))
 83            }
 84        }
 85    }
 86
 87    /// The answer at the front of `keys`: what they type before RET, or C-g; with the number of
 88    /// keys it used. Nil when neither RET nor C-g comes.
 89    public static func reply(from keys: some Collection<KeyChord>) -> (reply: Reply, used: Int)? {
 90        var text = ""
 91        var used = 0
 92        for key in keys {
 93            used += 1
 94            switch key {
 95            case KeyChord("RET"): return (.answer(text), used)
 96            case KeyDispatcher.quit: return (.quit, used)
 97            case KeyChord("SPC"): text.append(" ")
 98            case KeyChord("TAB"): text.append("\t")
 99            case KeyChord("j", .control): text.append("\n")
100            case KeyChord("DEL"): if !text.isEmpty { text.removeLast() }
101            default:
102                if key.modifiers.isEmpty, key.key.count == 1 { text += key.key }
103            }
104        }
105        return nil
106    }
107}
108
109/// Work a replayed key started that the replay waits for before its next key, as a user
110/// command running. It ends once, with the message it failed with or nil.
111@MainActor
112public final class MacroWait {
113    private var outcome: String??
114    private var waiting: [CheckedContinuation<String?, Never>] = []
115
116    public init() {}
117
118    public func finish(_ failure: String?) {
119        guard outcome == nil else { return }
120        outcome = .some(failure)
121        for continuation in waiting { continuation.resume(returning: failure) }
122        waiting = []
123    }
124
125    /// The failure, once the work has ended.
126    public var value: String? {
127        get async {
128            if let outcome { return outcome }
129            return await withCheckedContinuation { waiting.append($0) }
130        }
131    }
132}
133
134/// Where a macro replay stopped: at its end, with the error that ended it or nil, or at work
135/// it waits for.
136public enum MacroStep {
137    case ended(String?)
138    case waiting(MacroWait)
139}
140
141/// Macros named with `kmacro-name-last-macro`, kept in `macros.toml` in the configuration
142/// folder. Each runs as the command `macro.named.<name>`, which `keymap.toml` can bind.
143public final class NamedMacros: @unchecked Sendable {
144    public static let shared = NamedMacros()
145    public static let commandPrefix = "macro.named."
146    public static let fileName = "macros.toml"
147    /// The table of `macros.toml` that holds them.
148    public static let table = "macros"
149
150    private let lock = NSLock()
151    private var macros: [String: [KeyChord]] = [:]
152    private var saver: (@Sendable (String, [KeyChord]) throws -> Void)?
153
154    public init() {}
155
156    /// Names, sorted.
157    public var names: [String] {
158        lock.withLock { macros.keys.sorted() }
159    }
160
161    public func keys(_ name: String) -> [KeyChord]? {
162        lock.withLock { macros[name] }
163    }
164
165    /// Replaces every macro, as from the file.
166    public func replace(_ all: [String: [KeyChord]]) {
167        lock.withLock { macros = all }
168    }
169
170    /// Writes a named macro where it is kept; set by the app.
171    public func setSaver(_ saver: (@Sendable (String, [KeyChord]) throws -> Void)?) {
172        lock.withLock { self.saver = saver }
173    }
174
175    /// Names `keys` and writes it with the saver, if there is one.
176    public func name(_ name: String, _ keys: [KeyChord]) throws {
177        let saver = lock.withLock {
178            macros[name] = keys
179            return self.saver
180        }
181        try saver?(name, keys)
182    }
183
184    /// Letters, digits, `-` and `_`, as a TOML key and a command id allow.
185    public static func isValidName(_ name: String) -> Bool {
186        !name.isEmpty && name.unicodeScalars.allSatisfy { $0.isASCII && (CharacterSet.alphanumerics.contains($0) || $0 == "-" || $0 == "_") }
187    }
188
189    /// The `[macros]` table of a `macros.toml`: `name = "keys"`. Entries that can't be used are
190    /// skipped and reported in `problems`; a file that isn't valid TOML throws.
191    public static func parse(_ toml: String, problems: inout [String]) throws -> [String: [KeyChord]] {
192        var result: [String: [KeyChord]] = [:]
193        for table in try TOML.parse(toml) where !(table.name.isEmpty && table.values.isEmpty) {
194            guard table.name == Self.table, !table.isArrayElement else {
195                problems.append("line \(table.line): unknown table [\(table.name)]")
196                continue
197            }
198            for name in table.keys {
199                guard isValidName(name) else {
200                    problems.append("\(name): bad name")
201                    continue
202                }
203                guard let text = table.values[name]?.string, let keys = KeySequence.parse(text) else {
204                    problems.append("\(name): bad keys")
205                    continue
206                }
207                result[name] = keys
208            }
209        }
210        return result
211    }
212}
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