Commit 4d8e517de5

4d8e517de5aef10e915fb482735feba5435a4a21

parent: bd275bd1a8

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-27 15:57 UTC

User commands: org.run and keyboard macros

org.run(id) runs a built-in OrgCore command on the text as the user
command has left it and resolves with {text, selection}; later calls
read that text and the command's edits are in it. The changes of every
org.run and the command's own edits apply as one undo step at the base
revision, so an edit made meanwhile still refuses them. A built-in's
prompts go through the command's prompt; its failure rejects with its
message. org.run refuses app.* commands except app.save (saves after
the changes apply), user.* commands, editor commands, and commands that
return .external (Babel, Emacs tables, links, tangling, views).

User commands' prompts go through the editor on the Mac and iOS, so
keyboard macros record their answers. A replaying macro waits for a
user command started by a key to finish before the next key, including
in nested named macros; a failing command stops the macro.

Manual: org.run section, porting table, keyboard macros.

Closes #246

Layout: unified · split

Changed files (17)
Sources/OrgApp/CommandHost.swift +1 · view
@@ -423,6 +423,7 @@ public final class CommandHost {
423423 settings: () => call("settings", null),
424424 prompt: options => call("prompt", typeof options === "string" ? { message: options } : options ?? {}),
425425 message: text => call("message", String(text)),
426 run: id => call("run", String(id)),
426427 fail,
427428 });
428429 }
Sources/OrgApp/DocumentSession.swift +49 −14 · view
@@ -1491,10 +1491,12 @@ public final class DocumentSession {
14911491
14921492 /// Runs a user command on the focused buffer in the background, with `context` the editor's
14931493 /// context at the request's revision; the message comes back through `report`. `file` is
1494 /// the file's path relative to its folder, for `org.file()`. Prompts go to `ask`.
1494 /// the file's path relative to its folder, for `org.file()`. Prompts go to `ask`. `finished`
1495 /// gets the message once the command has ended, nil when its result was applied.
14951496 public func startUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?,
14961497 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
1497 report: @escaping @MainActor (String) -> Void) {
1498 report: @escaping @MainActor (String) -> Void,
1499 finished: @escaping @MainActor (String?) -> Void = { _ in }) {
14981500 userCommandTask?.cancel()
14991501 isRunningUserCommand = true
15001502 let task = Task { await runUserCommand(request, context: context, file: file, ask: ask, report: report) }
@@ -1506,6 +1508,7 @@ public final class DocumentSession {
15061508 isRunningUserCommand = false
15071509 }
15081510 if let message { report(message) }
1511 finished(message)
15091512 }
15101513 }
15111514
@@ -1536,22 +1539,52 @@ public final class DocumentSession {
15361539 final class State {
15371540 var failure: String?
15381541 var quit = false
1542 /// `org.run("app.save")` ran.
1543 var save = false
1544 var buffer: UserCommandState
1545 init(_ buffer: UserCommandState) { self.buffer = buffer }
1546 }
1547 let state = State(UserCommandState(
1548 EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection,
1549 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags),
1550 defaults: entry.buffer.document.defaults))
1551 /// The answer to `prompt`; a canceled prompt throws.
1552 func reply(to prompt: Prompt) async throws -> String {
1553 try await withCheckedThrowingContinuation { continuation in
1554 ask(prompt) { answer in
1555 guard let answer else {
1556 state.quit = true
1557 return continuation.resume(throwing: CommandHost.Failure.script("Quit"))
1558 }
1559 continuation.resume(returning: answer)
1560 }
1561 }
15391562 }
1540 let state = State()
1541 let context = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection,
1542 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags)
15431563 host.calls = { name, value in
1544 if let answer = UserCommandAPI.answer(name, value, context: context, file: file) { return answer }
1564 if let answer = UserCommandAPI.answer(name, value, context: state.buffer.context, file: file) { return answer }
15451565 switch name {
15461566 case "prompt":
15471567 let prompt = UserCommandAPI.prompt(value)
1548 return try await withCheckedThrowingContinuation { continuation in
1549 ask(prompt) { answer in
1550 guard let answer else {
1551 state.quit = true
1552 return continuation.resume(throwing: CommandHost.Failure.script("Quit"))
1553 }
1554 continuation.resume(returning: UserCommandAPI.answer(answer, to: prompt, now: Date(), calendar: context.calendar))
1568 return UserCommandAPI.answer(try await reply(to: prompt), to: prompt, now: Date(), calendar: state.buffer.context.calendar)
1569 case "run":
1570 let id = value as? String ?? ""
1571 if UserCommandAPI.safeAppCommands.contains(id) {
1572 state.save = true
1573 return state.buffer.reply
1574 }
1575 let command: any OrgCommand
1576 switch UserCommandAPI.builtIn(id) {
1577 case .success(let found): command = found
1578 case .failure(let problem): throw CommandHost.Failure.script(problem.message)
1579 }
1580 // A built-in command's prompts go through the same prompt as the command's own.
1581 var answers: [String: String] = [:]
1582 while true {
1583 switch state.buffer.run(command, answers: answers) {
1584 case .commit: return state.buffer.reply
1585 case .failed(let message): throw CommandHost.Failure.script(message)
1586 case .external: throw CommandHost.Failure.script(UserCommandAPI.external(id).message)
1587 case .prompt(let prompt): answers[prompt.key] = try await reply(to: prompt)
15551588 }
15561589 }
15571590 case "message":
@@ -1581,13 +1614,15 @@ public final class DocumentSession {
15811614 }
15821615 if let failure = state.failure { return failure }
15831616 guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") }
1584 switch UserCommandAPI.result(json, in: context) {
1617 switch state.buffer.result(json) {
15851618 case .failure(let problem):
15861619 return "\(command.title): \(problem.message)"
15871620 case .success(let result):
15881621 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the command finished." }
15891622 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
15901623 if !result.edits.isEmpty { changed(entry) }
1624 // A save that fails shows why, as Save does.
1625 if state.save { save(entry) }
15911626 return nil
15921627 }
15931628 #else
Sources/OrgCore/Commands/UserCommandAPI.swift +115 · view
@@ -205,4 +205,119 @@ public enum UserCommandAPI {
205205 let day = String(format: "%04d-%02d-%02d", read.year, read.month, read.day)
206206 return read.timeGiven ? day + String(format: " %02d:%02d", read.hour, read.minute) : day
207207 }
208
209 // MARK: - org.run
210
211 /// The commands of the app `org.run` runs; it refuses the others. An entry may not need a
212 /// window, a sheet or another file, and may not change the text.
213 public static let safeAppCommands: Set<String> = [
214 // Writes the buffer to its own file, as the person's own save would, once the command's
215 // changes are applied; nothing is saved when the command fails.
216 "app.save",
217 ]
218
219 /// The built-in command `org.run(id)` runs, or why it doesn't run `id`. `safeAppCommands`
220 /// are the caller's to handle.
221 public static func builtIn(_ id: String) -> Result<any OrgCommand, Problem> {
222 if id.hasPrefix(UserCommands.commandPrefix) { return .failure(Problem("A user command can't run another: \(id)")) }
223 if id.hasPrefix("app.") { return .failure(Problem("\(id) is a command of the app, which user commands can't run")) }
224 guard let command = Commands.command(id) else { return .failure(Problem("No built-in command \(id)")) }
225 return .success(command)
226 }
227
228 /// Why `org.run(id)` refused a command that asked for work outside the text.
229 public static func external(_ id: String) -> Problem {
230 Problem("\(id) needs work outside the text here (code blocks, Emacs, links, tangling or a view), which org.run doesn't do")
231 }
232}
233
234/// The buffer as a running user command sees it: the text it started with, changed by the
235/// built-in commands it ran with `org.run`. Calls read the current text, the command's
236/// returned edits are in it, and the result is one change from the starting text.
237public struct UserCommandState: Sendable {
238 /// The context the command started with.
239 public let start: EditContext
240 /// The text and selection now.
241 public private(set) var context: EditContext
242 let defaults: OrgSettings
243 /// Effects of the commands run that the result keeps: those without offsets.
244 private var effects: [Effect] = []
245 /// Whether a built-in command ran.
246 private var ran = false
247
248 /// `defaults` are the settings the buffer's tree was parsed with.
249 public init(_ start: EditContext, defaults: OrgSettings) {
250 self.start = start
251 context = start
252 self.defaults = defaults
253 }
254
255 /// Runs `command` at the current text and selection. A commit becomes the current state.
256 public mutating func run(_ command: any OrgCommand, answers: [String: String]) -> CommandStep {
257 let current = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: context.selection,
258 now: context.now, calendar: context.calendar, answers: answers, options: context.options,
259 knownTags: context.knownTags)
260 let step = command.run(in: current)
261 guard case .commit(let result) = step else { return step }
262 var text = context.text
263 var tree = context.tree
264 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
265 tree = OrgParser.reparse(tree, oldText: text, edit: edit, defaults: defaults)
266 text = edit.apply(to: text)
267 }
268 var options = context.options
269 for effect in result.effects {
270 switch effect {
271 case .fold, .sparseTree, .snippet: continue
272 case .timer(let timer): options.timer = timer
273 default: break
274 }
275 effects.append(effect)
276 }
277 context = EditContext(revision: context.revision, text: text, tree: tree,
278 selection: result.selection ?? Self.map(context.selection, through: result.edits),
279 now: context.now, calendar: context.calendar, options: options, knownTags: context.knownTags)
280 ran = true
281 return step
282 }
283
284 /// What `org.run` resolves with: the text and the selections.
285 public var reply: [String: Any] {
286 ["text": context.text, "selection": context.selection.map(UserCommandAPI.range)]
287 }
288
289 /// The command's returned JSON, in the current text, as one result at the starting revision.
290 public func result(_ json: String) -> Result<EditResult, UserCommandAPI.Problem> {
291 let own: EditResult
292 switch UserCommandAPI.result(json, in: context) {
293 case .failure(let problem): return .failure(problem)
294 case .success(let result): own = result
295 }
296 guard ran else { return .success(own) }
297 var text = context.text
298 for edit in own.edits.reversed() { text = edit.apply(to: text) }
299 return .success(EditResult(baseRevision: start.revision, edits: TextEdit.between(start.text, text),
300 selection: own.selection ?? Self.map(context.selection, through: own.edits),
301 effects: effects + own.effects))
302 }
303
304 /// Ranges moved by edits that don't overlap: an offset inside or at the end of a replaced
305 /// range, or at an insertion, moves past the replacement.
306 static func map(_ ranges: [Range<Int>], through edits: [TextEdit]) -> [Range<Int>] {
307 let sorted = edits.sorted { $0.range.lowerBound < $1.range.lowerBound }
308 func map(_ offset: Int) -> Int {
309 var shift = 0
310 for edit in sorted {
311 let lower = edit.range.lowerBound, upper = edit.range.upperBound
312 if offset < lower || (offset == lower && upper > lower) { return offset + shift }
313 if offset <= upper { return lower + shift + edit.replacement.utf16.count }
314 shift += edit.replacement.utf16.count - edit.range.count
315 }
316 return offset + shift
317 }
318 return ranges.map { range in
319 let lower = map(range.lowerBound)
320 return lower..<max(lower, map(range.upperBound))
321 }
322 }
208323}
Sources/OrgCore/Keymap/KeyboardMacros.swift +32 · view
@@ -106,6 +106,38 @@ public struct MacroRecorder: Sendable {
106106 }
107107}
108108
109/// Work a replayed key started that the replay waits for before its next key, as a user
110/// command running. It ends once, with the message it failed with or nil.
111@MainActor
112public final class MacroWait {
113 private var outcome: String??
114 private var waiting: [CheckedContinuation<String?, Never>] = []
115
116 public init() {}
117
118 public func finish(_ failure: String?) {
119 guard outcome == nil else { return }
120 outcome = .some(failure)
121 for continuation in waiting { continuation.resume(returning: failure) }
122 waiting = []
123 }
124
125 /// The failure, once the work has ended.
126 public var value: String? {
127 get async {
128 if let outcome { return outcome }
129 return await withCheckedContinuation { waiting.append($0) }
130 }
131 }
132}
133
134/// Where a macro replay stopped: at its end, with the error that ended it or nil, or at work
135/// it waits for.
136public enum MacroStep {
137 case ended(String?)
138 case waiting(MacroWait)
139}
140
109141/// Macros named with `kmacro-name-last-macro`, kept in `macros.toml` in the configuration
110142/// folder. Each runs as the command `macro.named.<name>`, which `keymap.toml` can bind.
111143public final class NamedMacros: @unchecked Sendable {
Sources/OrgEditorAppKit/OrgEditor+Macros.swift +76 −17 · view
@@ -18,7 +18,7 @@ extension OrgEditor {
1818
1919 /// Asks through `onPrompt`, recording the answer while a macro records. While one replays,
2020 /// the answer comes from its keys.
21 func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
21 public func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
2222 if kmacroDepth > 0 {
2323 guard let (answer, used) = MacroRecorder.reply(from: macroKeys) else {
2424 // The rest of the macro doesn't answer it: it is the person's to answer.
@@ -112,36 +112,95 @@ extension OrgEditor {
112112
113113 /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a
114114 /// round changes nothing. False when a command failed.
115 /// A key that starts a user command leaves the replay waiting until the command has
116 /// finished; it goes on from there.
115117 @discardableResult
116118 func playMacro(_ keys: [KeyChord], count: Int) -> Bool {
117119 guard kmacroDepth < 20 else {
118120 fail("Keyboard macros nest too deeply")
119121 return false
120122 }
121 let outer = macroKeys
123 let replay = MacroReplay(keys: keys, count: count, outer: macroKeys)
124 let outermost = kmacroDepth == 0
122125 kmacroDepth += 1
123 defer {
124 kmacroDepth -= 1
125 macroKeys = outer
126 if kmacroDepth == 0 { macroError = nil }
126 switch replayMacro(replay) {
127 case .ended(let error):
128 return error == nil
129 case .waiting(let wait):
130 // A replay this one runs in waits for the rest of it.
131 let rest = resumeMacro(replay, after: wait)
132 if !outermost { macroWait = rest }
133 return true
127134 }
135 }
136
137 /// Goes on with `replay` each time the work it waits for has finished.
138 private func resumeMacro(_ replay: MacroReplay, after wait: MacroWait) -> MacroWait {
139 let rest = MacroWait()
140 Task { [weak self] in
141 var wait = wait
142 while true {
143 let failure = await wait.value
144 guard let self else { return rest.finish("") }
145 if let failure, self.macroError == nil { self.macroError = failure }
146 switch self.replayMacro(replay) {
147 case .ended(let error): return rest.finish(error)
148 case .waiting(let next): wait = next
149 }
150 }
151 }
152 return rest
153 }
154
155 /// A macro being replayed: the rounds run, and the state the current round started from,
156 /// nil between rounds.
157 final class MacroReplay {
158 let keys: [KeyChord]
159 let count: Int
160 /// The keys left in the replay this one runs in.
161 let outer: [KeyChord]
128162 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
163 var before: (Int, NSRange)?
164
165 init(keys: [KeyChord], count: Int, outer: [KeyChord]) {
166 self.keys = keys
167 self.count = count
168 self.outer = outer
169 }
170 }
171
172 /// Feeds `replay`'s keys through `handleChord` until it ends with the error that stopped it,
173 /// nil when it ran through, or until a key leaves `macroWait` set: the replay waits for
174 /// that work and goes on with the next key.
175 private func replayMacro(_ replay: MacroReplay) -> MacroStep {
176 while true {
177 if replay.before == nil {
178 guard replay.count == 0 ? replay.rounds < 100_000 : replay.rounds < replay.count else { return endReplay(replay) }
179 replay.rounds += 1
180 replay.before = (document.revision, textView.selectedRange())
181 macroKeys = replay.keys
182 }
134183 while !macroKeys.isEmpty, macroError == nil {
135184 let key = macroKeys.removeFirst()
185 macroWait = nil
136186 if !handleChord(key) { typeUnhandled(key) }
187 if let wait = macroWait {
188 macroWait = nil
189 return .waiting(wait)
190 }
137191 }
138 if macroError != nil {
139 failed = true
140 break
141 }
142 if count == 0, before == (document.revision, textView.selectedRange()) { break }
192 if macroError != nil { return endReplay(replay) }
193 if replay.count == 0, let before = replay.before, before == (document.revision, textView.selectedRange()) { return endReplay(replay) }
194 replay.before = nil
143195 }
144 return !failed
196 }
197
198 private func endReplay(_ replay: MacroReplay) -> MacroStep {
199 let error = macroError
200 kmacroDepth -= 1
201 macroKeys = replay.outer
202 if kmacroDepth == 0 { macroError = nil }
203 return .ended(error)
145204 }
146205
147206 /// A replayed key that `handleChord` left to the text system, which gets it as an event.
Sources/OrgEditorAppKit/OrgEditor.swift +10 · view
@@ -401,6 +401,10 @@ public final class OrgEditor: NSObject {
401401 public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
402402 /// Runs work outside the text, such as a table recalculation in Emacs.
403403 public var onExternal: ((ExternalRequest) -> Void)?
404 /// Runs a user command, calling `finished` with its message once it has ended, nil when its
405 /// result was applied; a keyboard macro replaying waits for that. Without it, user commands
406 /// go to `onExternal`.
407 public var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)?
404408 /// Tags used across the workspace, for tag completion.
405409 public var knownTags: @Sendable () -> [String] = { [] }
406410 /// Answers completion's questions to the index; run off the main actor.
@@ -495,6 +499,8 @@ public final class OrgEditor: NSObject {
495499 var macroKeys: [KeyChord] = []
496500 var kmacroDepth = 0
497501 var macroError: String?
502 /// Work the last replayed key started, which the replay waits for.
503 var macroWait: MacroWait?
498504 var macroRepeatKey: KeyChord?
499505 var commandKeys: [KeyChord]?
500506 /// Named macros (`macros.toml`).
@@ -753,6 +759,10 @@ public final class OrgEditor: NSObject {
753759 }
754760 case .failed(let message):
755761 fail(message)
762 case .external(.userCommand(let request)) where onUserCommand != nil:
763 let wait = kmacroDepth > 0 ? MacroWait() : nil
764 macroWait = wait
765 onUserCommand?(request) { wait?.finish($0) }
756766 case .external(let request):
757767 if let onExternal { onExternal(request) } else { onMessage?(EmacsFallback.wording("This needs Emacs, which isn't available here.", "This isn't available here.")) }
758768 case .prompt(let prompt):
Sources/Orgstar/ContentView.swift +17 −7 · view
@@ -364,6 +364,7 @@ struct ContentView: View {
364364 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
365365 .onAppear {
366366 commands.externalHandler = runExternal
367 commands.userCommandHandler = runUserCommand
367368 commands.filesHandler = { attachActions.drop($0) }
368369 commands.imageHandler = { attachActions.yankImage($0, ext: $1) }
369370 #if APPSTORE
@@ -1295,10 +1296,15 @@ struct ContentView: View {
12951296 }
12961297 }
12971298
1298 /// Runs a user command once its file is trusted on this device.
1299 private func runUserCommand(_ request: UserCommandRequest) {
1300 guard let path = session.path, let modules = session.userCommands.folder else { return }
1301 if let refusal = session.refusesUserCommand(path) { return commands.show(refusal) }
1299 /// Runs a user command once its file is trusted on this device; `finished` gets its message
1300 /// once it has ended, nil when its result was applied. The command's prompts go through the
1301 /// editor, so keyboard macros record and replay their answers.
1302 private func runUserCommand(_ request: UserCommandRequest, finished: @escaping @MainActor (String?) -> Void = { _ in }) {
1303 guard let path = session.path, let modules = session.userCommands.folder else { return finished("") }
1304 if let refusal = session.refusesUserCommand(path) {
1305 commands.show(refusal)
1306 return finished(refusal)
1307 }
13021308 let ask: @MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void = { question, reply in
13031309 let answers = UserCommandTrust.Answer.allCases
13041310 // The echo area's line can cut the path short, so the detail above it repeats it whole.
@@ -1308,10 +1314,14 @@ struct ContentView: View {
13081314 }
13091315 }
13101316 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: {
1311 guard let context = commands.editor?.context() else { return }
1317 guard let editor = commands.editor else { return finished("") }
13121318 commands.show(String(localized: "Running \(request.command.title)… (⌘. to cancel)", comment: "A user command started"))
1313 session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: commands.ask) { commands.show($0) }
1314 }, refuse: { commands.show($0) })
1319 session.startUserCommand(request, context: editor.context(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths),
1320 ask: editor.ask, report: { commands.show($0) }, finished: finished)
1321 }, refuse: {
1322 commands.show($0)
1323 finished($0)
1324 })
13151325 }
13161326
13171327 /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does.
Sources/Orgstar/OrgstarApp.swift +2 · view
@@ -47,6 +47,8 @@ final class AppCommands {
4747 var editorSettings = EditorSettings()
4848 /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
4949 var externalHandler: ((ExternalRequest) -> Void)?
50 /// Runs a user command and says when it has finished; the main window sets it.
51 var userCommandHandler: ((UserCommandRequest, @escaping @MainActor (String?) -> Void) -> Void)?
5052 /// Files and images pasted or dropped on an editor; the main window sets them.
5153 var filesHandler: (([URL]) -> Void)?
5254 var imageHandler: ((Data, String) -> Void)?
Sources/Orgstar/PaneView.swift +1 · view
@@ -128,6 +128,7 @@ struct PaneView: NSViewRepresentable {
128128 session.reveal(offset)
129129 }
130130 editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) }
131 editor.onUserCommand = { [weak commands] request, finished in commands?.userCommandHandler?(request, finished) }
131132 editor.onFiles = { [weak commands] in commands?.filesHandler?($0) }
132133 editor.onImage = { [weak commands] in commands?.imageHandler?($0, $1) }
133134 editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } }
Sources/OrgstarMobile/EditorScreen.swift +17 −9 · view
@@ -443,16 +443,24 @@ struct EditorScreen: View {
443443 }
444444 }
445445
446 /// Runs a user command once its file is trusted on this device.
447 private func runUserCommand(_ request: UserCommandRequest) {
448 guard let modules = session.userCommands.folder else { return }
449 if let refusal = session.refusesUserCommand(path) { return message = refusal }
450 let ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { prompt = PromptRequest(prompt: $0, reply: $1) }
446 /// Runs a user command once its file is trusted on this device; `finished` gets its message
447 /// once it has ended, nil when its result was applied. The command's prompts go through the
448 /// editor, so keyboard macros record and replay their answers.
449 private func runUserCommand(_ request: UserCommandRequest, finished: @escaping @MainActor (String?) -> Void) {
450 guard let modules = session.userCommands.folder else { return finished("") }
451 if let refusal = session.refusesUserCommand(path) {
452 message = refusal
453 return finished(refusal)
454 }
451455 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: { trustRequest = TrustRequest(question: $0, reply: $1) }, run: {
452 guard let context = editor?.editContext() else { return }
456 guard let editor else { return finished("") }
453457 message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad")
454 session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: ask) { message = $0 }
455 }, refuse: { message = $0 })
458 session.startUserCommand(request, context: editor.editContext(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths),
459 ask: editor.ask, report: { message = $0 }, finished: finished)
460 }, refuse: {
461 message = $0
462 finished($0)
463 })
456464 }
457465
458466 private func start() {
@@ -537,7 +545,7 @@ struct EditorScreen: View {
537545 editor.onColumnView = { view in sheet = .columns(view) }
538546 editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
539547 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
540 editor.onUserCommand = { request in runUserCommand(request) }
548 editor.onUserCommand = { request, finished in runUserCommand(request, finished: finished) }
541549 editor.onRefreshSetup = { session.refreshSetup() }
542550 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
543551 editor.keymap = model.keymap
Sources/OrgstarMobile/MobileEditor+Macros.swift +75 −16 · view
@@ -104,36 +104,95 @@ extension MobileEditor {
104104
105105 /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a
106106 /// round changes nothing. False when a command failed.
107 /// A key that starts a user command leaves the replay waiting until the command has
108 /// finished; it goes on from there.
107109 @discardableResult
108110 func playMacro(_ keys: [KeyChord], count: Int) -> Bool {
109111 guard kmacroDepth < 20 else {
110112 fail("Keyboard macros nest too deeply")
111113 return false
112114 }
113 let outer = macroKeys
115 let replay = MacroReplay(keys: keys, count: count, outer: macroKeys)
116 let outermost = kmacroDepth == 0
114117 kmacroDepth += 1
115 defer {
116 kmacroDepth -= 1
117 macroKeys = outer
118 if kmacroDepth == 0 { macroError = nil }
118 switch replayMacro(replay) {
119 case .ended(let error):
120 return error == nil
121 case .waiting(let wait):
122 // A replay this one runs in waits for the rest of it.
123 let rest = resumeMacro(replay, after: wait)
124 if !outermost { macroWait = rest }
125 return true
119126 }
127 }
128
129 /// Goes on with `replay` each time the work it waits for has finished.
130 private func resumeMacro(_ replay: MacroReplay, after wait: MacroWait) -> MacroWait {
131 let rest = MacroWait()
132 Task { [weak self] in
133 var wait = wait
134 while true {
135 let failure = await wait.value
136 guard let self else { return rest.finish("") }
137 if let failure, self.macroError == nil { self.macroError = failure }
138 switch self.replayMacro(replay) {
139 case .ended(let error): return rest.finish(error)
140 case .waiting(let next): wait = next
141 }
142 }
143 }
144 return rest
145 }
146
147 /// A macro being replayed: the rounds run, and the state the current round started from,
148 /// nil between rounds.
149 final class MacroReplay {
150 let keys: [KeyChord]
151 let count: Int
152 /// The keys left in the replay this one runs in.
153 let outer: [KeyChord]
120154 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
155 var before: (Int, NSRange)?
156
157 init(keys: [KeyChord], count: Int, outer: [KeyChord]) {
158 self.keys = keys
159 self.count = count
160 self.outer = outer
161 }
162 }
163
164 /// Feeds `replay`'s keys through `handleChord` until it ends with the error that stopped it,
165 /// nil when it ran through, or until a key leaves `macroWait` set: the replay waits for
166 /// that work and goes on with the next key.
167 private func replayMacro(_ replay: MacroReplay) -> MacroStep {
168 while true {
169 if replay.before == nil {
170 guard replay.count == 0 ? replay.rounds < 100_000 : replay.rounds < replay.count else { return endReplay(replay) }
171 replay.rounds += 1
172 replay.before = (document.revision, textView.selectedRange)
173 macroKeys = replay.keys
174 }
126175 while !macroKeys.isEmpty, macroError == nil {
127176 let key = macroKeys.removeFirst()
177 macroWait = nil
128178 if !handleChord(key) { typeUnhandled(key) }
179 if let wait = macroWait {
180 macroWait = nil
181 return .waiting(wait)
182 }
129183 }
130 if macroError != nil {
131 failed = true
132 break
133 }
134 if count == 0, before == (document.revision, textView.selectedRange) { break }
184 if macroError != nil { return endReplay(replay) }
185 if replay.count == 0, let before = replay.before, before == (document.revision, textView.selectedRange) { return endReplay(replay) }
186 replay.before = nil
135187 }
136 return !failed
188 }
189
190 private func endReplay(_ replay: MacroReplay) -> MacroStep {
191 let error = macroError
192 kmacroDepth -= 1
193 macroKeys = replay.outer
194 if kmacroDepth == 0 { macroError = nil }
195 return .ended(error)
137196 }
138197
139198 /// A replayed key that `handleChord` left to the text system: typed here.
Sources/OrgstarMobile/MobileEditor.swift +8 −3 · view
@@ -77,6 +77,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
7777 var macroKeys: [KeyChord] = []
7878 var kmacroDepth = 0
7979 var macroError: String?
80 /// Work the last replayed key started, which the replay waits for.
81 var macroWait: MacroWait?
8082 var macroRepeatKey: KeyChord?
8183 var commandKeys: [KeyChord]?
8284 /// Named macros (`macros.toml`).
@@ -124,8 +126,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
124126 var onTangle: ((Tangle.Scope) -> Void)?
125127 /// A source block to run (C-c C-c).
126128 var onBabel: ((BabelJob) -> Void)?
127 /// A user command to run.
128 var onUserCommand: ((UserCommandRequest) -> Void)?
129 /// A user command to run; `finished` gets its message once it has ended, nil when its result
130 /// was applied, and a keyboard macro replaying waits for that.
131 var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)?
129132 /// The file's setup files to read again (C-c C-c on a keyword line).
130133 var onRefreshSetup: (() -> Void)?
131134 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
@@ -411,7 +414,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
411414 case .external(.babel(let job)) where onBabel != nil:
412415 onBabel?(job)
413416 case .external(.userCommand(let request)) where onUserCommand != nil:
414 onUserCommand?(request)
417 let wait = kmacroDepth > 0 ? MacroWait() : nil
418 macroWait = wait
419 onUserCommand?(request) { wait?.finish($0) }
415420 case .external(.tangle(let scope)) where onTangle != nil:
416421 onTangle?(scope)
417422 case .external(.agenda(let start, let count)) where onAgenda != nil:
Tests/OrgAppTests/UserCommandRunTests.swift +170 · view
@@ -44,6 +44,37 @@ struct UserCommandRunTests {
4444 name = "copy"
4545 file = "bad.js"
4646 function = "copy"
47
48 [[command]]
49 name = "compose"
50 file = "run.js"
51 function = "compose"
52
53 [[command]]
54 name = "schedule"
55 file = "run.js"
56 function = "schedule"
57
58 [[command]]
59 name = "promote"
60 title = "Promote"
61 file = "run.js"
62 function = "promote"
63
64 [[command]]
65 name = "refused"
66 file = "run.js"
67 function = "refused"
68
69 [[command]]
70 name = "save"
71 file = "run.js"
72 function = "save"
73
74 [[command]]
75 name = "edit-while-running"
76 file = "run.js"
77 function = "editWhileRunning"
4778 """
4879 static let headings = """
4980 import { upper } from "./lib/text.js";
@@ -76,6 +107,48 @@ struct UserCommandRunTests {
76107 export async function refuse(org) { await org.fail("Not today"); }
77108 export async function copy(org) { org.message("Copying"); return { copy: (await org.file()) ?? "none" }; }
78109 """
110 static let builtIns = """
111 export async function compose(org) {
112 await org.run("org.todo.cycle");
113 await org.run("org.todo.cycle");
114 const { text, selection: [{ from }] } = await org.run("org.heading.insert");
115 if (text !== await org.text()) return org.fail("org.text() isn't the text org.run gave");
116 return { edits: [{ from, text: "New" }] };
117 }
118 export async function schedule(org) {
119 await org.run("org.schedule");
120 await org.message((await org.heading()).scheduled);
121 }
122 export async function promote(org) {
123 try {
124 await org.run("org.heading.promote");
125 } catch (error) {
126 org.message("caught " + error.message);
127 }
128 await org.run("org.heading.promote");
129 }
130 export async function refused(org) {
131 const messages = [];
132 for (const id of ["app.export.html", "user.compose", "org.cycle", "org.babel.execute"]) {
133 try {
134 await org.run(id);
135 messages.push("ran " + id);
136 } catch (error) {
137 messages.push(error.message);
138 }
139 }
140 await org.message(messages.join(" | "));
141 }
142 export async function save(org) {
143 await org.run("org.todo.cycle");
144 const { text } = await org.run("app.save");
145 await org.message(text.slice(0, 6));
146 }
147 export async function editWhileRunning(org) {
148 await org.run("org.todo.cycle");
149 await org.prompt("Go on? ");
150 }
151 """
79152 static let file = "* Plan the week :work:\nbody\n* Next\n"
80153
81154 let config: Folder
@@ -92,6 +165,7 @@ struct UserCommandRunTests {
92165 try config.write("commands/lib/text.js", "export const upper = s => s.toUpperCase();\n")
93166 try config.write("commands/review.js", Self.review)
94167 try config.write("commands/bad.js", Self.bad)
168 try config.write("commands/run.js", Self.builtIns)
95169 path = try notes.write("a.org", Self.file).path
96170 session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
97171 session.saveMode = .explicit
@@ -156,6 +230,102 @@ struct UserCommandRunTests {
156230 #expect(reported == ["Copying"])
157231 }
158232
233 // MARK: - org.run
234
235 /// The commands a script runs and its own edits after them are one undo step, with the text
236 /// and selection that running the same commands directly gives.
237 @Test func runningBuiltInsIsOneUndoStep() async throws {
238 let direct = StateBuffer(DocumentState(bytes: Array(Self.file.utf8)))
239 direct.selection = [4..<4]
240 for id in ["org.todo.cycle", "org.todo.cycle", "org.heading.insert"] {
241 guard case .commit = direct.perform(try #require(Commands.command(id)), now: Date(), answers: [:]) else {
242 Issue.record("\(id) didn't commit")
243 return
244 }
245 }
246 let caret = direct.selection[0].lowerBound
247 #expect(try await run("compose") == nil)
248 #expect(buffer.document.text == (direct.document.text as NSString).replacingCharacters(in: NSRange(location: caret, length: 0), with: "New"))
249 #expect(buffer.document.text.hasPrefix("* DONE Pl"))
250 #expect(buffer.selection == [caret + 3..<caret + 3])
251 #expect(buffer.update { $0.undo() } != nil)
252 #expect(buffer.document.text == Self.file)
253 #expect(!buffer.document.canUndo)
254 }
255
256 /// A built-in command's prompt goes through the prompt the command's own prompts use.
257 @Test func aBuiltInsPromptGoesThroughThePrompt() async throws {
258 var asked: [Prompt] = []
259 var reported: [String] = []
260 let message = try await run("schedule", ask: { prompt, reply in
261 asked.append(prompt)
262 reply("2026-12-01")
263 }, report: { reported.append($0) })
264 #expect(message == nil)
265 #expect(asked.count == 1 && asked.first?.key == "date" && asked.first?.date != nil)
266 let scheduled = "* Plan the week :work:\nSCHEDULED: <2026-12-01 Tue>\nbody\n* Next\n"
267 #expect(buffer.document.text == scheduled)
268 #expect(reported == ["<2026-12-01 Tue>"])
269 // Canceling it ends the command with nothing changed.
270 #expect(try await run("schedule") == "Quit")
271 #expect(buffer.document.text == scheduled)
272 }
273
274 /// A failing built-in rejects with its message, which the script can catch.
275 @Test func aFailingBuiltInRejectsWithItsMessage() async throws {
276 let document = buffer.document
277 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [4..<4])
278 guard case .failed(let failure) = PromoteHeading().run(in: context) else {
279 Issue.record("promoting a level 1 heading didn't fail")
280 return
281 }
282 var reported: [String] = []
283 #expect(try await run("promote", report: { reported.append($0) }) == "Promote: \(failure)")
284 #expect(reported == ["caught \(failure)"])
285 #expect(buffer.document.text == Self.file)
286 }
287
288 /// Commands of the app other than the safe ones, user commands, the editor's own commands
289 /// and work outside the text are refused.
290 @Test func refusesWhatIsntABuiltInCommand() async throws {
291 let block = "#+begin_src sh\necho hi\n#+end_src\n"
292 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: block), now: Date(), answers: [:])
293 let document = buffer.document
294 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [2..<2])
295 guard case .external(.babel) = ExecuteSrcBlock().run(in: context) else {
296 Issue.record("the block doesn't run through Babel")
297 return
298 }
299 var reported: [String] = []
300 #expect(try await run("refused", at: 2, report: { reported.append($0) }) == nil)
301 #expect(reported == [[
302 "app.export.html is a command of the app, which user commands can't run",
303 "A user command can't run another: user.compose",
304 "No built-in command org.cycle",
305 UserCommandAPI.external("org.babel.execute").message,
306 ].joined(separator: " | ")])
307 #expect(buffer.document.text == block)
308 }
309
310 /// `app.save` saves the file once the command's changes are applied.
311 @Test func saveRunsAfterTheChanges() async throws {
312 var reported: [String] = []
313 #expect(try await run("save", report: { reported.append($0) }) == nil)
314 #expect(reported == ["* TODO"])
315 #expect(buffer.document.text.hasPrefix("* TODO Plan"))
316 #expect(!buffer.document.isDirty)
317 #expect(try String(contentsOfFile: path, encoding: .utf8) == buffer.document.text)
318 }
319
320 @Test func anEditWhileRunningRefusesWhatItsCommandsDid() async throws {
321 let message = try await run("edit-while-running", ask: { [buffer] _, reply in
322 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:])
323 reply("yes")
324 })
325 #expect(message == "The file changed; try again.")
326 #expect(buffer.document.text == Self.file + "typed\n")
327 }
328
159329 @Test func cancelStopsTheCommand() async throws {
160330 let document = buffer.document
161331 let command = try #require(session.userCommands.command("user.loop"))
Tests/OrgCoreTests/UserCommandTests.swift +36 · view
@@ -239,3 +239,39 @@ struct UserCommandAPITests {
239239 #expect(UserCommandAPI.answer("+2d", to: prompt, now: now, calendar: utc) == "+2d")
240240 }
241241}
242
243struct UserCommandStateTests {
244 func context(_ text: String, caret: Int) -> EditContext {
245 EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
246 }
247
248 /// Commands run one after another on the text the last one left; the command's own edits
249 /// are in that text, and the result is one change from the text it started with.
250 @Test func composesIntoOneResult() throws {
251 var state = UserCommandState(context("* a\n* b\n", caret: 2), defaults: .default)
252 guard case .commit = state.run(TodoCycle(), answers: [:]) else { Issue.record("no commit"); return }
253 #expect(state.context.text == "* TODO a\n* b\n")
254 #expect(state.context.selection == [7..<7])
255 #expect(state.reply["text"] as? String == "* TODO a\n* b\n")
256 guard case .commit = state.run(NextHeading(), answers: [:]) else { Issue.record("no commit"); return }
257 let result = try state.result(#"{"edits": [{"from": 11, "text": "!"}]}"#).get()
258 #expect(result.baseRevision == 3)
259 #expect(result.edits.count == 1)
260 var text = state.start.text
261 for edit in result.edits.reversed() { text = edit.apply(to: text) }
262 #expect(text == "* TODO a\n* !b\n")
263 #expect(result.selection == [9..<9])
264 }
265
266 @Test func refusesWhatIsntBuiltIn() {
267 func refusal(_ id: String) -> String? {
268 if case .failure(let problem) = UserCommandAPI.builtIn(id) { return problem.message }
269 return nil
270 }
271 #expect(refusal("org.todo.cycle") == nil)
272 #expect(refusal("app.export.html") == "app.export.html is a command of the app, which user commands can't run")
273 #expect(refusal("user.other") == "A user command can't run another: user.other")
274 #expect(refusal("org.cycle") == "No built-in command org.cycle")
275 #expect(UserCommandAPI.safeAppCommands == ["app.save"])
276 }
277}
Tests/OrgEditorAppKitTests/MacroTests.swift +81 · view
@@ -1,6 +1,7 @@
11import AppKit
22import Foundation
33import OrgCore
4import OrgDocument
45import Testing
56@testable import OrgApp
67@testable import OrgEditorAppKit
@@ -237,6 +238,86 @@ struct MacroTests {
237238 #expect(MacroRecorder.reply(from: KeySequence.parse("a")!) == nil)
238239 }
239240
241 /// A keyboard macro records a user command's key and its prompt's answer; replaying waits
242 /// for the command to finish before the next key, and answers its prompt from the macro.
243 @Test func macrosWaitForUserCommands() async throws {
244 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
245 defer { try? FileManager.default.removeItem(at: folder) }
246 let modules = folder.appendingPathComponent("config/commands")
247 try FileManager.default.createDirectory(at: modules, withIntermediateDirectories: true)
248 try Data("""
249 export async function stamp(org) {
250 const word = await org.prompt("Word: ");
251 await new Promise(resolve => setTimeout(resolve, 100));
252 const { selection: [{ from }] } = await org.run("org.todo.cycle");
253 const heading = await org.heading();
254 return { edits: [{ from: heading.titleEnd, text: " " + word }], selection: from };
255 }
256 """.utf8).write(to: modules.appendingPathComponent("stamp.js"))
257 let file = folder.appendingPathComponent("a.org")
258 try Data("* one\n* two\n* three\n".utf8).write(to: file)
259 let shared = (UserCommands.shared.all, UserCommands.shared.folder)
260 defer { UserCommands.shared.replace(shared.0, folder: shared.1) }
261 UserCommands.shared.replace([UserCommand(name: "stamp", title: "Stamp", file: "stamp.js", function: "stamp")], folder: modules)
262 OrgEditor.kmacro = MacroRecorder()
263 defer { OrgEditor.kmacro = MacroRecorder() }
264
265 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
266 session.saveMode = .explicit
267 session.userCommands = UserCommands.shared
268 session.open(file.path)
269 let h = Harness(try #require(session.document))
270 h.editor.onChange = { [weak session] in session?.bufferChanged() }
271 session.attach(h.editor)
272 var problems: [String] = []
273 let toml = "[[bind]]\nkeys = \"C-c u\"\ncommand = \"user.stamp\"\n[[bind]]\nkeys = \"C-c m\"\ncommand = \"macro.named.stamp\"\n"
274 let user = try Keymap(toml: toml, problems: &problems, commands: Set(EditorCommands.all.map(\.id) + ["macro.named.stamp"]))
275 h.editor.keymap = .layered([KeymapPreset.emacs.keymap, user])
276 var asked = 0
277 h.editor.onPrompt = { _, reply in
278 asked += 1
279 reply("ok")
280 }
281 var messages: [String] = []
282 h.editor.onMessage = { messages.append($0) }
283 h.editor.onUserCommand = { [weak session, weak h] request, finished in
284 guard let session, let h else { return }
285 session.startUserCommand(request, context: h.editor.context(), file: "a.org", ask: h.editor.ask, report: { messages.append($0) }, finished: finished)
286 }
287 func settled() async throws {
288 for _ in 0..<250 where session.isRunningUserCommand || h.editor.kmacroDepth > 0 { try await Task.sleep(for: .milliseconds(20)) }
289 #expect(!session.isRunningUserCommand && h.editor.kmacroDepth == 0)
290 }
291 h.caret(at: 2)
292 type(h, "C-x ( C-c u")
293 try await settled()
294 type(h, "C-n C-x )")
295 #expect(h.string == "* TODO one ok\n* two\n* three\n")
296 #expect(OrgEditor.kmacro.last == KeySequence.parse("C-c u o k RET C-n"))
297 #expect(asked == 1)
298
299 type(h, "C-u 2 C-x e")
300 try await settled()
301 #expect(h.string == "* TODO one ok\n* TODO two ok\n* TODO three ok\n")
302 #expect(asked == 1)
303 #expect(!messages.contains { $0.contains("undefined") })
304 h.checkInSync()
305 // Each run is one undo step.
306 h.textView.undoManager?.undo()
307 #expect(h.string == "* TODO one ok\n* TODO two ok\n* three\n")
308
309 // A macro waits for a named macro it runs that waits for a user command.
310 let store = NamedMacros()
311 store.replace(["stamp": try OrgEditor.kmacro.lastMacro()])
312 h.editor.namedMacros = store
313 OrgEditor.kmacro.last = KeySequence.parse("C-c m C-e !")
314 h.caret(at: 30)
315 type(h, "C-x e")
316 try await settled()
317 #expect(h.string == "* TODO one ok\n* TODO two ok\n* TODO three ok\n!")
318 #expect(asked == 1)
319 }
320
240321 // MARK: - Emacs
241322
242323 struct OracleCase {
docs/manual/guide/03-keys.org +2 · view
@@ -317,6 +317,8 @@ In the Doom preset the Emacs keys above that start with =C-x= work in every stat
317317
318318*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.
319319
320*User commands.* A key bound to a user command is recorded like any other, with the answers to the command's prompts, including those of the Org commands it runs. When the macro plays, it waits for the command to finish before the next key, and a command that fails stops it (see [[file:18-user-commands.org][User commands]]). The question before a command from a file not yet trusted on this device isn't recorded; it is asked whenever it comes up.
321
320322The 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.
321323
322324** Named macros
docs/manual/guide/18-user-commands.org +38 −6 · view
@@ -71,8 +71,8 @@ Every call returns a promise; use =await=. Offsets are UTF-16 code units, as Jav
7171
7272| Call | Gives |
7373|----------------------------+-----------------------------------------------------------------------------------------------------------------------------|
74| =org.text()= | The buffer's text when the command started. |
75| =org.selection()= | The selections as =[{from, to}]=, the main caret first. With nothing selected, =from= and =to= are both the caret. |
74| =org.text()= | The buffer's text: as the command started, or as the last =org.run= left it. |
75| =org.selection()= | The selections as =[{from, to}]=, the main caret first. With nothing selected, =from= and =to= are both the caret. After =org.run=, where that command left them. |
7676| =org.heading(at)= | The heading whose entry holds the offset =at= (default: the caret), as described below, or =null= before the first heading. |
7777| =org.outline()= | Every heading in the file, in order, as =org.heading()= describes it. |
7878| =org.file()= | The file's path relative to its folder (=notes/plan.org=), or =null= for a buffer without a file. |
@@ -80,6 +80,7 @@ Every call returns a promise; use =await=. Offsets are UTF-16 code units, as Jav
8080| =org.prompt(options)= | Asks in the echo area (the Mac) or a sheet (iPhone and iPad) and gives the answer as a string. Throws when you cancel. |
8181| =org.message(text)= | Shows =text= in the echo area while the command runs. |
8282| =org.fail(text)= | Ends the command: nothing changes and =text= is shown. Use it as =return org.fail("…")=. |
83| =org.run(id)= | Runs one of Org's commands by id (=org.todo.cycle=) and gives the text and selection after it as ={text, selection}=. See [[*Running Org's commands][Running Org's commands]]. |
8384| =org.version= | =1=. |
8485
8586A heading is an object with:
@@ -104,14 +105,37 @@ The function returns an object with any of these, or nothing:
104105
105106| Field | Value |
106107|-------------+---------------------------------------------------------------------------------------------------------------------------------------------|
107| =edits= | A list of ={from, to, text}= in the text the command was given. =to= defaults to =from= (an insertion) and =text= to =""= (a deletion). Edits may not overlap or start at the same offset. |
108| =edits= | A list of ={from, to, text}= in the text the command was given, or after =org.run=, in the text the last =org.run= gave. =to= defaults to =from= (an insertion) and =text= to =""= (a deletion). Edits may not overlap or start at the same offset. |
108109| =selection= | Where the caret or selection goes, in the text after the edits: an offset, ={from, to}=, or a list of them. Without it, the selection moves with the edits. |
109110| =message= | Text for the echo area. |
110111| =copy= | Text for the clipboard (the kill ring). |
111112
112113orgstar checks the edits before it makes any of them. An edit outside the text, edits that overlap, an edit that splits an emoji or other character in two, or an unknown field fail the command with a message such as =Add Weekly Review: edits overlap=, and nothing changes.
113114
114The edits are applied together as one step of undo, and only if the buffer is as it was when the command started. If you type, or the file changes on disk, while the command runs or waits for a prompt, its result is refused with "The file changed; try again."
115The edits are applied together as one step of undo, with the changes of the commands run with =org.run=, and only if the buffer is as it was when the command started. If you type, or the file changes on disk, while the command runs or waits for a prompt, its result is refused with "The file changed; try again."
116
117** Running Org's commands
118
119=org.run(id)= runs a built-in command on the text as it is at that point in the command, with the caret where the command has left it, and resolves with ={text, selection}= after it: =text= is the new text and =selection= the selections as =org.selection()= gives them. The ids are those of the palette and =keymap.toml= (see [[file:03-keys.org][Keys]]): =org.todo.cycle=, =org.schedule=, =org.heading.insert= and the rest. Later calls read the new text, and later =org.run= calls work on it.
120
121#+BEGIN_SRC js
122export async function startTask(org) {
123 await org.run("org.todo.cycle") // TODO
124 await org.run("org.schedule") // asks for the date
125 const { selection } = await org.run("org.heading.insert-todo")
126 return { edits: [{ from: selection[0].from, text: "Follow up" }] }
127}
128#+END_SRC
129
130- *One step of undo.* Nothing reaches the buffer until the command returns. Then the changes of every =org.run=, and the command's own =edits= after them, apply together as one step of undo. If the command fails or is cancelled, none of them apply.
131- *Prompts.* A command that asks (=org.schedule= for a date, =org.tags.set= for tags) asks through the same prompt as =org.prompt=. Cancelling it makes =org.run= throw =Quit=.
132- *Failures.* A command that can't run at the caret makes =org.run= throw an error with the command's own message (=error.message=), as =user-error= does in Emacs. Catch it to go on; uncaught, the command ends with that message and nothing changes.
133- *Messages and the clipboard.* Messages and text for the clipboard from the commands run are shown and copied when the command's changes apply. Folding, sparse trees and snippet fields from them are not.
134- *What it refuses.* =org.run= throws for:
135 - commands of the app (=app.*=: export, refile, capture, the clock, windows), except =app.save=, which saves the file after the command's changes apply. They need windows, other files or the network, which a command doesn't reach;
136 - other user commands (=user.*=);
137 - the editor's own commands, which aren't Org's: folding (=org.cycle=), movement and editing keys (=edit.*=), snippets and keyboard macros;
138 - work Org does outside the text: running a code block (=org.babel.execute=, or =C-c C-c= on one), table formulas that need Emacs, following a link, tangling, editing a block apart, column view and the agenda. =org.run= throws with "/id/ needs work outside the text here …" instead of starting it, since its result would come back after the command had ended.
115139
116140* Examples
117141
@@ -197,7 +221,7 @@ Edit ▸ Cancel Running Task (=⌘.=, =app.babel.cancel=) stops a running comman
197221- *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh.
198222- *The buffer only.* A command reads and changes the buffer it runs in, nothing else: no files, no network (=fetch=, =XMLHttpRequest=, =WebSocket=, =importScripts= and the rest are removed), no other buffers, no clipboard reads, no notifications, Calendar or other system services.
199223- *Encrypted text.* Commands don't run in an encrypted file or in a buffer with entries decrypted that are encrypted on disk: "/file/ has decrypted entries, so user commands don't run in it."
200- *Keyboard macros* don't wait for a user command to finish.
224- *Keyboard macros* record a key bound to a user command with the answers to its prompts, and wait for the command to finish when they play (see [[file:03-keys.org::*Keyboard macros][Keyboard macros]]).
201225- *Startup.* When you have commands, the engine that runs them starts when an editor opens, so the first run doesn't wait for it. It stops after five minutes without a run.
202226
203227* Compared with Emacs Lisp
@@ -208,7 +232,7 @@ What Emacs Lisp has that user commands don't:
208232
209233- Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read.
210234- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
211- The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=, calling Org's own commands (=org-todo=, =org-schedule=). Read headings with =org.heading()= and =org.outline()=, and write the text yourself.
235- The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=. Read headings with =org.heading()= and =org.outline()=, and write the text yourself or run Org's commands with =org.run=.
212236- Other buffers and files, =find-file=, =with-temp-buffer=, capture from a command.
213237- Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables.
214238- =interactive= codes other than the prompts above; =C-u= prefix arguments.
@@ -237,4 +261,12 @@ What Emacs Lisp has that user commands don't:
237261| =(message …)= | =org.message(…)= or =message= |
238262| =(user-error …)= | =return org.fail(…)= |
239263| =(kill-new …)= | =copy= |
264| =(org-todo)= | =await org.run("org.todo.cycle")= |
265| =(org-schedule nil)=, =(org-deadline nil)= | =await org.run("org.schedule")=, =org.run("org.deadline")= |
266| =(org-insert-heading)=, =(org-insert-todo-heading nil)= | =await org.run("org.heading.insert")=, =org.run("org.heading.insert-todo")= |
267| =(org-set-tags-command)= | =await org.run("org.tags.set")= |
268| =(org-set-effort)=, =(org-set-property …)= | =await org.run("org.effort.set")=, =org.run("org.property.read-and-set")= |
269| =(org-promote-subtree)=, =(org-demote-subtree)= | =await org.run("org.subtree.promote")=, =org.run("org.subtree.demote")= |
270| =(org-toggle-checkbox)= | =await org.run("org.checkbox.toggle")= |
271| =(save-buffer)= | =await org.run("app.save")= |
240272| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= |
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