Sources/OrgCore/Keymap/KeyboardMacros.swift
180 lines · 6885 bytes
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/// Macros named with `kmacro-name-last-macro`, kept in `macros.toml` in the configuration
110/// folder. Each runs as the command `macro.named.<name>`, which `keymap.toml` can bind.
111public final class NamedMacros: @unchecked Sendable {
112 public static let shared = NamedMacros()
113 public static let commandPrefix = "macro.named."
114 public static let fileName = "macros.toml"
115 /// The table of `macros.toml` that holds them.
116 public static let table = "macros"
117
118 private let lock = NSLock()
119 private var macros: [String: [KeyChord]] = [:]
120 private var saver: (@Sendable (String, [KeyChord]) throws -> Void)?
121
122 public init() {}
123
124 /// Names, sorted.
125 public var names: [String] {
126 lock.withLock { macros.keys.sorted() }
127 }
128
129 public func keys(_ name: String) -> [KeyChord]? {
130 lock.withLock { macros[name] }
131 }
132
133 /// Replaces every macro, as from the file.
134 public func replace(_ all: [String: [KeyChord]]) {
135 lock.withLock { macros = all }
136 }
137
138 /// Writes a named macro where it is kept; set by the app.
139 public func setSaver(_ saver: (@Sendable (String, [KeyChord]) throws -> Void)?) {
140 lock.withLock { self.saver = saver }
141 }
142
143 /// Names `keys` and writes it with the saver, if there is one.
144 public func name(_ name: String, _ keys: [KeyChord]) throws {
145 let saver = lock.withLock {
146 macros[name] = keys
147 return self.saver
148 }
149 try saver?(name, keys)
150 }
151
152 /// Letters, digits, `-` and `_`, as a TOML key and a command id allow.
153 public static func isValidName(_ name: String) -> Bool {
154 !name.isEmpty && name.unicodeScalars.allSatisfy { $0.isASCII && (CharacterSet.alphanumerics.contains($0) || $0 == "-" || $0 == "_") }
155 }
156
157 /// The `[macros]` table of a `macros.toml`: `name = "keys"`. Entries that can't be used are
158 /// skipped and reported in `problems`; a file that isn't valid TOML throws.
159 public static func parse(_ toml: String, problems: inout [String]) throws -> [String: [KeyChord]] {
160 var result: [String: [KeyChord]] = [:]
161 for table in try TOML.parse(toml) where !(table.name.isEmpty && table.values.isEmpty) {
162 guard table.name == Self.table, !table.isArrayElement else {
163 problems.append("line \(table.line): unknown table [\(table.name)]")
164 continue
165 }
166 for name in table.keys {
167 guard isValidName(name) else {
168 problems.append("\(name): bad name")
169 continue
170 }
171 guard let text = table.values[name]?.string, let keys = KeySequence.parse(text) else {
172 problems.append("\(name): bad keys")
173 continue
174 }
175 result[name] = keys
176 }
177 }
178 return result
179 }
180}