Commit 9c8e4f9667

9c8e4f9667c239dbcda0a122d127aa0620db4d35

parent: c87c64bf22

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 03:27 UTC

Keyboard macros in the Emacs and Mac presets, kept across restarts

C-x (, C-x ), C-x e with e to repeat, C-u counts, F3 and F4 with the
counter, and C-x C-k n in the Emacs preset; Edit > Macros and C-s-r,
C-S-s-r and C-s-m in the Mac preset. Prompts' answers are recorded as
keys and answered from them on replay; a failing command stops replay.
Named macros are saved in macros.toml, reloaded, listed in the palette
and bindable as macro.named.<name>. Same keys on iOS with a hardware
keyboard.

Closes #146

Layout: unified · split

Changed files (26)
Sources/OrgApp/CommandTitles.swift +7 · view
@@ -175,6 +175,7 @@ enum CommandTitles {
175175 String(localized: "Move Table Column Right", comment: "Command title"),
176176 String(localized: "Move Table Row Down", comment: "Command title"),
177177 String(localized: "Move Table Row Up", comment: "Command title"),
178 String(localized: "Name Last Macro…", comment: "Command title"),
178179 String(localized: "Narrow to Block", comment: "Command title"),
179180 String(localized: "Narrow to Subtree", comment: "Command title"),
180181 String(localized: "Narrow to Subtree or Widen", comment: "Command title"),
@@ -250,6 +251,8 @@ enum CommandTitles {
250251 String(localized: "Resolve Open Clocks…", comment: "Command title"),
251252 String(localized: "Resolve Sync Conflicts…", comment: "Command title"),
252253 String(localized: "Revert to File on Disk", comment: "Command title"),
254 String(localized: "Run Last Macro", comment: "Command title"),
255 String(localized: "Run Macro…", comment: "Command title"),
253256 String(localized: "Run Source Block", comment: "Command title"),
254257 String(localized: "Save", comment: "Command title"),
255258 String(localized: "Save All Buffers", comment: "Command title"),
@@ -296,8 +299,12 @@ enum CommandTitles {
296299 String(localized: "Sparse Tree…", comment: "Command title"),
297300 String(localized: "Split Pane Below", comment: "Command title"),
298301 String(localized: "Split Pane Right", comment: "Command title"),
302 String(localized: "Start Macro or Insert Counter", comment: "Command title"),
303 String(localized: "Start Recording Macro", comment: "Command title"),
299304 String(localized: "Start Timer", comment: "Command title"),
300305 String(localized: "Start Timer with Offset…", comment: "Command title"),
306 String(localized: "Stop Macro or Run Last Macro", comment: "Command title"),
307 String(localized: "Stop Recording Macro", comment: "Command title"),
301308 String(localized: "Stop Timer", comment: "Command title"),
302309 String(localized: "Store ID Link", comment: "Command title"),
303310 String(localized: "Store Link", comment: "Command title"),
Sources/OrgApp/ConfigSync.swift +12 −1 · view
@@ -25,6 +25,7 @@ public final class ConfigSync {
2525 @ObservationIgnored private var text: String?
2626 @ObservationIgnored private var configProblems: [String] = []
2727 @ObservationIgnored private var themeProblems: [String] = []
28 @ObservationIgnored private var macroProblems: [String] = []
2829 /// Why the file couldn't be read or written, the last time a setting was to go into it.
2930 @ObservationIgnored private var fileProblem: String?
3031 @ObservationIgnored private var applying = false
@@ -62,6 +63,7 @@ public final class ConfigSync {
6263 let template = UserConfig.template(from: defaults)
6364 if write(template) { text = template }
6465 }
66 loadMacros()
6567 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
6668 MainActor.assumeIsolated { self?.writeBack() }
6769 }
@@ -86,6 +88,7 @@ public final class ConfigSync {
8688 let name = file.lastPathComponent
8789 if name == self.url.lastPathComponent { self.reload() }
8890 if self.isThemeFile(file) { self.readTheme() }
91 if name == NamedMacros.fileName { self.loadMacros() }
8992 self.serial += 1
9093 self.changedFile = (name, self.serial)
9194 }
@@ -105,6 +108,7 @@ public final class ConfigSync {
105108 text = nil
106109 configProblems = []
107110 themeProblems = []
111 macroProblems = []
108112 fileProblem = nil
109113 self.url = url
110114 start(watch: watches)
@@ -124,6 +128,13 @@ public final class ConfigSync {
124128 readTheme()
125129 }
126130
131 /// `macros.toml`, beside the file, into the named macros.
132 private func loadMacros() {
133 let problems = MacroFile.load(from: url.deletingLastPathComponent().appendingPathComponent(NamedMacros.fileName))
134 macroProblems = problems.map { "\(NamedMacros.fileName): \($0)" }
135 updateProblems()
136 }
137
127138 /// `theme-file`, relative to the configuration folder.
128139 private var themeFile: URL? {
129140 guard let name = defaults.string(forKey: "themeFile"), !name.isEmpty else { return nil }
@@ -148,7 +159,7 @@ public final class ConfigSync {
148159 }
149160
150161 private func updateProblems() {
151 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems
162 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems + macroProblems
152163 if all != problems { problems = all }
153164 }
154165
Sources/OrgApp/MacroFile.swift added +41 · view
@@ -0,0 +1,41 @@
1import Foundation
2import OrgCore
3
4/// `macros.toml` in the configuration folder: keyboard macros by name, in a `[macros]` table of
5/// key sequences in the keymap's notation.
6public enum MacroFile {
7 public static var url: URL { UserConfig.file(NamedMacros.fileName) }
8
9 static let header = """
10 # Keyboard macros named with Name Last Macro (C-x C-k n in the Emacs preset). Each runs as
11 # the command macro.named.<name>, which keymap.toml can bind. Keys are in keymap.toml's
12 # notation; a prompt's answer is the keys typed into it, then RET.
13
14 """
15
16 /// Reads the file into `store`, and has `store` write macros named from now on into it.
17 /// The problems found; a missing file is none.
18 @discardableResult
19 public static func load(into store: NamedMacros = .shared, from url: URL = url) -> [String] {
20 store.setSaver { name, keys in try save(name, keys, to: url) }
21 guard let text = try? String(contentsOf: url, encoding: .utf8) else {
22 store.replace([:])
23 return []
24 }
25 var problems: [String] = []
26 do {
27 store.replace(try NamedMacros.parse(text, problems: &problems))
28 } catch {
29 problems.append("\(error)")
30 }
31 return problems
32 }
33
34 /// Writes `name` into the file, keeping what else it holds.
35 public static func save(_ name: String, _ keys: [KeyChord], to url: URL = url) throws {
36 let text = (try? String(contentsOf: url, encoding: .utf8)) ?? header
37 let updated = UserConfig.setting(text, section: NamedMacros.table, key: name, to: .string(KeySequence.format(keys)))
38 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
39 try updated.write(to: url.resolvingSymlinksInPath(), atomically: true, encoding: .utf8)
40 }
41}
Sources/OrgCore/Keymap/KeyboardMacros.swift added +180 · view
@@ -0,0 +1,180 @@
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}
Sources/OrgCore/Keymap/Keymap.swift +32 −1 · view
@@ -205,6 +205,11 @@ public struct KeyDispatcher: Sendable {
205205 public var keymap: Keymap
206206 public var mode: String?
207207 public private(set) var pending: [KeyChord] = []
208 /// The prefix argument of the sequence completed last: the number typed after C-u
209 /// (`C-u 3`), or 4 for each C-u. C-u is `universal-argument` when no binding starts with
210 /// the keys typed: the sequence completes without it, and with this set.
211 public private(set) var argument: Int?
212 private var digits = ""
208213
209214 public init(keymap: Keymap, mode: String? = nil) {
210215 self.keymap = keymap
@@ -212,24 +217,50 @@ public struct KeyDispatcher: Sendable {
212217 }
213218
214219 public static let quit = KeyChord("g", .control)
220 public static let universalArgument = KeyChord("u", .control)
215221
216222 public mutating func feed(_ chord: KeyChord) -> Outcome {
223 if pending.isEmpty { argument = nil }
217224 if !pending.isEmpty, chord == Self.quit {
218225 pending = []
226 digits = ""
219227 return .cancelled
220228 }
229 if !pending.isEmpty, pending.allSatisfy({ $0 == Self.universalArgument }), chord.modifiers.isEmpty, chord.key.count == 1,
230 let digit = chord.key.first, digit.isASCII, digit.isNumber {
231 digits.append(digit)
232 return .pending(pending)
233 }
221234 let sequence = pending + [chord]
222235 if keymap.isPrefix(sequence, mode: mode) {
223236 pending = sequence
224237 return .pending(sequence)
225238 }
226 pending = []
227239 let candidates = keymap.candidates(for: sequence, mode: mode)
240 let universal = sequence.prefix { $0 == Self.universalArgument }.count
241 if candidates.isEmpty, universal > 0, universal < sequence.count {
242 let rest = Array(sequence.dropFirst(universal))
243 if keymap.isPrefix(rest, mode: mode) {
244 pending = sequence
245 return .pending(sequence)
246 }
247 let found = keymap.candidates(for: rest, mode: mode)
248 if !found.isEmpty {
249 argument = Int(digits) ?? (0..<universal).reduce(1) { value, _ in value * 4 }
250 pending = []
251 digits = ""
252 return .complete(rest, found)
253 }
254 }
255 pending = []
256 digits = ""
228257 if !candidates.isEmpty { return .complete(sequence, candidates) }
229258 return sequence.count == 1 ? .unbound : .undefined(sequence)
230259 }
231260
232261 public mutating func reset() {
233262 pending = []
263 digits = ""
264 argument = nil
234265 }
235266}
Sources/OrgCore/Keymap/PresetEmacs.swift +19 · view
@@ -445,6 +445,25 @@ extension KeymapPreset {
445445 [[bind]]
446446 keys = "C-x C-f"
447447 command = "app.quick-open"
448 # Keyboard macros. C-u N before C-x e or <f4> runs the macro N times; C-u alone, 4 times.
449 [[bind]]
450 keys = "C-x ("
451 command = "macro.start"
452 [[bind]]
453 keys = "C-x )"
454 command = "macro.end"
455 [[bind]]
456 keys = "C-x e"
457 command = "macro.call"
458 [[bind]]
459 keys = "<f3>"
460 command = "macro.start-or-insert-counter"
461 [[bind]]
462 keys = "<f4>"
463 command = "macro.end-or-call"
464 [[bind]]
465 keys = "C-x C-k n"
466 command = "macro.name"
448467 [[bind]]
449468 keys = "M-x"
450469 command = "app.palette"
Sources/OrgCore/Keymap/PresetMac.swift +9 · view
@@ -301,6 +301,15 @@ extension KeymapPreset {
301301 [[bind]]
302302 keys = "M-ESC"
303303 command = "editor.complete"
304 [[bind]]
305 keys = "C-s-r"
306 command = "macro.start"
307 [[bind]]
308 keys = "C-S-s-r"
309 command = "macro.end"
310 [[bind]]
311 keys = "C-s-m"
312 command = "macro.call"
304313
305314 """
306315}
Sources/OrgEditorAppKit/EditorCommands.swift +24 −3 · view
@@ -37,7 +37,10 @@ public struct EditorCommand: Sendable {
3737}
3838
3939public enum EditorCommands {
40 public static let all: [EditorCommand] = Commands.everything.map { EditorCommand(id: $0.id, title: $0.title, action: .text($0)) } + [
40 /// Every command, with the named keyboard macros.
41 public static var all: [EditorCommand] { builtIn + namedMacros(NamedMacros.shared) }
42
43 public static let builtIn: [EditorCommand] = Commands.everything.map { EditorCommand(id: $0.id, title: $0.title, action: .text($0)) } + [
4144 EditorCommand(id: "org.cycle", title: "Cycle Visibility", action: .view),
4245 EditorCommand(id: "org.cycle-global", title: "Cycle Global Visibility", action: .view),
4346 EditorCommand(id: "org.fold.toggle", title: "Toggle Fold", action: .view),
@@ -231,8 +234,21 @@ public enum EditorCommands {
231234 EditorCommand(id: "edit.use-selection-for-find", title: "Use Selection for Find", action: .find(.setSearchString)),
232235 EditorCommand(id: "edit.set-mark", title: "Set Mark", action: .mark),
233236 EditorCommand(id: "edit.keyboard-quit", title: "Quit", action: .mark),
237
238 EditorCommand(id: "macro.start", title: "Start Recording Macro", action: .view),
239 EditorCommand(id: "macro.end", title: "Stop Recording Macro", action: .view),
240 EditorCommand(id: "macro.call", title: "Run Last Macro", action: .view),
241 EditorCommand(id: "macro.start-or-insert-counter", title: "Start Macro or Insert Counter", action: .view),
242 EditorCommand(id: "macro.end-or-call", title: "Stop Macro or Run Last Macro", action: .view),
243 EditorCommand(id: "macro.name", title: "Name Last Macro…", action: .view),
244 EditorCommand(id: "macro.run", title: "Run Macro…", action: .view),
234245 ]
235246
247 /// A command for each named macro, titled with its name.
248 public static func namedMacros(_ store: NamedMacros) -> [EditorCommand] {
249 store.names.map { EditorCommand(id: NamedMacros.commandPrefix + $0, title: $0, action: .view) }
250 }
251
236252 private static func movement(_ name: String, _ title: String, _ selector: String) -> EditorCommand {
237253 let extending = String(selector.dropLast()) + "AndModifySelection:"
238254 return EditorCommand(id: "edit.\(name)", title: title, action: .edit(selector: selector, extending: extending))
@@ -242,8 +258,13 @@ public enum EditorCommands {
242258 EditorCommand(id: "edit.\(name)", title: title, action: .edit(selector: selector))
243259 }
244260
245 private static let byID = Dictionary(uniqueKeysWithValues: all.map { ($0.id, $0) })
261 private static let byID = Dictionary(uniqueKeysWithValues: builtIn.map { ($0.id, $0) })
246262
247 public static func command(_ id: String) -> EditorCommand? { byID[id] }
263 /// A command by id; any `macro.named.` id is one, which says so when no macro has its name.
264 public static func command(_ id: String) -> EditorCommand? {
265 if let command = byID[id] { return command }
266 guard id.hasPrefix(NamedMacros.commandPrefix) else { return nil }
267 return EditorCommand(id: id, title: String(id.dropFirst(NamedMacros.commandPrefix.count)), action: .view)
268 }
248269}
249270#endif
Sources/OrgEditorAppKit/Modal.swift +3 −1 · view
@@ -37,6 +37,8 @@ extension OrgEditor {
3737 if binding.command == "org.fill-paragraph", vim.mode == .visual || vim.mode == .visualLine || vim.mode == .visualBlock {
3838 fillVisual()
3939 } else {
40 commandKeys = keys
41 defer { commandKeys = nil }
4042 run(binding.command)
4143 }
4244 updateCursor()
@@ -368,7 +370,7 @@ extension OrgEditor {
368370 if !history, kind == "/" || kind == "?" { return startISearch(forward: kind == "/", vim: true) }
369371 let earlier = Array((Self.promptHistory[kind] ?? []).reversed())
370372 let request = history ? Prompt(key: kind, message: kind, choices: earlier, requireMatch: false) : Prompt(key: kind, message: kind)
371 onPrompt?(request) { [weak self] answer in
373 ask(request) { [weak self] answer in
372374 guard let self, let answer, !answer.isEmpty else { return }
373375 var list = Self.promptHistory[kind] ?? []
374376 list.removeAll { $0 == answer }
Sources/OrgEditorAppKit/OrgEditor+Macros.swift added +235 · view
@@ -0,0 +1,235 @@
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
Sources/OrgEditorAppKit/OrgEditor+Shrink.swift +1 −1 · view
@@ -23,7 +23,7 @@ extension OrgEditor {
2323 case .notInTable: onMessage?("Not in a table")
2424 case .set(let columns, let table): setShrunk(columns, in: table)
2525 case .ask(let table, let current, let max):
26 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
26 ask(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
2727 guard let self, let answer else { return }
2828 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
2929 }
Sources/OrgEditorAppKit/OrgEditor.swift +43 −9 · view
@@ -461,6 +461,16 @@ public final class OrgEditor: NSObject {
461461 var recordingRegister: Character?
462462 var recordedKeys: [KeyChord] = []
463463 var replayingMacro = 0
464 /// Keyboard macros: the keys left in the one being replayed, how deep replays are nested,
465 /// the error that stops them, the key that runs the last one again right after (`e` after
466 /// C-x e), and the keys of the command running, nil when a menu or the palette ran it.
467 var macroKeys: [KeyChord] = []
468 var kmacroDepth = 0
469 var macroError: String?
470 var macroRepeatKey: KeyChord?
471 var commandKeys: [KeyChord]?
472 /// Named macros (`macros.toml`).
473 public var namedMacros = NamedMacros.shared
464474 /// A region is active: movement extends the selection, as after C-SPC in Emacs.
465475 private(set) var markActive = false
466476 /// An incremental search in progress, and whether Vim's `/` or `?` started it.
@@ -482,6 +492,19 @@ public final class OrgEditor: NSObject {
482492 /// Offers a key press to the keymap. False lets the text system have it.
483493 func handleKey(_ event: NSEvent) -> Bool {
484494 guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
495 return handleChord(chord)
496 }
497
498 /// A key, typed or replayed from a keyboard macro. False lets the text system have it.
499 func handleChord(_ chord: KeyChord) -> Bool {
500 if kmacroDepth == 0 { Self.kmacro.record(chord, begins: dispatcher.pending.isEmpty) }
501 if let key = macroRepeatKey {
502 macroRepeatKey = nil
503 if chord == key, dispatcher.pending.isEmpty, isearch == nil {
504 callLastMacro(count: 1, repeatKey: key)
505 return true
506 }
507 }
485508 if isearch != nil, isearchKey(chord) { return true }
486509 if let handled = completionKey(chord) { return handled }
487510 if modal { return handleModal(chord) }
@@ -495,19 +518,27 @@ public final class OrgEditor: NSObject {
495518 return true
496519 case .cancelled:
497520 onKeysPending?(nil, [])
498 onMessage?("Quit")
521 fail("Quit")
499522 return true
500523 case .undefined(let keys):
501524 onKeysPending?(nil, [])
502 onMessage?("\(KeySequence.format(keys)) is undefined")
525 fail("\(KeySequence.format(keys)) is undefined")
503526 return true
504527 case .unbound:
505528 return electricPair(chord) || autoFill(chord)
506529 case .complete(let keys, let candidates):
507 if keys.count > 1 { onKeysPending?(nil, []) }
530 let argument = dispatcher.argument != nil
531 if keys.count > 1 || argument { onKeysPending?(nil, []) }
508532 let context = context()
509533 let runnable = candidates.first { runs($0, in: context) }
510 if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
534 if let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) {
535 // A prefix argument (C-u, C-u 3) counts keyboard macros only.
536 if argument, !binding.command.hasPrefix("macro.") {
537 fail("\(KeySequence.format(keys)) doesn't take a prefix argument")
538 return true
539 }
540 commandKeys = keys
541 defer { commandKeys = nil }
511542 run(binding.command)
512543 return true
513544 }
@@ -566,11 +597,11 @@ public final class OrgEditor: NSObject {
566597 public func run(_ id: String) {
567598 defer { lastCommand = (id, document.revision) }
568599 guard let command = EditorCommands.command(id) else {
569 onMessage?("Unknown command \(id)")
600 fail("Unknown command \(id)")
570601 return
571602 }
572603 if !isOrg, id.hasPrefix("org.") {
573 onMessage?("Not an org file")
604 fail("Not an org file")
574605 return
575606 }
576607 // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
@@ -599,15 +630,18 @@ public final class OrgEditor: NSObject {
599630 case "edit.isearch-backward": startISearch(forward: false)
600631 case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
601632 case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
633 case _ where id.hasPrefix("macro."): macroCommand(id)
602634 default: tableColumnWidth(id)
603635 }
604636 case .edit(let selector, let extending):
637 let before = textView.selectedRange()
605638 if markActive, let extending {
606639 keepMark = true
607640 textView.doCommand(by: NSSelectorFromString(extending))
608641 } else {
609642 textView.doCommand(by: NSSelectorFromString(selector))
610643 }
644 if kmacroDepth > 0 { checkMovement(id, from: before) }
611645 case .find(let action):
612646 let item = NSMenuItem()
613647 item.tag = action.rawValue
@@ -638,7 +672,7 @@ public final class OrgEditor: NSObject {
638672 switch step {
639673 case .commit(let result):
640674 guard textView.isEditable || result.edits.isEmpty else {
641 onMessage?("This file is read-only.")
675 fail("This file is read-only.")
642676 return .failed("read-only")
643677 }
644678 commandEditing = true
@@ -661,11 +695,11 @@ public final class OrgEditor: NSObject {
661695 }
662696 }
663697 case .failed(let message):
664 onMessage?(message)
698 fail(message)
665699 case .external(let request):
666700 if let onExternal { onExternal(request) } else { onMessage?(EmacsFallback.wording("This needs Emacs, which isn't available here.", "This isn't available here.")) }
667701 case .prompt(let prompt):
668 onPrompt?(prompt) { [weak self] answer in
702 ask(prompt) { [weak self] answer in
669703 guard let self else { return }
670704 guard let answer else {
671705 self.onMessage?("Quit")
Sources/Orgstar/ContentView.swift +2 −1 · view
@@ -482,7 +482,8 @@ struct ContentView: View {
482482 }
483483 }
484484 .onChange(of: ConfigSync.shared.changedFile?.serial) {
485 if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
485 // Named macros are commands keymap.toml can bind.
486 if ["keymap.toml", NamedMacros.fileName].contains(ConfigSync.shared.changedFile?.name) { loadKeymap() }
486487 }
487488 .onChange(of: commands.jumpRequest?.id) {
488489 guard let request = commands.jumpRequest else { return }
Sources/Orgstar/OrgstarApp.swift +27 · view
@@ -553,6 +553,7 @@ struct OrgstarApp: App {
553553 CommandGroup(after: .pasteboard) {
554554 Divider()
555555 FindMenu(commands: commands)
556 MacroMenu(commands: commands)
556557 }
557558 CommandGroup(after: .textEditing) {
558559 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
@@ -741,6 +742,32 @@ struct FindMenu: View {
741742 }
742743}
743744
745/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
746struct MacroMenu: View {
747 let commands: AppCommands
748
749 var body: some View {
750 Menu("Macros") {
751 item("Start Recording", "macro.start")
752 item("Stop Recording", "macro.end")
753 item("Run Last Macro", "macro.call")
754 Divider()
755 item("Name Last Macro…", "macro.name")
756 item("Run Macro…", "macro.run")
757 }
758 }
759
760 private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
761 Button {
762 commands.editor?.run(id)
763 } label: {
764 Text(title)
765 if let keys = commands.keyLabel(for: id) { Text(keys) }
766 }
767 .disabled(commands.editor == nil)
768 }
769}
770
744771/// Window ▸ Agenda.
745772struct AgendaMenuItem: View {
746773 @Environment(\.openWindow) private var openWindow
Sources/OrgstarMobile/MobileEditor+Display.swift +1 −1 · view
@@ -16,7 +16,7 @@ extension MobileEditor {
1616 case .notInTable: onMessage?("Not in a table")
1717 case .set(let columns, let table): setShrunk(columns, in: table)
1818 case .ask(let table, let current, let max):
19 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
19 ask(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
2020 guard let self, let answer else { return }
2121 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
2222 }
Sources/OrgstarMobile/MobileEditor+Macros.swift added +255 · view
@@ -0,0 +1,255 @@
1#if os(iOS)
2import OrgCore
3import UIKit
4
5/// Keyboard macros with a hardware keyboard, as on the Mac: keys are recorded as they reach
6/// `handleChord` and replayed through it; a prompt opened while replaying reads its answer from
7/// the macro's keys, and a command that fails stops the macro. Keys the text system types are
8/// typed by the editor while replaying.
9extension MobileEditor {
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 macroKeys = []
25 onPrompt?(prompt, reply)
26 return
27 }
28 macroKeys.removeFirst(used)
29 switch answer {
30 case .answer(let text): reply(text)
31 case .quit:
32 macroError = "Quit"
33 reply(nil)
34 }
35 return
36 }
37 let records = Self.kmacro.isRecording
38 onPrompt?(prompt) { answer in
39 if records { Self.kmacro.record(answer: answer) }
40 reply(answer)
41 }
42 }
43
44 /// The count a macro command runs with: the prefix argument of the keys that ran it, or 1.
45 private var macroCount: Int { commandKeys == nil ? 1 : dispatcher.argument ?? 1 }
46
47 func macroCommand(_ id: String) {
48 let byKey = commandKeys != nil
49 do {
50 switch id {
51 case "macro.start":
52 try startMacro()
53 case "macro.end":
54 try endMacro(byKey: byKey)
55 case "macro.call":
56 if Self.kmacro.isRecording { try endMacro(byKey: byKey) }
57 callLastMacro(count: macroCount, repeatKey: commandKeys.flatMap { $0.count > 1 ? $0.last : nil })
58 case "macro.start-or-insert-counter":
59 if Self.kmacro.isRecording || kmacroDepth > 0 { textView.insertText(Self.kmacro.insertCounter()) } else { try startMacro() }
60 case "macro.end-or-call":
61 if Self.kmacro.isRecording { try endMacro(byKey: byKey) } else { callLastMacro(count: macroCount, repeatKey: nil) }
62 case "macro.name":
63 nameLastMacro()
64 case "macro.run":
65 runNamedMacro(count: macroCount)
66 default:
67 let name = String(id.dropFirst(NamedMacros.commandPrefix.count))
68 guard id.hasPrefix(NamedMacros.commandPrefix), let keys = namedMacros.keys(name) else {
69 return fail("No macro named \(name)")
70 }
71 playMacro(keys, count: macroCount)
72 }
73 } catch let failure as MacroRecorder.Failure {
74 fail(failure.message)
75 } catch {
76 fail("\(error)")
77 }
78 }
79
80 private func startMacro() throws {
81 guard kmacroDepth == 0 else { return }
82 try Self.kmacro.start()
83 onMessage?("Defining keyboard macro…")
84 }
85
86 private func endMacro(byKey: Bool) throws {
87 guard kmacroDepth == 0 else { return }
88 onMessage?(try Self.kmacro.end(byKey: byKey))
89 }
90
91 func callLastMacro(count: Int, repeatKey: KeyChord?) {
92 let completed: Bool
93 do {
94 completed = playMacro(try Self.kmacro.lastMacro(), count: count)
95 } catch let failure as MacroRecorder.Failure {
96 return fail(failure.message)
97 } catch {
98 return
99 }
100 guard completed, kmacroDepth == 0, let repeatKey else { return }
101 macroRepeatKey = repeatKey
102 onMessage?("(Type \(repeatKey) to repeat macro)")
103 }
104
105 /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a
106 /// round changes nothing. False when a command failed.
107 @discardableResult
108 func playMacro(_ keys: [KeyChord], count: Int) -> Bool {
109 guard kmacroDepth < 20 else {
110 fail("Keyboard macros nest too deeply")
111 return false
112 }
113 let outer = macroKeys
114 kmacroDepth += 1
115 defer {
116 kmacroDepth -= 1
117 macroKeys = outer
118 if kmacroDepth == 0 { macroError = nil }
119 }
120 var rounds = 0
121 var failed = false
122 while count == 0 ? rounds < 100_000 : rounds < count {
123 rounds += 1
124 let before = (document.revision, textView.selectedRange)
125 macroKeys = keys
126 while !macroKeys.isEmpty, macroError == nil {
127 let key = macroKeys.removeFirst()
128 if !handleChord(key) { typeUnhandled(key) }
129 }
130 if macroError != nil {
131 failed = true
132 break
133 }
134 if count == 0, before == (document.revision, textView.selectedRange) { break }
135 }
136 return !failed
137 }
138
139 /// A replayed key that `handleChord` left to the text system: typed here.
140 private func typeUnhandled(_ key: KeyChord) {
141 if modal { return insertTyped(key) }
142 if let command = keymap.candidates(for: [key]).first?.command, command.hasPrefix("edit.") {
143 return replayEdit(command)
144 }
145 let ns = textView.textStorage.string as NSString
146 let selected = textView.selectedRange
147 switch (key.key, key.modifiers) {
148 case ("DEL", []): textView.deleteBackward()
149 case ("<delete>", []):
150 if selected.length > 0 { textView.insertText("") } else if selected.location < ns.length {
151 replace(ns.rangeOfComposedCharacterSequence(at: selected.location), with: "")
152 }
153 case ("<left>", []): replayEdit("edit.backward-char")
154 case ("<right>", []): replayEdit("edit.forward-char")
155 case ("<up>", []): replayEdit("edit.previous-line")
156 case ("<down>", []): replayEdit("edit.next-line")
157 default:
158 let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
159 guard key.modifiers.isEmpty || key.modifiers == [.shift], text.count == 1 else { return fail("\(key) is undefined") }
160 textView.insertText(text)
161 }
162 }
163
164 private func replace(_ range: NSRange, with text: String) {
165 textView.selectedRange = range
166 textView.insertText(text)
167 }
168
169 private func setCaret(to offset: Int) {
170 textView.selectedRange = NSRange(location: offset, length: 0)
171 textView.scrollRangeToVisible(textView.selectedRange)
172 }
173
174 /// The text system's editing keys (C-f, C-n, C-k and the like), which it has while typing.
175 /// Moves that can't move are errors, as in Emacs.
176 private func replayEdit(_ id: String) {
177 let ns = textView.textStorage.string as NSString
178 let caret = textView.selectedRange.location
179 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
180 var lineEnd = 0
181 ns.getLineStart(nil, end: nil, contentsEnd: &lineEnd, for: line)
182 let column = caret - line.location
183 switch id {
184 case "edit.forward-char":
185 guard caret < ns.length else { return fail("End of buffer") }
186 setCaret(to: NSMaxRange(ns.rangeOfComposedCharacterSequence(at: caret)))
187 case "edit.backward-char":
188 guard caret > 0 else { return fail("Beginning of buffer") }
189 setCaret(to: ns.rangeOfComposedCharacterSequence(at: caret - 1).location)
190 case "edit.next-line":
191 guard NSMaxRange(line) < ns.length || (NSMaxRange(line) == ns.length && lineEnd < NSMaxRange(line)) else {
192 setCaret(to: ns.length)
193 return fail("End of buffer")
194 }
195 let next = ns.lineRange(for: NSRange(location: NSMaxRange(line), length: 0))
196 var nextEnd = 0
197 ns.getLineStart(nil, end: nil, contentsEnd: &nextEnd, for: next)
198 setCaret(to: min(next.location + column, nextEnd))
199 case "edit.previous-line":
200 guard line.location > 0 else {
201 setCaret(to: 0)
202 return fail("Beginning of buffer")
203 }
204 let previous = ns.lineRange(for: NSRange(location: line.location - 1, length: 0))
205 setCaret(to: min(previous.location + column, line.location - 1))
206 case "edit.beginning-of-line": setCaret(to: line.location)
207 case "edit.end-of-line": setCaret(to: lineEnd)
208 case "edit.beginning-of-buffer": setCaret(to: 0)
209 case "edit.end-of-buffer": setCaret(to: ns.length)
210 case "edit.forward-word", "edit.backward-word":
211 let forward = id == "edit.forward-word"
212 guard let start = textView.selectedTextRange?.end,
213 let position = textView.tokenizer.position(from: start, toBoundary: .word, inDirection: .storage(forward ? .forward : .backward))
214 else { return }
215 setCaret(to: textView.offset(from: textView.beginningOfDocument, to: position))
216 case "edit.delete-char":
217 guard caret < ns.length else { return fail("End of buffer") }
218 replace(ns.rangeOfComposedCharacterSequence(at: caret), with: "")
219 case "edit.kill-line":
220 guard caret < ns.length else { return fail("End of buffer") }
221 replace(NSRange(location: caret, length: caret < lineEnd ? lineEnd - caret : NSMaxRange(line) - caret), with: "")
222 default:
223 fail(Self.unavailable(command: id))
224 }
225 }
226
227 /// `kmacro-name-last-macro`, with the name saved in `macros.toml`.
228 private func nameLastMacro() {
229 guard let keys = Self.kmacro.last else { return fail("No keyboard macro defined") }
230 ask(Prompt(key: "macro-name", message: "Name for last kbd macro:")) { [weak self] answer in
231 guard let self, let answer else { return }
232 let name = answer.trimmingCharacters(in: .whitespaces)
233 guard NamedMacros.isValidName(name) else {
234 return self.fail(name.isEmpty ? "No command name given" : "A macro name has letters, digits, - and _ only")
235 }
236 do {
237 try self.namedMacros.name(name, keys)
238 self.onMessage?("Macro \(name) saved in \(NamedMacros.fileName)")
239 } catch {
240 self.fail("\(NamedMacros.fileName) wasn't written: \(error.localizedDescription)")
241 }
242 }
243 }
244
245 private func runNamedMacro(count: Int) {
246 let names = namedMacros.names
247 guard !names.isEmpty else { return fail("No named macros") }
248 ask(Prompt(key: "macro", message: "Run macro:", choices: names)) { [weak self] answer in
249 guard let self, let answer else { return }
250 guard let keys = self.namedMacros.keys(answer) else { return self.fail("No macro named \(answer)") }
251 self.playMacro(keys, count: count)
252 }
253 }
254}
255#endif
Sources/OrgstarMobile/MobileEditor+Modal.swift +3 −1 · view
@@ -21,6 +21,8 @@ extension MobileEditor {
2121 if let binding = candidates.first(where: { binding in
2222 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
2323 }) {
24 commandKeys = keys
25 defer { commandKeys = nil }
2426 run(binding.command)
2527 updateCursor()
2628 return true
@@ -272,7 +274,7 @@ extension MobileEditor {
272274 private func prompt(_ kind: String, history: Bool = false) {
273275 let earlier = Array((Self.promptHistory[kind] ?? []).reversed())
274276 let request = history ? Prompt(key: kind, message: kind, choices: earlier, requireMatch: false) : Prompt(key: kind, message: kind)
275 onPrompt?(request) { [weak self] answer in
277 ask(request) { [weak self] answer in
276278 guard let self, let answer, !answer.isEmpty else { return }
277279 var list = Self.promptHistory[kind] ?? []
278280 list.removeAll { $0 == answer }
Sources/OrgstarMobile/MobileEditor.swift +39 −7 · view
@@ -70,6 +70,16 @@ final class MobileEditor: NSObject, DocumentBuffer {
7070 var recordingRegister: Character?
7171 var recordedKeys: [KeyChord] = []
7272 var replayingMacro = 0
73 /// Keyboard macros: the keys left in the one being replayed, how deep replays are nested,
74 /// the error that stops them, the key that runs the last one again right after (`e` after
75 /// C-x e), and the keys of the command running, nil when it didn't come from keys.
76 var macroKeys: [KeyChord] = []
77 var kmacroDepth = 0
78 var macroError: String?
79 var macroRepeatKey: KeyChord?
80 var commandKeys: [KeyChord]?
81 /// Named macros (`macros.toml`).
82 var namedMacros = NamedMacros.shared
7383 static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
7484 static var vimClipboardRecord: (text: String, linewise: Bool)?
7585 static var macros: [Character: [KeyChord]] = [:]
@@ -309,7 +319,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
309319 switch step {
310320 case .commit(let result):
311321 guard textView.isEditable || result.edits.isEmpty else {
312 onMessage?("This file is read-only.")
322 fail("This file is read-only.")
313323 return .failed("read-only")
314324 }
315325 commandEditing = true
@@ -333,9 +343,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
333343 }
334344 }
335345 case .failed(let message):
336 onMessage?(message)
346 fail(message)
337347 case .prompt(let prompt):
338 onPrompt?(prompt) { [weak self] answer in
348 ask(prompt) { [weak self] answer in
339349 guard let self else { return }
340350 guard let answer else { return self.onMessage?("Quit") ?? () }
341351 _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
@@ -421,13 +431,14 @@ final class MobileEditor: NSObject, DocumentBuffer {
421431 case "edit.undo": textView.undoManager?.undo()
422432 case "edit.redo": textView.undoManager?.redo()
423433 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
434 case _ where id.hasPrefix("macro."): macroCommand(id)
424435 case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
425436 if let onAppCommand { onAppCommand(id) } else { onMessage?(Self.unavailable(command: id)) }
426437 default:
427438 if let command = Commands.command(id) {
428439 _ = perform(command)
429440 } else {
430 onMessage?(Self.unavailable(command: id))
441 fail(Self.unavailable(command: id))
431442 }
432443 }
433444 }
@@ -499,6 +510,19 @@ final class MobileEditor: NSObject, DocumentBuffer {
499510 func handleKey(_ key: UIKey) -> Bool {
500511 movedByArrow = [.keyboardUpArrow, .keyboardDownArrow, .keyboardLeftArrow, .keyboardRightArrow].contains(key.keyCode)
501512 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
513 return handleChord(chord)
514 }
515
516 /// A key, typed or replayed from a keyboard macro. False lets the text system have it.
517 func handleChord(_ chord: KeyChord) -> Bool {
518 if kmacroDepth == 0 { Self.kmacro.record(chord, begins: dispatcher.pending.isEmpty) }
519 if let key = macroRepeatKey {
520 macroRepeatKey = nil
521 if chord == key, dispatcher.pending.isEmpty, isearch == nil {
522 callLastMacro(count: 1, repeatKey: key)
523 return true
524 }
525 }
502526 if isearch != nil, isearchKey(chord) { return true }
503527 if modal { return handleModal(chord) }
504528 // Option alone types characters unless it begins a binding.
@@ -509,10 +533,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
509533 onMessage?(KeySequence.format(keys) + "-")
510534 return true
511535 case .cancelled:
512 onMessage?("Quit")
536 fail("Quit")
513537 return true
514538 case .undefined(let keys):
515 onMessage?("\(KeySequence.format(keys)) is undefined")
539 fail("\(KeySequence.format(keys)) is undefined")
516540 return true
517541 case .unbound:
518542 return false
@@ -522,8 +546,16 @@ final class MobileEditor: NSObject, DocumentBuffer {
522546 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
523547 }
524548 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
525 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
549 let argument = dispatcher.argument != nil
550 guard let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) else { return false }
551 // A prefix argument (C-u, C-u 3) counts keyboard macros only.
552 if argument, !binding.command.hasPrefix("macro.") {
553 fail("\(KeySequence.format(keys)) doesn't take a prefix argument")
554 return true
555 }
526556 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
557 commandKeys = keys
558 defer { commandKeys = nil }
527559 run(binding.command)
528560 return true
529561 }
Sources/OrgstarMobile/MobileModel.swift +1 · view
@@ -147,6 +147,7 @@ final class MobileModel {
147147 keymap = loaded.keymap
148148 modalKeys = preset.isModal
149149 configProblems += loaded.problems.map { "keymap.toml: " + $0 }
150 configProblems += MacroFile.load().map { "\(NamedMacros.fileName): " + $0 }
150151 let settings = OrgPreferences.orgSettings()
151152 session.defaults = settings
152153 session.options = OrgPreferences.options()
Tests/OrgCoreTests/KeymapTests.swift +28 · view
@@ -228,6 +228,34 @@ struct KeymapTests {
228228 #expect(dispatcher.feed(KeyChord("z")) == .unbound)
229229 }
230230
231 /// C-u is `universal-argument` where no binding starts with the keys typed.
232 @Test func universalArgument() {
233 var dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
234 func feed(_ keys: String) -> KeyDispatcher.Outcome {
235 var outcome = KeyDispatcher.Outcome.unbound
236 for key in KeySequence.parse(keys)! { outcome = dispatcher.feed(key) }
237 return outcome
238 }
239 let callMacro = { (outcome: KeyDispatcher.Outcome) in
240 if case .complete(let keys, let found) = outcome { return keys == KeySequence.parse("C-x e") && found.first?.command == "macro.call" }
241 return false
242 }
243 #expect(callMacro(feed("C-u 1 2 C-x e")))
244 #expect(dispatcher.argument == 12)
245 #expect(callMacro(feed("C-u C-u C-x e")))
246 #expect(dispatcher.argument == 16)
247 #expect(callMacro(feed("C-x e")))
248 #expect(dispatcher.argument == nil)
249 // Bindings that start with C-u keep it, with no argument.
250 guard case .complete(let keys, _) = feed("C-u C-c C-w") else {
251 Issue.record("expected a binding")
252 return
253 }
254 #expect(keys == KeySequence.parse("C-u C-c C-w") && dispatcher.argument == nil)
255 #expect(feed("C-u 3 C-g") == .cancelled)
256 #expect(feed("C-u C-z") == .undefined(KeySequence.parse("C-u C-z")!))
257 }
258
231259 @Test func continuationsListNextKeys() {
232260 let keymap = KeymapPreset.emacs.keymap
233261 let next = keymap.continuations(of: [KeyChord("x", .control)])
Tests/OrgEditorAppKitTests/CommandTitleTests.swift +1 −1 · view
@@ -13,7 +13,7 @@ struct CommandTitleTests {
1313 static func titles() throws -> [String] {
1414 let ios = try String(contentsOf: root.appendingPathComponent("Sources/OrgstarMobile/EditorScreen.swift"), encoding: .utf8)
1515 let iosTitles = ios.matches(of: /\("(?:app|org|edit|editor|view)\.[^"]+", "([^"\\]+)"\)/).map { String($0.1) }
16 return Array(Set(EditorCommands.all.map(\.title) + iosTitles)).sorted()
16 return Array(Set(EditorCommands.builtIn.map(\.title) + iosTitles)).sorted()
1717 }
1818
1919 static func source(_ titles: [String]) -> String {
Tests/OrgEditorAppKitTests/MacroTests.swift added +315 · view
@@ -0,0 +1,315 @@
1import AppKit
2import Foundation
3import OrgCore
4import Testing
5@testable import OrgApp
6@testable import OrgEditorAppKit
7
8/// Keyboard macros in the Emacs and Mac presets: C-x (, C-x ), C-x e and their counts, F3 and
9/// F4, prompts answered from the macro, errors that stop it, and named macros in macros.toml.
10@MainActor
11@Suite(.serialized)
12struct MacroTests {
13
14 /// Types `keys`, in the keymap's notation, as key events.
15 func type(_ h: Harness, _ keys: String) {
16 for key in KeySequence.parse(keys)! {
17 let event = OrgEditor.event(for: key, window: h.window)!
18 if key.modifiers.contains(.command) {
19 _ = h.textView.performKeyEquivalent(with: event)
20 } else {
21 h.textView.keyDown(with: event)
22 }
23 }
24 }
25
26 /// An editor with the Emacs keys, no macro recorded, and the messages it shows.
27 func emacs(_ text: String, caret: Int = 0) -> (Harness, () -> [String]) {
28 OrgEditor.kmacro = MacroRecorder()
29 let h = Harness(text)
30 var messages: [String] = []
31 h.editor.onMessage = { messages.append($0) }
32 h.caret(at: caret)
33 return (h, { messages })
34 }
35
36 @Test func recordStopAndCall() {
37 let (h, messages) = emacs("one\ntwo\nthree\nfour\n")
38 type(h, "C-x ( C-a * SPC C-n C-x )")
39 #expect(h.string == "* one\ntwo\nthree\nfour\n")
40 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-a * SPC C-n"))
41 #expect(messages() == ["Defining keyboard macro…", "Keyboard macro defined"])
42 type(h, "C-x e")
43 #expect(h.string == "* one\n* two\nthree\nfour\n")
44 #expect(messages().last == "(Type e to repeat macro)")
45 // e runs it again right after, and only then.
46 type(h, "e e")
47 #expect(h.string == "* one\n* two\n* three\n* four\n")
48 type(h, "C-a e")
49 #expect(h.string == "* one\n* two\n* three\n* four\ne")
50 }
51
52 @Test func counts() {
53 let (h, _) = emacs("a\nb\nc\nd\ne\nf\ng\nh\n")
54 type(h, "C-x ( C-a - SPC C-n C-x )")
55 type(h, "C-u 2 C-x e")
56 #expect(h.string == "- a\n- b\n- c\nd\ne\nf\ng\nh\n")
57 type(h, "C-u C-x e")
58 #expect(h.string == "- a\n- b\n- c\n- d\n- e\n- f\n- g\nh\n")
59 // 0 runs it until a command fails: C-n on the last line.
60 type(h, "C-u 0 C-x e")
61 #expect(h.string == "- a\n- b\n- c\n- d\n- e\n- f\n- g\n- h\n- ")
62 }
63
64 @Test func endingWithCallRunsTheMacroOnce() {
65 let (h, _) = emacs("x\n")
66 type(h, "C-x ( C-e ! C-x e")
67 #expect(h.string == "x!!\n")
68 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-e !"))
69 }
70
71 @Test func aFailingCommandStopsTheMacro() {
72 let (h, messages) = emacs("ab\ncd\n")
73 OrgEditor.kmacro.last = KeySequence.parse("C-f C-f C-f C-f C-f C-f C-f y")
74 type(h, "C-x e")
75 #expect(h.string == "ab\ncd\n")
76 #expect(h.textView.selectedRange().location == 6)
77 #expect(messages().last == "End of buffer")
78 // Nothing waits for e after an error.
79 type(h, "e")
80 #expect(h.string == "ab\ncd\ne")
81 // So does a key sequence nothing binds.
82 let (other, _) = emacs("text\n")
83 OrgEditor.kmacro.last = KeySequence.parse("C-c C-z z")
84 type(other, "C-x e")
85 #expect(other.string == "text\n")
86 }
87
88 @Test func errorsAsInEmacs() {
89 let (h, messages) = emacs("x\n")
90 type(h, "C-x e")
91 #expect(messages().last == "No kbd macro has been defined")
92 type(h, "C-x )")
93 #expect(messages().last == "Not defining kbd macro")
94 type(h, "C-x ( C-x )")
95 #expect(messages().last == "Ignore empty macro")
96 #expect(OrgEditor.kmacro.last == nil)
97 type(h, "C-x ( C-x (")
98 #expect(messages().last == "Already defining keyboard macro")
99 h.editor.run("macro.end")
100 // A prefix argument counts macros only.
101 type(h, "C-u 3 C-c C-t")
102 #expect(messages().last == "C-c C-t doesn't take a prefix argument")
103 type(h, "C-u C-e")
104 #expect(messages().last == "C-e doesn't take a prefix argument")
105 #expect(h.string == "x\n")
106 // Bindings that start with C-u keep it.
107 type(h, "C-u C-c C-w")
108 #expect(messages().last != "C-c C-w doesn't take a prefix argument")
109 }
110
111 @Test func promptsAnswersAreRecordedAndReplayed() {
112 let (h, _) = emacs("* a\n* b\n* c\n")
113 var asked = 0
114 h.editor.onPrompt = { prompt, reply in
115 asked += 1
116 #expect(prompt.key == "tags")
117 reply("foo:bar")
118 }
119 type(h, "C-x ( C-c C-q C-n C-x )")
120 #expect(asked == 1)
121 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-c C-q f o o : b a r RET C-n"))
122 type(h, "C-u 2 C-x e")
123 #expect(asked == 1)
124 #expect(h.string.components(separatedBy: "\n").filter { $0.hasSuffix(":foo:bar:") }.count == 3)
125 // A cancelled prompt records C-g, which stops the macro when replayed.
126 h.editor.onPrompt = { _, reply in reply(nil) }
127 h.caret(at: 0)
128 type(h, "C-x ( C-c C-q C-x )")
129 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-c C-q C-g"))
130 }
131
132 @Test func f3InsertsTheCounterAndF4EndsOrCalls() {
133 let (h, _) = emacs("")
134 type(h, "<f3> <f3> RET <f4>")
135 #expect(h.string == "0\n")
136 type(h, "<f4> <f4>")
137 #expect(h.string == "0\n1\n2\n")
138 type(h, "C-u <f4>")
139 #expect(h.string == "0\n1\n2\n3\n4\n5\n6\n")
140 }
141
142 @Test func menuCommandsKeepEveryKey() {
143 let (h, _) = emacs("abc\n")
144 h.editor.run("macro.start")
145 type(h, "C-f C-d")
146 h.editor.run("macro.end")
147 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-f C-d"))
148 h.editor.run("macro.call")
149 #expect(h.string == "ac")
150 }
151
152 @Test func macPresetKeys() {
153 let (h, _) = emacs("a\nb\nc\n")
154 h.editor.keymap = KeymapPreset.mac.keymap
155 type(h, "C-s-r - <down> <left> C-S-s-r")
156 #expect(OrgEditor.kmacro.last == KeySequence.parse("- <down> <left>"))
157 type(h, "C-s-m C-s-m")
158 #expect(h.string == "-a\n-b\n-c\n")
159 }
160
161 @Test func doomNormalStateKeys() {
162 let (h, _) = emacs("one two\nthree four\nfive six\n")
163 h.editor.keymap = KeymapPreset.doom.keymap
164 h.editor.modal = true
165 type(h, "C-x ( d w j C-x )")
166 #expect(OrgEditor.kmacro.last == KeySequence.parse("d w j"))
167 type(h, "C-x e e")
168 #expect(h.string == "two\nfour\nsix\n")
169 }
170
171 @Test func namingSavesToTheFileAndLoadsBack() throws {
172 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-macros-\(UUID().uuidString)")
173 defer { try? FileManager.default.removeItem(at: folder) }
174 let file = folder.appendingPathComponent(NamedMacros.fileName)
175 let store = NamedMacros()
176 #expect(MacroFile.load(into: store, from: file).isEmpty)
177 let (h, messages) = emacs("* a\n* b\n")
178 h.editor.namedMacros = store
179 var answers = ["x", "tags-and-next", "bad name"]
180 h.editor.onPrompt = { _, reply in reply(answers.removeFirst()) }
181 type(h, "C-x ( C-c C-q C-n C-x ) C-x C-k n")
182 #expect(messages().last == "Macro tags-and-next saved in macros.toml")
183 let text = try String(contentsOf: file, encoding: .utf8)
184 #expect(text.hasSuffix("[macros]\ntags-and-next = \"C-c C-q x RET C-n\"\n"), "\(text)")
185 type(h, "C-x C-k n")
186 #expect(messages().last == "A macro name has letters, digits, - and _ only")
187
188 let loaded = NamedMacros()
189 #expect(MacroFile.load(into: loaded, from: file).isEmpty)
190 #expect(loaded.names == ["tags-and-next"])
191 #expect(loaded.keys("tags-and-next") == KeySequence.parse("C-c C-q x RET C-n"))
192 // Naming another adds it, keeping the first.
193 try loaded.name("other", KeySequence.parse("C-e")!)
194 var problems: [String] = []
195 #expect(try NamedMacros.parse(String(contentsOf: file, encoding: .utf8), problems: &problems).keys.sorted() == ["other", "tags-and-next"])
196 #expect(problems.isEmpty)
197 }
198
199 @Test func namedMacroBoundInKeymap() throws {
200 let store = NamedMacros()
201 store.replace(["bang": KeySequence.parse("C-e ! C-n")!])
202 let known = Set((EditorCommands.builtIn + EditorCommands.namedMacros(store)).map(\.id))
203 var problems: [String] = []
204 let toml = "[[bind]]\nkeys = \"C-c m\"\ncommand = \"macro.named.bang\"\n[[bind]]\nkeys = \"C-c n\"\ncommand = \"macro.named.missing\"\n"
205 let user = try Keymap(toml: toml, problems: &problems, commands: known)
206 #expect(problems == ["line 4: unknown command macro.named.missing"])
207 let (h, messages) = emacs("a\nb\nc\n")
208 h.editor.namedMacros = store
209 h.editor.keymap = .layered([KeymapPreset.emacs.keymap, user])
210 type(h, "C-c m C-u 2 C-c m")
211 #expect(h.string == "a!\nb!\nc!\n")
212 h.editor.run("macro.named.missing")
213 #expect(messages().last == "No macro named missing")
214 // Run Macro… picks one by name.
215 h.caret(at: 0)
216 h.editor.onPrompt = { prompt, reply in
217 #expect(prompt.choices == ["bang"])
218 reply("bang")
219 }
220 h.editor.run("macro.run")
221 #expect(h.string == "a!!\nb!\nc!\n")
222 }
223
224 @Test func parsingReportsBadEntries() throws {
225 var problems: [String] = []
226 let macros = try NamedMacros.parse("[macros]\nok = \"C-a\"\nbad = \"C-\"\n[other]\nx = 1\n", problems: &problems)
227 #expect(macros == ["ok": [KeyChord("a", .control)]])
228 #expect(problems == ["bad: bad keys", "line 4: unknown table [other]"])
229 }
230
231 @Test func answerKeysRoundTrip() {
232 let text = "Tag one\tand\ntwo é"
233 let keys = MacroRecorder.keys(typing: text) + [KeyChord("RET")]
234 #expect(KeySequence.parse(KeySequence.format(keys)) == keys)
235 #expect(MacroRecorder.reply(from: keys)?.reply == .answer(text))
236 #expect(MacroRecorder.reply(from: KeySequence.parse("a b DEL c RET z")!)! == (.answer("ac"), 5))
237 #expect(MacroRecorder.reply(from: KeySequence.parse("a")!) == nil)
238 }
239
240 // MARK: - Emacs
241
242 struct OracleCase {
243 var text: String
244 var caret: Int
245 var keys: String
246 var count: Int
247 }
248
249 static let oracleCases = [
250 OracleCase(text: "one\ntwo\nthree\nfour", caret: 0, keys: "C-a * SPC C-n", count: 0),
251 OracleCase(text: "* a\n* b\n* c\n", caret: 0, keys: "C-c C-t C-n", count: 2),
252 OracleCase(text: "* a\n* b\n", caret: 0, keys: "C-c C-q f o o RET C-n", count: 2),
253 OracleCase(text: "ab\ncd", caret: 1, keys: "C-f C-f C-f C-f C-f C-f y", count: 1),
254 OracleCase(text: "- a\n- b\n", caret: 0, keys: "C-e SPC x C-n", count: 0),
255 OracleCase(text: "* TODO a\n", caret: 0, keys: "C-c C-t", count: 3),
256 OracleCase(text: "x", caret: 1, keys: "RET * SPC h", count: 2),
257 OracleCase(text: "a b c\nd e f\n", caret: 0, keys: "C-d C-f C-k C-n C-a", count: 4),
258 OracleCase(text: "first\nsecond\n", caret: 12, keys: "C-p C-p C-e .", count: 0),
259 ]
260
261 /// Each case run in Emacs with `execute-kbd-macro` and here with C-u N C-x e: the same
262 /// buffer and point.
263 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
264 func replayMatchesEmacs() throws {
265 let emacs = try Self.runEmacs(Self.oracleCases)
266 for (index, c) in Self.oracleCases.enumerated() {
267 let (h, _) = self.emacs(c.text, caret: c.caret)
268 OrgEditor.kmacro.last = KeySequence.parse(c.keys)
269 type(h, c.count == 1 ? "C-x e" : "C-u \(c.count) C-x e")
270 #expect(h.string == emacs[index].text, "\(c.keys)")
271 #expect(h.textView.selectedRange().location + 1 == emacs[index].point, "\(c.keys)")
272 }
273 }
274
275 static func runEmacs(_ cases: [OracleCase]) throws -> [(text: String, point: Int)] {
276 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-kmacro-\(UUID().uuidString)")
277 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
278 defer { try? FileManager.default.removeItem(at: folder) }
279 func literal(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
280 let forms = cases.map { "(orgstar-case \(literal($0.text)) \($0.caret + 1) \(literal($0.keys)) \($0.count))" }.joined(separator: "\n")
281 let output = folder.appendingPathComponent("out.json")
282 let script = folder.appendingPathComponent("kmacro.el")
283 try """
284 ;;; -*- lexical-binding: t -*-
285 (require 'org)
286 (require 'json)
287 (setq org-todo-keywords '((sequence "TODO" "DONE")) org-log-done nil org-tags-column -77)
288 (setq-default indent-tabs-mode nil)
289 (defvar orgstar-results nil)
290 (defun orgstar-case (text point keys count)
291 (let ((buffer (generate-new-buffer "case")))
292 ;; Keys run in the selected window's buffer.
293 (switch-to-buffer buffer)
294 (insert text)
295 (org-mode)
296 (goto-char point)
297 (condition-case nil (execute-kbd-macro (kbd keys) count) (error nil))
298 (push (list (buffer-substring-no-properties (point-min) (point-max)) (point)) orgstar-results)
299 (kill-buffer buffer)))
300 \(forms)
301 (with-temp-file \(literal(output.path))
302 (insert (json-encode (vconcat (nreverse orgstar-results)))))
303 """.write(to: script, atomically: true, encoding: .utf8)
304 let process = Process()
305 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
306 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "-l", script.path]
307 process.standardInput = FileHandle.nullDevice
308 process.standardOutput = FileHandle.nullDevice
309 process.standardError = FileHandle.nullDevice
310 try process.run()
311 process.waitUntilExit()
312 let results = try JSONSerialization.jsonObject(with: Data(contentsOf: output)) as! [[Any]]
313 return results.map { ($0[0] as! String, $0[1] as! Int) }
314 }
315}
docs/manual/guide/03-keys.org +53 −1 · view
@@ -1,5 +1,5 @@
11#+TITLE: Keys and commands
2#+DESCRIPTION: The three key presets, prefix keys and key hints, the echo area, the command palette, Option as Meta, keymap.toml, Vim editing in the Doom preset, and every binding.
2#+DESCRIPTION: The three key presets, prefix keys and key hints, the echo area, the command palette, Option as Meta, keymap.toml, keyboard macros, Vim editing in the Doom preset, and every binding.
33#+LEDE: Every action in orgstar is a named command; a keymap preset decides which keys run which commands, and keymap.toml lets you change that.
44
55* Commands and keymaps
@@ -291,6 +291,45 @@ Problems are reported in the echo area with the line number, for example =keymap
291291
292292Settings ▸ General ▸ Import from Emacs… reads your Emacs or Doom configuration and offers, among other things, the key bindings it finds: =global-set-key=, =keymap-global-set=, =define-key=, =keymap-set=, =evil-define-key= and Doom's =map!= with =:leader=, =:localleader=, state keywords and =:prefix=. Bindings to commands orgstar has are appended to =keymap.toml= under a =# Imported from Emacs.= comment, leaving out bindings the file already has. Keys written as vectors, such as =[f5]=, are skipped. See [[file:15-alongside-emacs.org][Alongside Emacs]].
293293
294* Keyboard macros
295
296A keyboard macro records the keys you type and plays them back, as Emacs's =kmacro= does. Keys are recorded as they reach the keymap, so a macro holds keys that run commands as well as typed text, and plays them back through the same keymap. The Doom preset's =q= and =@= registers (see [[*Macros][Macros]] under Vim editing) record the same way and are separate from these.
297
298| Emacs | Mac | Edit ▸ Macros | Command | Does |
299|-+-+-+-+-|
300| =C-x (= | =⌃⌘R= | Start Recording | =macro.start= | Starts recording (=kmacro-start-macro=). The echo area shows =Defining keyboard macro…=. |
301| =C-x )= | =⌃⇧⌘R= | Stop Recording | =macro.end= | Stops recording; the keys become the last macro (=kmacro-end-macro=). |
302| =C-x e= | =⌃⌘M= | Run Last Macro | =macro.call= | Plays the last macro, stopping a recording first (=kmacro-end-and-call-macro=). After =C-x e=, =e= plays it again, until another key. |
303| =<f3>= | — | — | =macro.start-or-insert-counter= | Starts recording; while recording or playing, inserts the macro counter and adds one to it (=kmacro-start-macro-or-insert-counter=). The counter starts at 0 with each recording. |
304| =<f4>= | — | — | =macro.end-or-call= | Stops recording, or plays the last macro (=kmacro-end-or-call-macro=). |
305| =C-x C-k n= | — | Name Last Macro… | =macro.name= | Asks for a name and saves the last macro under it in =macros.toml= (=kmacro-name-last-macro=). |
306| — | — | Run Macro… | =macro.run= | Asks for a named macro and plays it. |
307
308In the Doom preset the Emacs keys above that start with =C-x= work in every state. The Edit ▸ Macros menu shows each item's keys in the current preset.
309
310*Counts.* In the Emacs preset, =C-u= /n/ before =C-x e=, =<f4>= or a key bound to a named macro plays it /n/ times; =C-u= alone plays it 4 times and =C-u C-u= 16. =C-u 0= plays it until a command fails, which is how a macro is run down a whole file: record one line's change ending with =C-n=, then =C-u 0 C-x e= stops when =C-n= reaches the last line. A round that changes neither the text nor the caret also stops it. Other commands don't take a prefix argument; =C-u= before one of them shows =… doesn't take a prefix argument= and does nothing. Key sequences that start with =C-u= in the presets, such as =C-u C-c C-w=, are unchanged.
311
312*Prompts.* A question a command asks while recording is answered as usual, and the answer is recorded as the keys that type it followed by =RET=, as in Emacs. When the macro plays, the command reads its answer from those keys instead of asking. Cancelling the question records =C-g=, which stops the macro when it plays.
313
314*Errors.* A command that fails while a macro plays stops it, with the command's message in the echo area, as in Emacs. Failing includes a key sequence nothing binds, =C-g=, editing a read-only file, a command that refuses at the caret, =C-f= at the end of the buffer, =C-b= at its start, =C-n= on the last line and =C-p= on the first.
315
316*What is recorded.* Keys typed in the editor, including =⌘= keys, which replay through the menus; the answers to the editor's questions; and keys typed during incremental search. Commands chosen with the mouse from a menu, the palette or the toolbar are not recorded, nor is what is typed into the palette, Quick Open or the app's own windows and sheets (refile targets, capture, export). Starting or stopping a recording from Edit ▸ Macros keeps every key typed in between.
317
318The last macro and the recording are shared by every buffer, as in Emacs. The last macro is gone when orgstar quits; name it to keep it.
319
320** Named macros
321
322=C-x C-k n= (Edit ▸ Macros ▸ Name Last Macro…) asks for a name of letters, digits, =-= and =_= and writes the last macro into =macros.toml= in the configuration folder, beside =keymap.toml= (see [[file:13-configuration.org][Configuration]]). A named macro is the command =macro.named.=/name/: it is in the command palette under its name, Edit ▸ Macros ▸ Run Macro… plays it, and =keymap.toml= can bind it:
323
324#+BEGIN_SRC toml
325# C-c m plays the macro named done-and-next; C-u 5 C-c m plays it five times.
326[[bind]]
327keys = "C-c m"
328command = "macro.named.done-and-next"
329#+END_SRC
330
331orgstar reloads =macros.toml= when you save it, and reads =keymap.toml= again so that bindings to new names apply.
332
294333* Vim editing (Doom preset)
295334
296335The Doom preset edits modally, as Doom Emacs does with =evil=, =evil-org=, =evil-surround=, =evil-snipe= and =evil-nerd-commenter=. orgstar implements these itself; none of them are Emacs packages running inside it. The caret is a block in normal and visual states and a bar in insert state, and the modeline shows the state.
@@ -745,6 +784,7 @@ With a hardware keyboard, the iOS app runs the preset =keymap= names in the fold
745784- Of the =app.= commands only the clock commands run from keys: =C-c C-x C-i=, =C-c C-x C-o=, =C-c C-x C-q=, =C-c C-x C-j=, =C-c C-x C-x= and =C-c C-x C-z=. Other =app.= keys, and editor commands such as narrowing, show =Not available on iOS yet=.
746785- A sequence of two or more keys whose command cannot run at the caret runs it anyway and shows its message, as on the Mac (for example =Not on a heading=).
747786- A pending prefix shows as a message, without key hints.
787- Keyboard macros work as on the Mac with the Emacs preset's keys (=C-x (=, =C-x )=, =C-x e=, =<f3>=, =<f4>=, =C-x C-k n=) and the named macros in =macros.toml=. While a macro plays, the editor types the keys the text system would have: characters, =RET=, =TAB=, =DEL=, =<delete>=, the arrow keys, and =C-f=, =C-b=, =C-n=, =C-p=, =C-a=, =C-e=, =C-d=, =C-k=, =M-f=, =M-b=, =M-<= and =M->=; other text-system keys stop the macro. =C-n= and =C-p= move by lines of text, not by lines on screen. Macros can't be recorded from the on-screen keyboard or the key bar.
748788
749789The on-screen key bar's buttons run what their Emacs keys run at the caret (Fold is =TAB=, Promote is =M-<left>=, TODO is =C-c C-t=). See [[file:14-ios.org][iOS]].
750790
@@ -1063,6 +1103,17 @@ When a key appears in several rows, it runs the command whose condition holds at
10631103| Truncate or Wrap Long Lines (=editor.toggle-truncate-lines=) | =C-x x t= | — | =SPC t w= (N) | Switches between wrapping and truncating long lines (=toggle-truncate-lines=). |
10641104| Quit orgstar (=app.quit=) | — | — | =SPC q q= (N) | Quits orgstar (=save-buffers-kill-terminal=). |
10651105
1106** Keyboard macros
1107
1108| Command | Emacs | Mac | Doom | What it does |
1109|-+-+-+-+-|
1110| Start Recording Macro (=macro.start=) | =C-x (= | =⌃⌘R= | — | Starts recording keys (=kmacro-start-macro=). |
1111| Stop Recording Macro (=macro.end=) | =C-x )= | =⌃⇧⌘R= | — | Stops recording; the keys become the last macro (=kmacro-end-macro=). |
1112| Run Last Macro (=macro.call=) | =C-x e= | =⌃⌘M= | — | Plays the last macro, stopping a recording first; =e= plays it again; =C-u= /n/ plays it /n/ times (=kmacro-end-and-call-macro=). |
1113| Start Macro or Insert Counter (=macro.start-or-insert-counter=) | =<f3>= | — | — | Starts recording, or while recording or playing inserts the counter (=kmacro-start-macro-or-insert-counter=). |
1114| Stop Macro or Run Last Macro (=macro.end-or-call=) | =<f4>= | — | — | Stops recording, or plays the last macro (=kmacro-end-or-call-macro=). |
1115| Name Last Macro… (=macro.name=) | =C-x C-k n= | — | — | Names the last macro and saves it in =macros.toml= (=kmacro-name-last-macro=). |
1116
10661117** Attachments
10671118
10681119The Emacs keys also work with Control on the last key (=C-c C-a C-a=), as in Org's dispatcher. See [[file:04-outlines.org][Outlines]].
@@ -1142,6 +1193,7 @@ No preset binds these. Run them from the palette or a menu, or bind them in =key
11421193| Edit Config File (=app.edit-config=) | Opens =config.toml= in the editor. =⌥⌘,=. |
11431194| Import from Emacs… (=app.import-emacs=) | Opens Import from Emacs…. |
11441195| Revert to File on Disk (=app.revert=) | Replaces the buffer with the file on disk; unsaved changes go to recovery (=revert-buffer=). |
1196| Run Macro… (=macro.run=) | Asks for a named keyboard macro and plays it. Edit ▸ Macros ▸ Run Macro…. |
11451197| Recovery Versions… (=app.recovery=) | Shows the recovery versions of the file. |
11461198| Resolve Sync Conflicts… (=app.sync-conflicts=) | Shows the file's sync conflict copies to resolve them. |
11471199| Import Table from File… (=app.table-import=) | Asks for a CSV, TSV or space-separated file and inserts it as a table (=org-table-import=). |
docs/manual/guide/13-configuration.org +15 −2 · view
@@ -21,6 +21,7 @@ The folder holds these files:
2121| =keymap.toml= | Your key bindings, on top of the preset | Only by Import from Emacs |
2222| =capture.toml= | Capture templates | Only by Import from Emacs |
2323| =views.toml= | Saved agenda views | No |
24| =macros.toml= | Named keyboard macros | Yes, when you name a macro |
2425| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch |
2526
2627=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way.
@@ -43,7 +44,7 @@ If =config.toml= has a line orgstar can't use, the problem shows in the message
4344- =config.toml: org-agenda-start-day must look like "-3d" or "+0d"=
4445- =config.toml: theme.light.background must be a color such as "#1f2328"=
4546
46A file that isn't valid TOML is reported with its parse error, and none of it applies. =keymap.toml=, =capture.toml= and =views.toml= report their problems the same way when they are read.
47A file that isn't valid TOML is reported with its parse error, and none of it applies. =keymap.toml=, =capture.toml=, =views.toml= and =macros.toml= report their problems the same way when they are read.
4748
4849* The Settings window
4950
@@ -464,7 +465,7 @@ save = "explicit"
464465
465466Earlier versions used keys such as =editor.fill-column= and =agenda.span=. orgstar still reads them. At launch, each such key in the file is renamed in place to its current name and moved to its current section; the rest of the file, and the comments on those lines, stay as they are. When a setting is in the file under both names, the current name wins and the old line is removed. A section the move leaves empty is removed. A file that lacks a whole section (such as =[theme]=) gets that section added at the end.
466467
467* keymap.toml and capture.toml
468* keymap.toml, capture.toml and macros.toml
468469
469470=keymap.toml= holds =[[bind]]= tables with =keys=, =command=, and optionally =mode= and =when=. They layer over the preset chosen in Keys. orgstar reloads the file when it changes. See [[file:03-keys.org][Keys and commands]].
470471
@@ -478,6 +479,18 @@ command = "app.agenda"
478479
479480=views.toml= holds =[[view]]= tables for the agenda; see [[file:07-agenda.org][The agenda]].
480481
482=macros.toml= holds named keyboard macros in a =[macros]= table, one line per macro: the name, then the keys in =keymap.toml='s notation, separated by spaces. Typed text is one key per character, with =SPC= for a space, and a question's answer is the keys that type it followed by =RET=. Name Last Macro… (=C-x C-k n=) adds a line, or replaces the line with the same name, and leaves the rest of the file as it is. orgstar reloads the file when it changes; the iOS app reads it with the folder's other files. Each macro runs as the command =macro.named.=/name/, which =keymap.toml= can bind. See [[file:03-keys.org::*Keyboard macros][Keyboard macros]].
483
484#+BEGIN_SRC toml
485[macros]
486# Marks the heading DONE and moves to the next one.
487done-and-next = "C-c C-t C-n"
488# Adds the tags work and review, answering C-c C-q's question.
489tag-review = "C-c C-q w o r k : r e v i e w RET"
490#+END_SRC
491
492A name has letters, digits, =-= and =_=. A line whose keys can't be read, or a table other than =[macros]=, is reported and skipped.
493
481494* In-file settings
482495
483496Keyword lines in a file set options for that file, as in Emacs. orgstar reads them outside blocks; for =#+STARTUP= only keyword lines count, so a =#+STARTUP= line inside a paragraph or a block changes nothing: not folding, logging or inline images.
docs/manual/guide/15-alongside-emacs.org +1 · view
@@ -254,6 +254,7 @@ Other:
254254- Line numbers are on the Mac only. Visual line numbers count the screen lines in view; with the caret scrolled out of view they count lines of the file.
255255- Incremental search doesn't save the mark where it began, and has no =M-e= editing, =C-w= or =C-y= yanking into the string, or search ring beyond the last search.
256256- =auto-fill-mode= fills on a typed space only, not on =RET=.
257- Keyboard macros (see [[file:03-keys.org][Keys and commands]]): the prefix argument counts macros only; =C-u= before another command does nothing and says so. =C-u C-x (= and =C-u <f3>= (append to the last macro), the macro ring (=C-x C-k C-n=, =C-x C-k C-p=), the counter commands other than =<f3>= (=C-x C-k C-c=, =C-x C-k C-f=), =C-x C-k e= (editing a macro), =C-x C-k b= (binding a key), =C-x C-k r= (running on each line of the region) and =C-x q= (query) aren't supported. A named macro is saved in =macros.toml= rather than written with =insert-kbd-macro=. Commands run from a menu or the palette while recording aren't recorded; Emacs records =M-x= and its answer.
257258- The agenda's text search (see [[file:07-agenda.org][The agenda]]) covers the agenda files only: =org-agenda-text-search-extra-files= and =org-agenda-search-view-max-outline-level= aren't supported. It runs from the view menu rather than the dispatcher's =s= and =S=, and the search view's =[=, =]=, ={= and =}= keys, which add words and regexps to the search, aren't supported.
258259- In regexps, =\<=, =\>= and =\b= use Org's word syntax but don't find a word boundary where the script changes between two word characters, as Emacs does (for example between an emoji and a letter).
259260- org-roam: nodes come from orgstar's index, not org-roam's database, so =ROAM_ALIASES=, =ROAM_REFS=, =ROAM_EXCLUDE=, and node tags in the chooser aren't supported; the graph is orgstar's own (see [[file:09-links.org][Links]]), not org-roam-ui's. Insert Node Link… and Find Node… make a new node from a title that isn't found with org-roam's default template only, and file it at once rather than in a capture buffer. Daily notes use the first of =org-roam-dailies-capture-templates=, without choosing among several, and the date prompt prefers future dates, where org-roam prefers past ones. Capturing to a daily note files the entry at once rather than in a capture buffer.
l10n/Localizable.xcstrings +347 · view
@@ -21604,6 +21604,40 @@
2160421604 }
2160521605 }
2160621606 },
21607 "Macros": {
21608 "localizations": {
21609 "de": {
21610 "stringUnit": {
21611 "state": "translated",
21612 "value": "Makros"
21613 }
21614 },
21615 "es": {
21616 "stringUnit": {
21617 "state": "translated",
21618 "value": "Macros"
21619 }
21620 },
21621 "fr": {
21622 "stringUnit": {
21623 "state": "translated",
21624 "value": "Macros"
21625 }
21626 },
21627 "ja": {
21628 "stringUnit": {
21629 "state": "translated",
21630 "value": "マクロ"
21631 }
21632 },
21633 "pt-BR": {
21634 "stringUnit": {
21635 "state": "translated",
21636 "value": "Macros"
21637 }
21638 }
21639 }
21640 },
2160721641 "Makes notes.org in a folder you choose or make in iCloud Drive and adds the folder": {
2160821642 "localizations": {
2160921643 "de": {
@@ -22943,6 +22977,41 @@
2294322977 }
2294422978 }
2294522979 },
22980 "Name Last Macro…": {
22981 "comment": "Command title",
22982 "localizations": {
22983 "de": {
22984 "stringUnit": {
22985 "state": "translated",
22986 "value": "Letztes Makro benennen …"
22987 }
22988 },
22989 "es": {
22990 "stringUnit": {
22991 "state": "translated",
22992 "value": "Nombrar última macro…"
22993 }
22994 },
22995 "fr": {
22996 "stringUnit": {
22997 "state": "translated",
22998 "value": "Nommer la dernière macro…"
22999 }
23000 },
23001 "ja": {
23002 "stringUnit": {
23003 "state": "translated",
23004 "value": "最後のマクロに名前を付ける…"
23005 }
23006 },
23007 "pt-BR": {
23008 "stringUnit": {
23009 "state": "translated",
23010 "value": "Nomear Última Macro…"
23011 }
23012 }
23013 }
23014 },
2294623015 "Name for this view:": {
2294723016 "localizations": {
2294823017 "de": {
@@ -32253,6 +32322,76 @@
3225332322 }
3225432323 }
3225532324 },
32325 "Run Last Macro": {
32326 "comment": "Command title",
32327 "localizations": {
32328 "de": {
32329 "stringUnit": {
32330 "state": "translated",
32331 "value": "Letztes Makro ausführen"
32332 }
32333 },
32334 "es": {
32335 "stringUnit": {
32336 "state": "translated",
32337 "value": "Ejecutar última macro"
32338 }
32339 },
32340 "fr": {
32341 "stringUnit": {
32342 "state": "translated",
32343 "value": "Exécuter la dernière macro"
32344 }
32345 },
32346 "ja": {
32347 "stringUnit": {
32348 "state": "translated",
32349 "value": "最後のマクロを実行"
32350 }
32351 },
32352 "pt-BR": {
32353 "stringUnit": {
32354 "state": "translated",
32355 "value": "Executar Última Macro"
32356 }
32357 }
32358 }
32359 },
32360 "Run Macro…": {
32361 "comment": "Command title",
32362 "localizations": {
32363 "de": {
32364 "stringUnit": {
32365 "state": "translated",
32366 "value": "Makro ausführen …"
32367 }
32368 },
32369 "es": {
32370 "stringUnit": {
32371 "state": "translated",
32372 "value": "Ejecutar macro…"
32373 }
32374 },
32375 "fr": {
32376 "stringUnit": {
32377 "state": "translated",
32378 "value": "Exécuter une macro…"
32379 }
32380 },
32381 "ja": {
32382 "stringUnit": {
32383 "state": "translated",
32384 "value": "マクロを実行…"
32385 }
32386 },
32387 "pt-BR": {
32388 "stringUnit": {
32389 "state": "translated",
32390 "value": "Executar Macro…"
32391 }
32392 }
32393 }
32394 },
3225632395 "Run Source Block": {
3225732396 "comment": "Command title",
3225832397 "localizations": {
@@ -36418,6 +36557,110 @@
3641836557 }
3641936558 }
3642036559 },
36560 "Start Macro or Insert Counter": {
36561 "comment": "Command title",
36562 "localizations": {
36563 "de": {
36564 "stringUnit": {
36565 "state": "translated",
36566 "value": "Makro starten oder Zähler einfügen"
36567 }
36568 },
36569 "es": {
36570 "stringUnit": {
36571 "state": "translated",
36572 "value": "Iniciar macro o insertar contador"
36573 }
36574 },
36575 "fr": {
36576 "stringUnit": {
36577 "state": "translated",
36578 "value": "Démarrer une macro ou insérer le compteur"
36579 }
36580 },
36581 "ja": {
36582 "stringUnit": {
36583 "state": "translated",
36584 "value": "マクロを開始またはカウンタを挿入"
36585 }
36586 },
36587 "pt-BR": {
36588 "stringUnit": {
36589 "state": "translated",
36590 "value": "Iniciar Macro ou Inserir Contador"
36591 }
36592 }
36593 }
36594 },
36595 "Start Recording": {
36596 "localizations": {
36597 "de": {
36598 "stringUnit": {
36599 "state": "translated",
36600 "value": "Aufnahme starten"
36601 }
36602 },
36603 "es": {
36604 "stringUnit": {
36605 "state": "translated",
36606 "value": "Iniciar grabación"
36607 }
36608 },
36609 "fr": {
36610 "stringUnit": {
36611 "state": "translated",
36612 "value": "Démarrer l’enregistrement"
36613 }
36614 },
36615 "ja": {
36616 "stringUnit": {
36617 "state": "translated",
36618 "value": "記録を開始"
36619 }
36620 },
36621 "pt-BR": {
36622 "stringUnit": {
36623 "state": "translated",
36624 "value": "Iniciar Gravação"
36625 }
36626 }
36627 }
36628 },
36629 "Start Recording Macro": {
36630 "comment": "Command title",
36631 "localizations": {
36632 "de": {
36633 "stringUnit": {
36634 "state": "translated",
36635 "value": "Makroaufnahme starten"
36636 }
36637 },
36638 "es": {
36639 "stringUnit": {
36640 "state": "translated",
36641 "value": "Iniciar grabación de macro"
36642 }
36643 },
36644 "fr": {
36645 "stringUnit": {
36646 "state": "translated",
36647 "value": "Démarrer l’enregistrement de la macro"
36648 }
36649 },
36650 "ja": {
36651 "stringUnit": {
36652 "state": "translated",
36653 "value": "マクロの記録を開始"
36654 }
36655 },
36656 "pt-BR": {
36657 "stringUnit": {
36658 "state": "translated",
36659 "value": "Iniciar Gravação de Macro"
36660 }
36661 }
36662 }
36663 },
3642136664 "Start Timer": {
3642236665 "comment": "Command title",
3642336666 "localizations": {
@@ -36664,6 +36907,110 @@
3666436907 }
3666536908 }
3666636909 },
36910 "Stop Macro or Run Last Macro": {
36911 "comment": "Command title",
36912 "localizations": {
36913 "de": {
36914 "stringUnit": {
36915 "state": "translated",
36916 "value": "Makro beenden oder letztes Makro ausführen"
36917 }
36918 },
36919 "es": {
36920 "stringUnit": {
36921 "state": "translated",
36922 "value": "Detener macro o ejecutar última macro"
36923 }
36924 },
36925 "fr": {
36926 "stringUnit": {
36927 "state": "translated",
36928 "value": "Arrêter la macro ou exécuter la dernière"
36929 }
36930 },
36931 "ja": {
36932 "stringUnit": {
36933 "state": "translated",
36934 "value": "マクロを停止または最後のマクロを実行"
36935 }
36936 },
36937 "pt-BR": {
36938 "stringUnit": {
36939 "state": "translated",
36940 "value": "Parar Macro ou Executar Última Macro"
36941 }
36942 }
36943 }
36944 },
36945 "Stop Recording": {
36946 "localizations": {
36947 "de": {
36948 "stringUnit": {
36949 "state": "translated",
36950 "value": "Aufnahme beenden"
36951 }
36952 },
36953 "es": {
36954 "stringUnit": {
36955 "state": "translated",
36956 "value": "Detener grabación"
36957 }
36958 },
36959 "fr": {
36960 "stringUnit": {
36961 "state": "translated",
36962 "value": "Arrêter l’enregistrement"
36963 }
36964 },
36965 "ja": {
36966 "stringUnit": {
36967 "state": "translated",
36968 "value": "記録を停止"
36969 }
36970 },
36971 "pt-BR": {
36972 "stringUnit": {
36973 "state": "translated",
36974 "value": "Parar Gravação"
36975 }
36976 }
36977 }
36978 },
36979 "Stop Recording Macro": {
36980 "comment": "Command title",
36981 "localizations": {
36982 "de": {
36983 "stringUnit": {
36984 "state": "translated",
36985 "value": "Makroaufnahme beenden"
36986 }
36987 },
36988 "es": {
36989 "stringUnit": {
36990 "state": "translated",
36991 "value": "Detener grabación de macro"
36992 }
36993 },
36994 "fr": {
36995 "stringUnit": {
36996 "state": "translated",
36997 "value": "Arrêter l’enregistrement de la macro"
36998 }
36999 },
37000 "ja": {
37001 "stringUnit": {
37002 "state": "translated",
37003 "value": "マクロの記録を停止"
37004 }
37005 },
37006 "pt-BR": {
37007 "stringUnit": {
37008 "state": "translated",
37009 "value": "Parar Gravação de Macro"
37010 }
37011 }
37012 }
37013 },
3666737014 "Stop Timer": {
3666837015 "comment": "Command title",
3666937016 "localizations": {
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