Commit 071e94ac59

071e94ac597ceadb3ee079a0401d882f11c45a76

parent: 73b5c3d293

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-27 17:40 UTC

User commands: TODO state and capture hooks

[[hook]] entries in commands.toml with event after-todo-state-change
or capture-before-finalize, file, function, and optional timeout and
workspace as commands have. Problems are reported as "hook at line N".
A hook's function gets org and the event's argument; it may return
edits and message. org.prompt throws in hooks.

after-todo-state-change: every OrgCore path through org-todo's
afterTodoChange reports a todoStateChanged effect (heading, from, to;
to is the done keyword before a repeat). Hooks run for the Mac and iOS
editors and for every DocumentSession.perform caller (agenda, board,
column view, entry sheet, watch, clock-in state switch), one at a time,
on the text the change left. Their edits apply as their own undo step
through applyChanges, refused if the file changed meanwhile; a failing
hook leaves the change and reports. Changes made by hooks, user
commands (org.run) and the command-line tool run no hooks.

capture-before-finalize: runs on the filled capture text with the
template key before filing, from the Mac capture window, the iOS
capture sheet, x-callback-url capture without the sheet and the
Shortcuts capture actions. Edits change the text; a failure cancels
the capture. orgstar capture files without hooks and says so on
stderr.

Hooks use their file's command trust. Untrusted hooks ask with an
alert where the app can, and are skipped with a message where it
can't (non-interactive capture). CommandHost answers each run's calls
with its own handler, so a hook and a command can run together.

Manual: Hooks section, porting rows, command-line note. Strings in
de, es, fr, ja, pt-BR.

Closes #248

Layout: unified · split

Changed files (28)
Sources/OrgApp/CaptureModel.swift +37 −3 · view
@@ -63,6 +63,42 @@ extension DocumentSession {
63 _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel, 63 _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
64 clipboard: String, userName: String, answers: [String: String] = [:], properties: [String: String] = [:] 64 clipboard: String, userName: String, answers: [String: String] = [:], properties: [String: String] = [:]
65 ) -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> { 65 ) -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> {
66 filled(text, templateKey: key, templates: templates, workspace: workspace, clipboard: clipboard, userName: userName,
67 answers: answers, properties: properties).flatMap { chosen, filled in
68 file(filled, with: chosen, workspace: workspace, clock: clock)
69 }
70 }
71
72 /// `capture(_:templateKey:…)` with the `capture-before-finalize` hooks run on the filled
73 /// template first. A hook from a file not trusted here is skipped, since nothing asks.
74 public func captureRunningHooks(
75 _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
76 clipboard: String, userName: String, answers: [String: String] = [:], properties: [String: String] = [:]
77 ) async -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> {
78 let chosen: CaptureTemplate, filledText: String
79 switch filled(text, templateKey: key, templates: templates, workspace: workspace, clipboard: clipboard, userName: userName,
80 answers: answers, properties: properties) {
81 case .failure(let error): return .failure(error)
82 case .success(let prepared): (chosen, filledText) = prepared
83 }
84 switch await runCaptureHooks(filledText, template: chosen.key, interactive: false) {
85 case .failure(let error): return .failure(error)
86 case .success(let text): return file(text, with: chosen, workspace: workspace, clock: clock)
87 }
88 }
89
90 private func file(_ text: String, with chosen: CaptureTemplate, workspace: WorkspaceModel, clock: ClockModel)
91 -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> {
92 chosen.resolved(workspace: workspace, session: self, clock: clock).flatMap { resolved in
93 capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
94 }.map { (chosen, $0.path, $0.offset) }
95 }
96
97 /// The template keyed `key` and its text filled as `capture(_:templateKey:…)` fills it.
98 private func filled(
99 _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel,
100 clipboard: String, userName: String, answers: [String: String], properties: [String: String]
101 ) -> Result<(CaptureTemplate, String), CaptureError> {
66 let key = key.flatMap { $0.isEmpty ? nil : $0 } 102 let key = key.flatMap { $0.isEmpty ? nil : $0 }
67 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else { 103 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
68 return .failure(CaptureError(message: "No capture template \"\(key ?? "")\"")) 104 return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
@@ -75,9 +111,7 @@ extension DocumentSession {
75 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else { 111 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
76 return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\"")) 112 return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\""))
77 } 113 }
78 return chosen.resolved(workspace: workspace, session: self, clock: clock).flatMap { resolved in 114 return .success((chosen, filled.text))
79 capture(filled.text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
80 }.map { (chosen, $0.path, $0.offset) }
81 } 115 }
82} 116}
83 117
Sources/OrgApp/CommandHost.swift +17 −11 · view
@@ -70,9 +70,11 @@ public final class CommandHost {
70 70
71 /// Calls `function` exported by `module`, a path in `commands/`, with the JSON `context` and a 71 /// Calls `function` exported by `module`, a path in `commands/`, with the JSON `context` and a
72 /// function the command calls the app with, and returns its result as JSON. With `api`, the 72 /// function the command calls the app with, and returns its result as JSON. With `api`, the
73 /// function gets that version's `org` object instead, whose calls reach `calls`. `timeout` 73 /// function gets that version's `org` object instead, whose calls reach `calls`, and then
74 /// is at most `maximumTimeout`. 74 /// `context` unless it is `null`. `timeout` is at most `maximumTimeout`. `answer`, when
75 public func run(module: String, function: String, context: String, timeout: Duration = defaultTimeout, api: Int? = nil) async throws -> String { 75 /// given, answers this run's calls in place of `calls`.
76 public func run(module: String, function: String, context: String, timeout: Duration = defaultTimeout, api: Int? = nil,
77 answer: (@MainActor (String, Any) async throws -> Any)? = nil) async throws -> String {
76 guard Files.relative(module) != nil else { throw Failure.script("No module \(module) in commands/.") } 78 guard Files.relative(module) != nil else { throw Failure.script("No module \(module) in commands/.") }
77 let limit = min(timeout, Self.maximumTimeout) 79 let limit = min(timeout, Self.maximumTimeout)
78 idleTask?.cancel() 80 idleTask?.cancel()
@@ -87,7 +89,7 @@ public final class CommandHost {
87 throw Failure.stopped 89 throw Failure.stopped
88 } 90 }
89 try Task.checkCancellation() 91 try Task.checkCancellation()
90 let run = Run(limit: limit) 92 let run = Run(limit: limit, answer: answer)
91 engine.runs[id] = run 93 engine.runs[id] = run
92 defer { engine.runs[id] = nil } 94 defer { engine.runs[id] = nil }
93 let reply: String 95 let reply: String
@@ -141,8 +143,8 @@ public final class CommandHost {
141 if self.engine === engine { unload() } else { engine.close() } 143 if self.engine === engine { unload() } else { engine.close() }
142 } 144 }
143 145
144 func call(_ name: String, _ value: Any) async throws -> Any { 146 func call(_ name: String, _ value: Any, run: Run) async throws -> Any {
145 try await calls(name, value) 147 try await (run.answer ?? calls)(name, value)
146 } 148 }
147 149
148 /// A run, which ends once: with the worker's reply, a cancel, the timeout or the end of the 150 /// A run, which ends once: with the worker's reply, a cancel, the timeout or the end of the
@@ -150,6 +152,8 @@ public final class CommandHost {
150 @MainActor 152 @MainActor
151 final class Run { 153 final class Run {
152 let limit: Duration 154 let limit: Duration
155 /// Answers this run's calls in place of the host's `calls`.
156 let answer: (@MainActor (String, Any) async throws -> Any)?
153 private var remaining: Duration 157 private var remaining: Duration
154 private var since = ContinuousClock.now 158 private var since = ContinuousClock.now
155 private var timer: Task<Void, Never>? 159 private var timer: Task<Void, Never>?
@@ -157,8 +161,9 @@ public final class CommandHost {
157 private(set) var ended = false 161 private(set) var ended = false
158 private var continuation: CheckedContinuation<String, Error>? 162 private var continuation: CheckedContinuation<String, Error>?
159 163
160 init(limit: Duration) { 164 init(limit: Duration, answer: (@MainActor (String, Any) async throws -> Any)? = nil) {
161 self.limit = limit 165 self.limit = limit
166 self.answer = answer
162 remaining = limit 167 remaining = limit
163 } 168 }
164 169
@@ -286,7 +291,7 @@ public final class CommandHost {
286 run.pause() 291 run.pause()
287 defer { run.resume() } 292 defer { run.resume() }
288 do { 293 do {
289 return (try await host.call(name, body["value"] ?? NSNull()), nil) 294 return (try await host.call(name, body["value"] ?? NSNull(), run: run), nil)
290 } catch let Failure.script(message) { 295 } catch let Failure.script(message) {
291 return (nil, message) 296 return (nil, message)
292 } catch { 297 } catch {
@@ -392,8 +397,8 @@ public final class CommandHost {
392 """ 397 """
393 398
394 /// Removes the ways out of the worker, then waits for a command: imports its module, calls 399 /// Removes the ways out of the worker, then waits for a command: imports its module, calls
395 /// the function with the context and `call`, or with `org` for API version 1, and posts the 400 /// the function with the context and `call`, or for API version 1 with `org` and the
396 /// result as JSON. 401 /// context unless it is null, and posts the result as JSON.
397 static let worker = """ 402 static let worker = """
398 const post = self.postMessage.bind(self); 403 const post = self.postMessage.bind(self);
399 for (const name of ["fetch", "XMLHttpRequest", "WebSocket", "EventSource", "importScripts", "indexedDB", "caches", "Worker", "SharedWorker"]) { 404 for (const name of ["fetch", "XMLHttpRequest", "WebSocket", "EventSource", "importScripts", "indexedDB", "caches", "Worker", "SharedWorker"]) {
@@ -442,7 +447,8 @@ public final class CommandHost {
442 try { 447 try {
443 const module = await import("./commands/" + m.module); 448 const module = await import("./commands/" + m.module);
444 if (typeof module[m.name] !== "function") throw new Error(`${m.module} exports no function ${m.name}.`); 449 if (typeof module[m.name] !== "function") throw new Error(`${m.module} exports no function ${m.name}.`);
445 const value = await module[m.name](...(m.api === 1 ? [api1()] : [JSON.parse(m.context), call])); 450 const context = JSON.parse(m.context);
451 const value = await module[m.name](...(m.api === 1 ? [api1(), ...(context === null ? [] : [context])] : [context, call]));
446 post({ result: JSON.stringify(value) ?? "null" }); 452 post({ result: JSON.stringify(value) ?? "null" });
447 } catch (error) { 453 } catch (error) {
448 post({ error: String(error && error.message || error) }); 454 post({ error: String(error && error.message || error) });
Sources/OrgApp/DocumentSession.swift +253 −45 · view
@@ -1213,7 +1213,10 @@ public final class DocumentSession {
1213 do { 1213 do {
1214 let options = self.options 1214 let options = self.options
1215 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) } 1215 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
1216 if case .commit = step { changed(entry) } 1216 if case .commit(let result) = step {
1217 changed(entry)
1218 afterTodoStateChange(result.effects, in: path)
1219 }
1217 return step 1220 return step
1218 } catch { 1221 } catch {
1219 return .failed("\(error)") 1222 return .failed("\(error)")
@@ -1230,7 +1233,10 @@ public final class DocumentSession {
1230 if case .commit = step, state.isDirty, case .conflict = try closedFileSaver.save(&state, to: url) { 1233 if case .commit = step, state.isDirty, case .conflict = try closedFileSaver.save(&state, to: url) {
1231 return .failed("\(name) changed on disk; nothing was changed.") 1234 return .failed("\(name) changed on disk; nothing was changed.")
1232 } 1235 }
1233 if case .commit = step { textChanged?(path) } 1236 if case .commit(let result) = step {
1237 textChanged?(path)
1238 afterTodoStateChange(result.effects, in: path, text: state.text)
1239 }
1234 return step 1240 return step
1235 } catch { 1241 } catch {
1236 return .failed("Can't change \(name): \(error.localizedDescription)") 1242 return .failed("Can't change \(name): \(error.localizedDescription)")
@@ -1487,6 +1493,10 @@ public final class DocumentSession {
1487 } 1493 }
1488 #endif 1494 #endif
1489 @ObservationIgnored private var userCommandTask: Task<String?, Never>? 1495 @ObservationIgnored private var userCommandTask: Task<String?, Never>?
1496 /// What hooks need from the app; nil runs none.
1497 @ObservationIgnored public var hooks: UserHookHost?
1498 /// The hooks started last; the next wait for them.
1499 @ObservationIgnored private var hookQueue: Task<Void, Never>?
1490 public private(set) var isRunningUserCommand = false 1500 public private(set) var isRunningUserCommand = false
1491 1501
1492 /// Runs a user command on the focused buffer in the background, with `context` the editor's 1502 /// Runs a user command on the focused buffer in the background, with `context` the editor's
@@ -1537,41 +1547,95 @@ public final class DocumentSession {
1537 guard entry.buffer.document.revision == request.revision, context.revision == request.revision else { return "The file changed; try again." } 1547 guard entry.buffer.document.revision == request.revision, context.revision == request.revision else { return "The file changed; try again." }
1538 #if canImport(WebKit) 1548 #if canImport(WebKit)
1539 guard let host = userCommandHost() else { return "No \(UserCommands.fileName)." } 1549 guard let host = userCommandHost() else { return "No \(UserCommands.fileName)." }
1540 final class State { 1550 let state = UserScript(file: command.file, function: command.function, timeout: command.timeout, workspace: command.workspace,
1541 var failure: String? 1551 title: command.title, buffer: UserCommandState(
1542 var quit = false 1552 EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection,
1543 /// `org.run("app.save")` ran. 1553 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags),
1544 var save = false 1554 defaults: entry.buffer.document.defaults))
1545 var buffer: UserCommandState 1555 let json: String
1546 init(_ buffer: UserCommandState) { self.buffer = buffer } 1556 switch await run(state, host: host, path: path, file: file, workspace: workspace, ask: ask, report: report) {
1547 } 1557 case .failure(let message): return message.text
1548 let state = State(UserCommandState( 1558 case .success(let returned): json = returned
1549 EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection, 1559 }
1550 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags), 1560 guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") }
1551 defaults: entry.buffer.document.defaults)) 1561 switch state.buffer.result(json) {
1562 case .failure(let problem):
1563 return "\(command.title): \(problem.message)"
1564 case .success(let result):
1565 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the command finished." }
1566 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1567 if !result.edits.isEmpty { changed(entry) }
1568 // A save that fails shows why, as Save does.
1569 if state.save { save(entry) }
1570 return nil
1571 }
1572 #else
1573 return "User commands aren't available here."
1574 #endif
1575 }
1576
1577 #if canImport(WebKit)
1578 /// A run of a user command or hook: what it runs, the buffer as it sees it, and what its
1579 /// calls asked for.
1580 final class UserScript {
1581 let file: String
1582 let function: String
1583 let timeout: Int
1584 let workspace: Bool
1585 let title: String
1586 /// The second argument of a hook's function, as JSON; `null` for a command.
1587 let argument: String
1588 var buffer: UserCommandState
1589 var failure: String?
1590 var quit = false
1591 /// `org.run("app.save")` ran.
1592 var save = false
1593
1594 init(file: String, function: String, timeout: Int, workspace: Bool, title: String, argument: String = "null", buffer: UserCommandState) {
1595 self.file = file
1596 self.function = function
1597 self.timeout = timeout
1598 self.workspace = workspace
1599 self.title = title
1600 self.argument = argument
1601 self.buffer = buffer
1602 }
1603 }
1604
1605 struct ScriptFailure: Error {
1606 let text: String
1607 }
1608
1609 /// Runs `script` in the host with API version 1 and its calls answered against its buffer;
1610 /// the JSON it returned, or the message saying why it failed. `path` is the file the
1611 /// workspace calls see it run in and `file` what `org.file()` gives. Without `ask`,
1612 /// `org.prompt` and the prompts of `org.run`'s commands throw.
1613 func run(_ script: UserScript, host: CommandHost, path: String, file: String?, workspace: UserCommandWorkspace?,
1614 ask: (@MainActor (Prompt, @escaping (String?) -> Void) -> Void)?, report: @escaping @MainActor (String) -> Void) async -> Result<String, ScriptFailure> {
1552 /// The answer to `prompt`; a canceled prompt throws. 1615 /// The answer to `prompt`; a canceled prompt throws.
1553 func reply(to prompt: Prompt) async throws -> String { 1616 func reply(to prompt: Prompt) async throws -> String {
1554 try await withCheckedThrowingContinuation { continuation in 1617 guard let ask else { throw CommandHost.Failure.script("Hooks can't ask: org.prompt isn't available in them.") }
1618 return try await withCheckedThrowingContinuation { continuation in
1555 ask(prompt) { answer in 1619 ask(prompt) { answer in
1556 guard let answer else { 1620 guard let answer else {
1557 state.quit = true 1621 script.quit = true
1558 return continuation.resume(throwing: CommandHost.Failure.script("Quit")) 1622 return continuation.resume(throwing: CommandHost.Failure.script("Quit"))
1559 } 1623 }
1560 continuation.resume(returning: answer) 1624 continuation.resume(returning: answer)
1561 } 1625 }
1562 } 1626 }
1563 } 1627 }
1564 host.calls = { name, value in 1628 let calls: @MainActor (String, Any) async throws -> Any = { name, value in
1565 if let answer = UserCommandAPI.answer(name, value, context: state.buffer.context, file: file) { return answer } 1629 if let answer = UserCommandAPI.answer(name, value, context: script.buffer.context, file: file) { return answer }
1566 switch name { 1630 switch name {
1567 case "prompt": 1631 case "prompt":
1568 let prompt = UserCommandAPI.prompt(value) 1632 let prompt = UserCommandAPI.prompt(value)
1569 return UserCommandAPI.answer(try await reply(to: prompt), to: prompt, now: Date(), calendar: state.buffer.context.calendar) 1633 return UserCommandAPI.answer(try await reply(to: prompt), to: prompt, now: Date(), calendar: script.buffer.context.calendar)
1570 case "run": 1634 case "run":
1571 let id = value as? String ?? "" 1635 let id = value as? String ?? ""
1572 if UserCommandAPI.safeAppCommands.contains(id) { 1636 if UserCommandAPI.safeAppCommands.contains(id) {
1573 state.save = true 1637 script.save = true
1574 return state.buffer.reply 1638 return script.buffer.reply
1575 } 1639 }
1576 let command: any OrgCommand 1640 let command: any OrgCommand
1577 switch UserCommandAPI.builtIn(id) { 1641 switch UserCommandAPI.builtIn(id) {
@@ -1581,8 +1645,8 @@ public final class DocumentSession {
1581 // A built-in command's prompts go through the same prompt as the command's own. 1645 // A built-in command's prompts go through the same prompt as the command's own.
1582 var answers: [String: String] = [:] 1646 var answers: [String: String] = [:]
1583 while true { 1647 while true {
1584 switch state.buffer.run(command, answers: answers) { 1648 switch script.buffer.run(command, answers: answers) {
1585 case .commit: return state.buffer.reply 1649 case .commit: return script.buffer.reply
1586 case .failed(let message): throw CommandHost.Failure.script(message) 1650 case .failed(let message): throw CommandHost.Failure.script(message)
1587 case .external: throw CommandHost.Failure.script(UserCommandAPI.external(id).message) 1651 case .external: throw CommandHost.Failure.script(UserCommandAPI.external(id).message)
1588 case .prompt(let prompt): answers[prompt.key] = try await reply(to: prompt) 1652 case .prompt(let prompt): answers[prompt.key] = try await reply(to: prompt)
@@ -1592,10 +1656,10 @@ public final class DocumentSession {
1592 report(value as? String ?? "") 1656 report(value as? String ?? "")
1593 return NSNull() 1657 return NSNull()
1594 case "fail": 1658 case "fail":
1595 state.failure = value as? String ?? "" 1659 script.failure = value as? String ?? ""
1596 return NSNull() 1660 return NSNull()
1597 case _ where UserCommandWorkspace.calls.contains(name): 1661 case _ where UserCommandWorkspace.calls.contains(name):
1598 guard command.workspace else { 1662 guard script.workspace else {
1599 throw CommandHost.Failure.script("org.\(name) needs workspace = true on the command in \(UserCommands.fileName).") 1663 throw CommandHost.Failure.script("org.\(name) needs workspace = true on the command in \(UserCommands.fileName).")
1600 } 1664 }
1601 guard let workspace else { throw CommandHost.Failure.script("org.\(name) isn't available here.") } 1665 guard let workspace else { throw CommandHost.Failure.script("org.\(name) isn't available here.") }
@@ -1608,39 +1672,183 @@ public final class DocumentSession {
1608 throw CommandHost.Failure.script("org.\(name) isn't in API version \(UserCommands.apiVersion).") 1672 throw CommandHost.Failure.script("org.\(name) isn't in API version \(UserCommands.apiVersion).")
1609 } 1673 }
1610 } 1674 }
1675 let title = script.title
1611 let json: String 1676 let json: String
1612 do { 1677 do {
1613 json = try await host.run(module: command.file, function: command.function, context: "null", 1678 json = try await host.run(module: script.file, function: script.function, context: script.argument,
1614 timeout: .seconds(command.timeout), api: UserCommands.apiVersion) 1679 timeout: .seconds(script.timeout), api: UserCommands.apiVersion, answer: calls)
1615 } catch let CommandHost.Failure.timedOut(limit) { 1680 } catch let CommandHost.Failure.timedOut(limit) {
1616 let seconds = Int(limit.components.seconds) 1681 let seconds = Int(limit.components.seconds)
1617 return String(localized: "\(command.title) didn't finish within \(seconds) s and was stopped.", comment: "A user command passed its time limit") 1682 return .failure(ScriptFailure(text: String(localized: "\(title) didn't finish within \(seconds) s and was stopped.", comment: "A user command passed its time limit")))
1618 } catch CommandHost.Failure.script(let message) { 1683 } catch CommandHost.Failure.script(let message) {
1619 if let failure = state.failure { return failure } 1684 if let failure = script.failure { return .failure(ScriptFailure(text: failure)) }
1620 return state.quit ? "Quit" : "\(command.title): \(message)" 1685 return .failure(ScriptFailure(text: script.quit ? "Quit" : "\(title): \(message)"))
1621 } catch CommandHost.Failure.stopped { 1686 } catch CommandHost.Failure.stopped {
1622 return String(localized: "\(command.title) was stopped: its web view ended, as when a command runs out of memory.", comment: "A user command whose web view ended") 1687 return .failure(ScriptFailure(text: String(localized: "\(title) was stopped: its web view ended, as when a command runs out of memory.", comment: "A user command whose web view ended")))
1623 } catch { 1688 } catch {
1624 return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") 1689 return .failure(ScriptFailure(text: String(localized: "\(title) canceled.", comment: "A user command canceled with Cancel Running Task")))
1625 } 1690 }
1626 if let failure = state.failure { return failure } 1691 if let failure = script.failure { return .failure(ScriptFailure(text: failure)) }
1627 guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") } 1692 return .success(json)
1628 switch state.buffer.result(json) { 1693 }
1629 case .failure(let problem): 1694 #endif
1630 return "\(command.title): \(problem.message)" 1695
1631 case .success(let result): 1696 // MARK: - Hooks
1632 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the command finished." } 1697
1633 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message } 1698 /// Whether `commands.toml` has hooks for `event`.
1634 if !result.edits.isEmpty { changed(entry) } 1699 public func hasHooks(_ event: UserHook.Event) -> Bool {
1635 // A save that fails shows why, as Save does. 1700 hooks != nil && !userCommands.hooks(event).isEmpty
1636 if state.save { save(entry) } 1701 }
1702
1703 /// Runs the `after-todo-state-change` hooks for the TODO changes in `effects`, from a commit
1704 /// to `path`, after the hooks already waiting. `text` is the file's text after the commit;
1705 /// nil reads the open buffer's.
1706 public func afterTodoStateChange(_ effects: [Effect], in path: String, text: String? = nil) {
1707 let changes = effects.compactMap { effect -> TodoStateChange? in
1708 if case .todoStateChanged(let change) = effect { return change }
1637 return nil 1709 return nil
1638 } 1710 }
1639 #else 1711 guard !changes.isEmpty, hasHooks(.afterTodoStateChange), let text = text ?? entry(path)?.buffer.document.text else { return }
1640 return "User commands aren't available here." 1712 let previous = hookQueue
1713 hookQueue = Task {
1714 await previous?.value
1715 for change in changes { await runTodoHooks(change, in: path, text: text) }
1716 }
1717 }
1718
1719 /// Waits for the hooks started so far.
1720 func hooksFinished() async {
1721 await hookQueue?.value
1722 }
1723
1724 /// Runs each `after-todo-state-change` hook, in file order, on `path` as `text`, the file
1725 /// after the change. Each hook's edits apply as their own change, and the next hook sees
1726 /// them; a file changed meanwhile ends the run.
1727 func runTodoHooks(_ change: TodoStateChange, in path: String, text: String) async {
1728 #if canImport(WebKit)
1729 guard let hooks, let modules = userCommands.folder, let host = userCommandHost() else { return }
1730 let list = userCommands.hooks(.afterTodoStateChange)
1731 guard !list.isEmpty else { return }
1732 if let refusal = refusesUserCommand(path) { return hooks.report(refusal) }
1733 let name = (path as NSString).lastPathComponent
1734 var text = text
1735 var heading = change.heading
1736 for hook in list {
1737 if let refusal = await trust(hook, modules: modules, hooks: hooks) {
1738 hooks.report("\(hook.title): \(refusal)")
1739 continue
1740 }
1741 guard let context = hookContext(path, expecting: text, caret: heading) else {
1742 return hooks.report(String(localized: "\(name) changed before \(hook.title) ran, so it didn't run.",
1743 comment: "An after-todo-state-change hook not run because its file changed"))
1744 }
1745 let described = UserCommandAPI.answer("heading", heading, context: context, file: nil) ?? NSNull()
1746 let argument: [String: Any] = ["entry": described, "from": change.from ?? NSNull(), "to": change.to ?? NSNull()]
1747 guard let data = try? JSONSerialization.data(withJSONObject: argument), let json = String(data: data, encoding: .utf8) else { continue }
1748 let script = UserScript(file: hook.file, function: hook.function, timeout: hook.timeout, workspace: hook.workspace, title: hook.title,
1749 argument: json, buffer: UserCommandState(context, defaults: defaults))
1750 let result: EditResult
1751 switch await run(script, host: host, path: path, file: UserCommandFile.relativePath(path, roots: hooks.workspace?.workspace.rootPaths ?? []), workspace: hooks.workspace,
1752 ask: nil, report: hooks.report) {
1753 case .failure(let failure):
1754 hooks.report(failure.text)
1755 continue
1756 case .success(let returned):
1757 switch Self.hookResult(script, returned) {
1758 case .failure(let failure):
1759 hooks.report(failure.text)
1760 continue
1761 case .success(let own): result = own
1762 }
1763 }
1764 if !result.edits.isEmpty {
1765 guard currentText(path) == context.text else {
1766 return hooks.report(String(localized: "\(name) changed while \(hook.title) ran; its changes weren't made.",
1767 comment: "An after-todo-state-change hook's edits refused because its file changed"))
1768 }
1769 if let message = applyChanges(result.edits, to: path, expecting: context.text) { return hooks.report("\(hook.title): \(message)") }
1770 text = currentText(path) ?? text
1771 heading = UserCommandState.map([heading..<heading], through: result.edits)[0].lowerBound
1772 }
1773 if script.save, let entry = entry(path) { save(entry) }
1774 for case .message(let message) in result.effects { hooks.report(message) }
1775 }
1776 #endif
1777 }
1778
1779 /// Runs each `capture-before-finalize` hook, in file order, on `text`, the capture as filled
1780 /// from template `template`: the text to file, changed by the hooks' edits, or why a hook
1781 /// canceled the capture. Hooks from files not trusted here ask with `interactive`, and are
1782 /// skipped with a message without.
1783 public func runCaptureHooks(_ text: String, template: String, interactive: Bool) async -> Result<String, CaptureError> {
1784 #if canImport(WebKit)
1785 guard var hooks, let modules = userCommands.folder, let host = userCommandHost() else { return .success(text) }
1786 if !interactive { hooks.ask = nil }
1787 var text = text
1788 for hook in userCommands.hooks(.captureBeforeFinalize) {
1789 if let refusal = await trust(hook, modules: modules, hooks: hooks) {
1790 hooks.report("\(hook.title): \(refusal)")
1791 continue
1792 }
1793 let length = text.utf16.count
1794 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text, defaults: defaults), selection: [length..<length])
1795 let argument: [String: Any] = ["text": text, "template": template]
1796 guard let data = try? JSONSerialization.data(withJSONObject: argument), let json = String(data: data, encoding: .utf8) else { continue }
1797 let script = UserScript(file: hook.file, function: hook.function, timeout: hook.timeout, workspace: hook.workspace, title: hook.title,
1798 argument: json, buffer: UserCommandState(context, defaults: defaults))
1799 let result = await run(script, host: host, path: "", file: nil, workspace: hooks.workspace, ask: nil, report: hooks.report)
1800 .flatMap { Self.hookResult(script, $0) }
1801 switch result {
1802 case .failure(let failure):
1803 return .failure(CaptureError(message: failure.text))
1804 case .success(let result):
1805 for edit in result.edits.reversed() { text = edit.apply(to: text) }
1806 for case .message(let message) in result.effects { hooks.report(message) }
1807 }
1808 }
1641 #endif 1809 #endif
1810 return .success(text)
1811 }
1812
1813 #if canImport(WebKit)
1814 /// What a hook returned, read as for a command; it may return only `edits` and `message`.
1815 static func hookResult(_ script: UserScript, _ json: String) -> Result<EditResult, ScriptFailure> {
1816 let returned = (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any] ?? [:]
1817 if ["selection", "copy"].contains(where: { returned[$0].map { !($0 is NSNull) } ?? false }) {
1818 return .failure(ScriptFailure(text: "\(script.title): a hook returns only edits and message"))
1819 }
1820 return script.buffer.result(json).mapError { ScriptFailure(text: "\(script.title): \($0.message)") }
1821 }
1822
1823 /// Nil when `hook`'s file is trusted, or once the person allowed it; else why it didn't run.
1824 private func trust(_ hook: UserHook, modules: URL, hooks: UserHookHost) async -> String? {
1825 await withCheckedContinuation { continuation in
1826 UserCommandTrust.check(hook, modules: modules, trust: hooks.trust, ask: hooks.ask,
1827 run: { continuation.resume(returning: nil) }, refuse: { continuation.resume(returning: $0) })
1828 }
1642 } 1829 }
1643 1830
1831 /// The file at `path` as an edit context with the caret at `caret`, when its text is
1832 /// `expected`: the open buffer, or the file on disk.
1833 private func hookContext(_ path: String, expecting expected: String, caret: Int) -> EditContext? {
1834 if let entry = entry(path) {
1835 let document = entry.buffer.document
1836 guard document.text == expected else { return nil }
1837 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [caret..<caret])
1838 }
1839 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
1840 let state = loaded(bytes, path: path)
1841 guard state.text == expected else { return nil }
1842 return EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [caret..<caret])
1843 }
1844
1845 /// The text of `path`: its open buffer's, or the file's on disk.
1846 private func currentText(_ path: String) -> String? {
1847 if let entry = entry(path) { return entry.buffer.document.text }
1848 return (try? fileSystem.read(URL(fileURLWithPath: path))).map { loaded($0, path: path).text }
1849 }
1850 #endif
1851
1644 // MARK: - Locations 1852 // MARK: - Locations
1645 1853
1646 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets 1854 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
Sources/OrgApp/UserCommandFile.swift +69 −14 · view
@@ -5,7 +5,7 @@ import OrgCore
5public enum UserCommandFile { 5public enum UserCommandFile {
6 /// Reads `commands.toml` in `folder` into `store`, without running anything. The problems 6 /// Reads `commands.toml` in `folder` into `store`, without running anything. The problems
7 /// found, each starting with the file's name; a missing file is none. A module iCloud hasn't 7 /// found, each starting with the file's name; a missing file is none. A module iCloud hasn't
8 /// downloaded is reported and its download started; its command is kept. 8 /// downloaded is reported and its download started; its command or hook is kept.
9 @discardableResult 9 @discardableResult
10 public static func load(into store: UserCommands = .shared, folder: URL, read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }) -> [String] { 10 public static func load(into store: UserCommands = .shared, folder: URL, read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }) -> [String] {
11 let modules = folder.appendingPathComponent(UserCommands.folderName) 11 let modules = folder.appendingPathComponent(UserCommands.folderName)
@@ -15,17 +15,18 @@ public enum UserCommandFile {
15 } 15 }
16 var problems: [String] = [] 16 var problems: [String] = []
17 var commands: [UserCommand] = [] 17 var commands: [UserCommand] = []
18 var hooks: [UserHook] = []
18 do { 19 do {
19 commands = try UserCommands.parse(text, problems: &problems) { path in 20 (commands, hooks) = try UserCommands.manifest(text, problems: &problems) { path in
20 FileManager.default.fileExists(atPath: modules.appendingPathComponent(path).path) || placeholder(modules.appendingPathComponent(path)) != nil 21 FileManager.default.fileExists(atPath: modules.appendingPathComponent(path).path) || placeholder(modules.appendingPathComponent(path)) != nil
21 } 22 }
22 } catch { 23 } catch {
23 problems.append("\(error)") 24 problems.append("\(error)")
24 } 25 }
25 for file in Set(commands.map(\.file)).sorted() where needsDownload(modules.appendingPathComponent(file)) { 26 for file in Set(commands.map(\.file) + hooks.map(\.file)).sorted() where needsDownload(modules.appendingPathComponent(file)) {
26 problems.append("\(UserCommands.folderName)/\(file) isn't downloaded from iCloud yet") 27 problems.append("\(UserCommands.folderName)/\(file) isn't downloaded from iCloud yet")
27 } 28 }
28 store.replace(commands, folder: commands.isEmpty ? nil : modules) 29 store.replace(commands, hooks: hooks, folder: commands.isEmpty && hooks.isEmpty ? nil : modules)
29 return problems.map { "\(UserCommands.fileName): \($0)" } 30 return problems.map { "\(UserCommands.fileName): \($0)" }
30 } 31 }
31 32
@@ -148,20 +149,35 @@ public enum UserCommandTrust {
148 public let imports: [String] 149 public let imports: [String]
149 /// Its commands can also read every file in the folders and capture to them. 150 /// Its commands can also read every file in the folders and capture to them.
150 public let workspace: Bool 151 public let workspace: Bool
152 /// Asked for a hook on this event rather than a command.
153 public let hook: UserHook.Event?
151 154
152 public init(file: String, imports: [String] = [], workspace: Bool = false) { 155 public init(file: String, imports: [String] = [], workspace: Bool = false, hook: UserHook.Event? = nil) {
153 self.file = file 156 self.file = file
154 self.imports = imports 157 self.imports = imports
155 self.workspace = workspace 158 self.workspace = workspace
159 self.hook = hook
156 } 160 }
157 161
158 public var title: String { 162 public var title: String {
159 String(localized: "Run commands from \(file)?", comment: "Asked before a user command from a file not yet trusted on this device runs") 163 hook == nil
164 ? String(localized: "Run commands from \(file)?", comment: "Asked before a user command from a file not yet trusted on this device runs")
165 : String(localized: "Run hooks from \(file)?", comment: "Asked before a user hook from a file not yet trusted on this device runs")
160 } 166 }
161 167
162 /// The modules it imports, if any, and what its commands can do, a line each. 168 /// When the hook runs, the modules it imports, if any, and what its commands can do, a
169 /// line each.
163 public var message: String { 170 public var message: String {
164 var lines: [String] = [] 171 var lines: [String] = []
172 switch hook {
173 case .afterTodoStateChange?:
174 lines.append(String(localized: "This hook runs after you change an entry's TODO state.",
175 comment: "When an after-todo-state-change hook runs, in the question before it runs"))
176 case .captureBeforeFinalize?:
177 lines.append(String(localized: "This hook runs before a capture is filed and can change or cancel it.",
178 comment: "When a capture-before-finalize hook runs, in the question before it runs"))
179 case nil: break
180 }
165 if !imports.isEmpty { 181 if !imports.isEmpty {
166 let list = ListFormatter.localizedString(byJoining: imports) 182 let list = ListFormatter.localizedString(byJoining: imports)
167 lines.append(String(localized: "It imports \(list).", comment: "The modules a user command's file imports, in the question before it runs")) 183 lines.append(String(localized: "It imports \(list).", comment: "The modules a user command's file imports, in the question before it runs"))
@@ -183,17 +199,35 @@ public enum UserCommandTrust {
183 public static func check(_ command: UserCommand, modules: URL, trust: TrustStore, 199 public static func check(_ command: UserCommand, modules: URL, trust: TrustStore,
184 ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void, 200 ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void,
185 run: @escaping () -> Void, refuse: @escaping (String) -> Void) { 201 run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
186 guard let texts = UserCommandFile.moduleTexts(command.file, modules: modules) else { 202 check(file: command.file, workspace: command.workspace, modules: modules, trust: trust, ask: ask, run: run, refuse: refuse)
187 return refuse("No file \(UserCommands.folderName)/\(command.file)") 203 }
204
205 /// `check` for a hook: the same trust as its file's commands. Without `ask`, a hook from a
206 /// file not trusted here is refused.
207 public static func check(_ hook: UserHook, modules: URL, trust: TrustStore,
208 ask: (@MainActor (Question, @escaping (Answer?) -> Void) -> Void)?,
209 run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
210 let shown = "\(UserCommands.folderName)/\(hook.file)"
211 check(file: hook.file, workspace: hook.workspace, hook: hook.event, modules: modules, trust: trust, ask: ask ?? { _, _ in
212 refuse(String(localized: "\(shown) isn't trusted on this device yet, and orgstar can't ask here.",
213 comment: "A hook from a file not yet trusted, skipped where orgstar can't ask, as for a capture from Shortcuts"))
214 }, run: run, refuse: refuse)
215 }
216
217 private static func check(file: String, workspace: Bool, hook: UserHook.Event? = nil, modules: URL, trust: TrustStore,
218 ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void,
219 run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
220 guard let texts = UserCommandFile.moduleTexts(file, modules: modules) else {
221 return refuse("No file \(UserCommands.folderName)/\(file)")
188 } 222 }
189 let text = UserCommandFile.trustedText(texts) 223 let text = UserCommandFile.trustedText(texts)
190 let path = modules.appendingPathComponent(command.file).path 224 let path = modules.appendingPathComponent(file).path
191 let workspaceText = workspaceTrust + text 225 let workspaceText = workspaceTrust + text
192 let accepted = command.workspace ? [workspaceText] : [text, workspaceText] 226 let accepted = workspace ? [workspaceText] : [text, workspaceText]
193 if accepted.contains(where: { trust.isTrusted(path: path, content: $0) }) { return run() } 227 if accepted.contains(where: { trust.isTrusted(path: path, content: $0) }) { return run() }
194 let imports = texts.filter { $0.key != command.file && $0.value != nil }.keys.sorted() 228 let imports = texts.filter { $0.key != file && $0.value != nil }.keys.sorted()
195 let question = Question(file: "\(UserCommands.folderName)/\(command.file)", 229 let question = Question(file: "\(UserCommands.folderName)/\(file)",
196 imports: imports.map { "\(UserCommands.folderName)/\($0)" }, workspace: command.workspace) 230 imports: imports.map { "\(UserCommands.folderName)/\($0)" }, workspace: workspace, hook: hook)
197 ask(question) { answer in 231 ask(question) { answer in
198 switch answer { 232 switch answer {
199 case .runOnce: run() 233 case .runOnce: run()
@@ -205,3 +239,24 @@ public enum UserCommandTrust {
205 } 239 }
206 } 240 }
207} 241}
242
243/// What hooks need from the app: the trust kept for their files, the question for a file not yet
244/// trusted where the app can ask, where their messages go, and the folders for hooks with
245/// `workspace = true`.
246@MainActor
247public struct UserHookHost {
248 public var trust: TrustStore
249 /// Nil where the app can't ask; a hook from a file not trusted here is then skipped with a
250 /// message.
251 public var ask: (@MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void)?
252 public var report: @MainActor (String) -> Void
253 public var workspace: UserCommandWorkspace?
254
255 public init(trust: TrustStore, ask: (@MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void)?,
256 report: @escaping @MainActor (String) -> Void, workspace: UserCommandWorkspace? = nil) {
257 self.trust = trust
258 self.ask = ask
259 self.report = report
260 self.workspace = workspace
261 }
262}
Sources/OrgApp/XCallback.swift +3 −3 · view
@@ -232,7 +232,7 @@ public struct XCallbackRunner {
232 // A link that launched the app can come before the folders were first read. 232 // A link that launched the app can come before the folders were first read.
233 if workspace.files.isEmpty { await workspace.refresh() } 233 if workspace.files.isEmpty { await workspace.refresh() }
234 switch action { 234 switch action {
235 case .capture: return capture(request, sheet: interactive) 235 case .capture: return await capture(request, sheet: interactive)
236 case .open: return open(request) 236 case .open: return open(request)
237 case .agenda: return .reply(await agenda(request)) 237 case .agenda: return .reply(await agenda(request))
238 case .clockIn: return .reply(await clockIn(request, ask: ask)) 238 case .clockIn: return .reply(await clockIn(request, ask: ask))
@@ -273,12 +273,12 @@ public struct XCallbackRunner {
273 } 273 }
274 } 274 }
275 275
276 private func capture(_ request: XCallbackRequest, sheet: Bool) -> Step { 276 private func capture(_ request: XCallbackRequest, sheet: Bool) async -> Step {
277 let properties = Self.properties(request) 277 let properties = Self.properties(request)
278 if sheet { return .capture(template: request.value("template"), properties: properties) } 278 if sheet { return .capture(template: request.value("template"), properties: properties) }
279 var answers = request.parameters 279 var answers = request.parameters
280 for name in Self.reservedCaptureParameters { answers[name] = nil } 280 for name in Self.reservedCaptureParameters { answers[name] = nil }
281 let placed = session.capture( 281 let placed = await session.captureRunningHooks(
282 request.parameters["text"] ?? "", templateKey: request.value("template"), templates: templates(), workspace: workspace, clock: clock, 282 request.parameters["text"] ?? "", templateKey: request.value("template"), templates: templates(), workspace: workspace, clock: clock,
283 clipboard: clipboard(), userName: userName, answers: answers, properties: properties 283 clipboard: clipboard(), userName: userName, answers: answers, properties: properties
284 ) 284 )
Sources/OrgCore/Commands/Command.swift +20 · view
@@ -274,6 +274,26 @@ public enum Effect: Sendable, Equatable {
274 case timer(OrgTimer?) 274 case timer(OrgTimer?)
275 /// A snippet was expanded; its fields are filled in next. 275 /// A snippet was expanded; its fields are filled in next.
276 case snippet(SnippetSession) 276 case snippet(SnippetSession)
277 /// An entry's TODO keyword changed, as `org-todo` changes it; the app runs the
278 /// `after-todo-state-change` hooks.
279 case todoStateChanged(TodoStateChange)
280}
281
282/// A change of an entry's TODO keyword.
283public struct TodoStateChange: Sendable, Equatable {
284 /// Where the entry's heading starts, in the new text.
285 public let heading: Int
286 /// The keyword before, nil for none.
287 public let from: String?
288 /// The keyword set, nil for none. For a repeating entry marked done it is the done
289 /// keyword, though the repeat has put the entry back, as `org-state` is in Org's hook.
290 public let to: String?
291
292 public init(heading: Int, from: String?, to: String?) {
293 self.heading = heading
294 self.from = from
295 self.to = to
296 }
277} 297}
278 298
279public struct EditResult: Sendable, Equatable { 299public struct EditResult: Sendable, Equatable {
Sources/OrgCore/Commands/EmacsBuffer.swift +4 −1 · view
@@ -40,6 +40,8 @@ final class EmacsBuffer {
40 var lastInsertedTimestamp: String? 40 var lastInsertedTimestamp: String?
41 /// Shown after the command commits, as `message`. 41 /// Shown after the command commits, as `message`.
42 var message: String? 42 var message: String?
43 /// TODO keyword changes `afterTodoChange` saw: the heading, the keyword before and after.
44 var todoChanges: [(heading: Marker, from: String?, to: String?)] = []
43 45
44 let options: EditingOptions 46 let options: EditingOptions
45 47
@@ -501,7 +503,8 @@ func commitBuffer(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void)
501 while prefix > 0, prefix < old.count, UTF16.isTrailSurrogate(old[prefix]) { prefix -= 1 } 503 while prefix > 0, prefix < old.count, UTF16.isTrailSurrogate(old[prefix]) { prefix -= 1 }
502 while suffix > 0, UTF16.isTrailSurrogate(old[old.count - suffix]) { suffix -= 1 } 504 while suffix > 0, UTF16.isTrailSurrogate(old[old.count - suffix]) { suffix -= 1 }
503 let caret = buffer.point 505 let caret = buffer.point
504 let effects: [Effect] = buffer.message.map { [.message($0)] } ?? [] 506 let effects: [Effect] = (buffer.message.map { [.message($0)] } ?? [])
507 + buffer.todoChanges.map { .todoStateChanged(TodoStateChange(heading: $0.heading.position, from: $0.from, to: $0.to)) }
505 guard old.count != new.count || prefix != old.count else { 508 guard old.count != new.count || prefix != old.count else {
506 return .commit(EditResult(baseRevision: context.revision, edits: [], selection: [caret..<caret], effects: effects)) 509 return .commit(EditResult(baseRevision: context.revision, edits: [], selection: [caret..<caret], effects: effects))
507 } 510 }
Sources/OrgCore/Commands/TodoLogging.swift +2 · view
@@ -183,9 +183,11 @@ extension EmacsBuffer {
183 183
184 /// What `org-todo` does after the keyword went from `previous` to the current one: CLOSED, 184 /// What `org-todo` does after the keyword went from `previous` to the current one: CLOSED,
185 /// the repeat of a repeating entry, and the log note, asking for its text with `answers`. 185 /// the repeat of a repeating entry, and the log note, asking for its text with `answers`.
186 /// The change is kept for the result's `todoStateChanged` effect.
186 func afterTodoChange(previous: String?, answers: [String: String]) throws { 187 func afterTodoChange(previous: String?, answers: [String: String]) throws {
187 let state = todoKeyword 188 let state = todoKeyword
188 guard state != previous else { return } 189 guard state != previous else { return }
190 if let heading = saveExcursion({ try? backToHeading() }) { todoChanges.append((marker(heading), previous, state)) }
189 let log = logSettings() 191 let log = logSettings()
190 var setup = try saveExcursion { try todoLogging(previous: previous, state: state, log: log) } 192 var setup = try saveExcursion { try todoLogging(previous: previous, state: state, log: log) }
191 if let state, settings.isDone(state), !(previous.map(settings.isDone) ?? false), 193 if let state, settings.isDone(state), !(previous.map(settings.isDone) ?? false),
Sources/OrgCore/Commands/UserCommandAPI.swift +3 −2 · view
@@ -268,7 +268,8 @@ public struct UserCommandState: Sendable {
268 var options = context.options 268 var options = context.options
269 for effect in result.effects { 269 for effect in result.effects {
270 switch effect { 270 switch effect {
271 case .fold, .sparseTree, .snippet: continue 271 // A command's or hook's own TODO changes run no hooks.
272 case .fold, .sparseTree, .snippet, .todoStateChanged: continue
272 case .timer(let timer): options.timer = timer 273 case .timer(let timer): options.timer = timer
273 default: break 274 default: break
274 } 275 }
@@ -303,7 +304,7 @@ public struct UserCommandState: Sendable {
303 304
304 /// Ranges moved by edits that don't overlap: an offset inside or at the end of a replaced 305 /// 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 /// range, or at an insertion, moves past the replacement.
306 static func map(_ ranges: [Range<Int>], through edits: [TextEdit]) -> [Range<Int>] { 307 public static func map(_ ranges: [Range<Int>], through edits: [TextEdit]) -> [Range<Int>] {
307 let sorted = edits.sorted { $0.range.lowerBound < $1.range.lowerBound } 308 let sorted = edits.sorted { $0.range.lowerBound < $1.range.lowerBound }
308 func map(_ offset: Int) -> Int { 309 func map(_ offset: Int) -> Int {
309 var shift = 0 310 var shift = 0
Sources/OrgCore/Commands/UserCommands.swift +116 −43 · view
@@ -53,6 +53,37 @@ public struct UserCommandRequest: Sendable, Equatable {
53 } 53 }
54} 54}
55 55
56/// A function of a module in `commands/` that runs when something happens rather than from a
57/// key, declared as `[[hook]]` in `commands.toml`. There are no per-keystroke hooks.
58public struct UserHook: Sendable, Equatable {
59 public enum Event: String, Sendable, CaseIterable {
60 /// `org-after-todo-state-change-hook`: after a command changed an entry's TODO keyword.
61 case afterTodoStateChange = "after-todo-state-change"
62 /// `org-capture-before-finalize-hook`: before a capture is filed.
63 case captureBeforeFinalize = "capture-before-finalize"
64 }
65
66 public let event: Event
67 /// The module, relative to `commands/`.
68 public let file: String
69 public let function: String
70 /// Seconds, at most `UserCommands.maximumTimeout`.
71 public let timeout: Int
72 /// `workspace = true`, as for commands.
73 public let workspace: Bool
74
75 public init(event: Event, file: String, function: String, timeout: Int = UserCommands.defaultTimeout, workspace: Bool = false) {
76 self.event = event
77 self.file = file
78 self.function = function
79 self.timeout = timeout
80 self.workspace = workspace
81 }
82
83 /// How messages name it: `logDone in commands/todo.js`.
84 public var title: String { "\(function) in \(UserCommands.folderName)/\(file)" }
85}
86
56/// The commands of `commands.toml`, which the app reads from the configuration folder. 87/// The commands of `commands.toml`, which the app reads from the configuration folder.
57public final class UserCommands: @unchecked Sendable { 88public final class UserCommands: @unchecked Sendable {
58 public static let shared = UserCommands() 89 public static let shared = UserCommands()
@@ -67,6 +98,7 @@ public final class UserCommands: @unchecked Sendable {
67 98
68 private let lock = NSLock() 99 private let lock = NSLock()
69 private var commands: [UserCommand] = [] 100 private var commands: [UserCommand] = []
101 private var hookList: [UserHook] = []
70 private var modules: URL? 102 private var modules: URL?
71 103
72 public init() {} 104 public init() {}
@@ -77,29 +109,44 @@ public final class UserCommands: @unchecked Sendable {
77 /// The `commands` folder the modules are in; nil before a file was read. 109 /// The `commands` folder the modules are in; nil before a file was read.
78 public var folder: URL? { lock.withLock { modules } } 110 public var folder: URL? { lock.withLock { modules } }
79 111
112 /// The hooks for `event`, in file order.
113 public func hooks(_ event: UserHook.Event) -> [UserHook] {
114 lock.withLock { hookList.filter { $0.event == event } }
115 }
116
80 public func command(_ id: String) -> UserCommand? { 117 public func command(_ id: String) -> UserCommand? {
81 guard id.hasPrefix(Self.commandPrefix) else { return nil } 118 guard id.hasPrefix(Self.commandPrefix) else { return nil }
82 let name = id.dropFirst(Self.commandPrefix.count) 119 let name = id.dropFirst(Self.commandPrefix.count)
83 return lock.withLock { commands.first { $0.name == name } } 120 return lock.withLock { commands.first { $0.name == name } }
84 } 121 }
85 122
86 /// Replaces every command, as from the file, with the folder their modules are in. 123 /// Replaces every command and hook, as from the file, with the folder their modules are in.
87 public func replace(_ all: [UserCommand], folder: URL?) { 124 public func replace(_ all: [UserCommand], hooks: [UserHook] = [], folder: URL?) {
88 lock.withLock { 125 lock.withLock {
89 commands = all 126 commands = all
127 hookList = hooks
90 modules = folder 128 modules = folder
91 } 129 }
92 } 130 }
93 131
94 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout", "workspace"] 132 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout", "workspace"]
133 static let hookKeys: Set<String> = ["event", "file", "function", "timeout", "workspace"]
95 134
96 /// The commands of a `commands.toml`. Entries that can't be used are skipped and reported in 135 /// The commands of a `commands.toml`, as `manifest` reads them.
97 /// `problems`; with a missing or newer `api`, none is used. `exists` says whether a module
98 /// path (relative to `commands/`) is there. A file that isn't valid TOML throws.
99 public static func parse(_ toml: String, problems: inout [String], exists: (String) -> Bool) throws -> [UserCommand] { 136 public static func parse(_ toml: String, problems: inout [String], exists: (String) -> Bool) throws -> [UserCommand] {
137 try manifest(toml, problems: &problems, exists: exists).commands
138 }
139
140 /// The commands and hooks of a `commands.toml`. Entries that can't be used are skipped and
141 /// reported in `problems`; with a missing or newer `api`, none is used. `exists` says
142 /// whether a module path (relative to `commands/`) is there. A file that isn't valid TOML
143 /// throws.
144 public static func manifest(_ toml: String, problems: inout [String], exists: (String) -> Bool) throws
145 -> (commands: [UserCommand], hooks: [UserHook]) {
100 let tables = try TOML.parse(toml) 146 let tables = try TOML.parse(toml)
101 var api: Int? 147 var api: Int?
102 var result: [UserCommand] = [] 148 var result: [UserCommand] = []
149 var hooks: [UserHook] = []
103 var names = Set<String>() 150 var names = Set<String>()
104 for table in tables { 151 for table in tables {
105 if table.name.isEmpty { 152 if table.name.isEmpty {
@@ -113,10 +160,25 @@ public final class UserCommands: @unchecked Sendable {
113 } 160 }
114 continue 161 continue
115 } 162 }
116 guard table.name == "command", table.isArrayElement else { 163 guard ["command", "hook"].contains(table.name), table.isArrayElement else {
117 problems.append("line \(table.line): unknown table [\(table.name)]") 164 problems.append("line \(table.line): unknown table [\(table.name)]")
118 continue 165 continue
119 } 166 }
167 if table.name == "hook" {
168 func problem(_ text: String) { problems.append("hook at line \(table.line): \(text)") }
169 for key in table.keys where !hookKeys.contains(key) { problem("unknown key \(key)") }
170 guard let name = table.values["event"]?.string else {
171 problem("missing event")
172 continue
173 }
174 guard let event = UserHook.Event(rawValue: name) else {
175 problem("unknown event \(name); the events are \(UserHook.Event.allCases.map(\.rawValue).joined(separator: " and "))")
176 continue
177 }
178 guard let module = module(table, exists: exists, problem: problem) else { continue }
179 hooks.append(UserHook(event: event, file: module.file, function: module.function, timeout: module.timeout, workspace: module.workspace))
180 continue
181 }
120 guard let name = table.values["name"]?.string, NamedMacros.isValidName(name) else { 182 guard let name = table.values["name"]?.string, NamedMacros.isValidName(name) else {
121 problems.append("line \(table.line): command needs a name of letters, digits, - and _") 183 problems.append("line \(table.line): command needs a name of letters, digits, - and _")
122 continue 184 continue
@@ -127,56 +189,67 @@ public final class UserCommands: @unchecked Sendable {
127 problem("defined twice") 189 problem("defined twice")
128 continue 190 continue
129 } 191 }
130 guard let file = table.values["file"]?.string, !file.isEmpty else { 192 guard let module = module(table, exists: exists, problem: problem) else { continue }
131 problem("missing file")
132 continue
133 }
134 guard isModulePath(file) else {
135 problem("file must be a .js or .mjs file in \(folderName)/")
136 continue
137 }
138 guard exists(file) else {
139 problem("no file \(folderName)/\(file)")
140 continue
141 }
142 guard let function = table.values["function"]?.string, isIdentifier(function) else {
143 problem("function must be the name of an exported function")
144 continue
145 }
146 let when = table.values["when"]?.string 193 let when = table.values["when"]?.string
147 if let when, !KeyContext.names.contains(when) { 194 if let when, !KeyContext.names.contains(when) {
148 problem("unknown context \(when)") 195 problem("unknown context \(when)")
149 continue 196 continue
150 } 197 }
151 var timeout = defaultTimeout
152 if let value = table.values["timeout"] {
153 guard let seconds = value.integer, (1...maximumTimeout).contains(seconds) else {
154 problem("timeout must be 1 to \(maximumTimeout) seconds")
155 continue
156 }
157 timeout = seconds
158 }
159 var workspace = false
160 if let value = table.values["workspace"] {
161 guard let flag = value.bool else {
162 problem("workspace must be true or false")
163 continue
164 }
165 workspace = flag
166 }
167 if let value = table.values["title"], value.string == nil { problem("title must be a string") } 198 if let value = table.values["title"], value.string == nil { problem("title must be a string") }
168 let title = table.values["title"]?.string.flatMap { $0.isEmpty ? nil : $0 } ?? name 199 let title = table.values["title"]?.string.flatMap { $0.isEmpty ? nil : $0 } ?? name
169 result.append(UserCommand(name: name, title: title, file: file, function: function, when: when, timeout: timeout, workspace: workspace)) 200 result.append(UserCommand(name: name, title: title, file: module.file, function: module.function, when: when,
201 timeout: module.timeout, workspace: module.workspace))
170 } 202 }
171 guard let api else { 203 guard let api else {
172 if !result.isEmpty || tables.contains(where: { $0.name == "command" }) { problems.append("missing api = \(apiVersion)") } 204 if !result.isEmpty || !hooks.isEmpty || tables.contains(where: { ["command", "hook"].contains($0.name) }) {
173 return [] 205 problems.append("missing api = \(apiVersion)")
206 }
207 return ([], [])
174 } 208 }
175 guard api == apiVersion else { 209 guard api == apiVersion else {
176 problems.append(api > apiVersion ? "api \(api) needs a newer orgstar" : "unknown api \(api)") 210 problems.append(api > apiVersion ? "api \(api) needs a newer orgstar" : "unknown api \(api)")
177 return [] 211 return ([], [])
212 }
213 return (result, hooks)
214 }
215
216 /// The `file`, `function`, `timeout` and `workspace` of a command or hook; nil once the
217 /// first that can't be used is reported.
218 private static func module(_ table: TOML.Table, exists: (String) -> Bool, problem: (String) -> Void)
219 -> (file: String, function: String, timeout: Int, workspace: Bool)? {
220 guard let file = table.values["file"]?.string, !file.isEmpty else {
221 problem("missing file")
222 return nil
223 }
224 guard isModulePath(file) else {
225 problem("file must be a .js or .mjs file in \(folderName)/")
226 return nil
227 }
228 guard exists(file) else {
229 problem("no file \(folderName)/\(file)")
230 return nil
231 }
232 guard let function = table.values["function"]?.string, isIdentifier(function) else {
233 problem("function must be the name of an exported function")
234 return nil
235 }
236 var timeout = defaultTimeout
237 if let value = table.values["timeout"] {
238 guard let seconds = value.integer, (1...maximumTimeout).contains(seconds) else {
239 problem("timeout must be 1 to \(maximumTimeout) seconds")
240 return nil
241 }
242 timeout = seconds
243 }
244 var workspace = false
245 if let value = table.values["workspace"] {
246 guard let flag = value.bool else {
247 problem("workspace must be true or false")
248 return nil
249 }
250 workspace = flag
178 } 251 }
179 return result 252 return (file, function, timeout, workspace)
180 } 253 }
181 254
182 /// A path of `.js` or `.mjs` file below `commands/`, without `.`, `..` or empty parts. 255 /// A path of `.js` or `.mjs` file below `commands/`, without `.`, `..` or empty parts.
Sources/Orgstar/CaptureIntent.swift +2 −2 · view
@@ -29,14 +29,14 @@ struct CaptureIntent: AppIntent {
29 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar+") } 29 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar+") }
30 for _ in 0..<50 where Self.environment == nil { try? await Task.sleep(for: .milliseconds(100)) } 30 for _ in 0..<50 where Self.environment == nil { try? await Task.sleep(for: .milliseconds(100)) }
31 guard let (workspace, session, clock, commands) = Self.environment else { throw Failure(message: "orgstar isn't ready") } 31 guard let (workspace, session, clock, commands) = Self.environment else { throw Failure(message: "orgstar isn't ready") }
32 let placed = session.capture( 32 let placed = await session.captureRunningHooks(
33 text, templateKey: template, templates: CaptureTemplates.load().templates, workspace: workspace, clock: clock, 33 text, templateKey: template, templates: CaptureTemplates.load().templates, workspace: workspace, clock: clock,
34 clipboard: NSPasteboard.general.string(forType: .string) ?? "", userName: NSFullUserName() 34 clipboard: NSPasteboard.general.string(forType: .string) ?? "", userName: NSFullUserName()
35 ) 35 )
36 switch placed { 36 switch placed {
37 case .failure(let error): 37 case .failure(let error):
38 throw Failure(message: error.message) 38 throw Failure(message: error.message)
39 case .success(let chosen): 39 case .success(let (chosen, _, _)):
40 let message = "Captured to \(CaptureView.target(chosen))" 40 let message = "Captured to \(CaptureView.target(chosen))"
41 commands.show(message) 41 commands.show(message)
42 return .result(value: message, dialog: "\(message)") 42 return .result(value: message, dialog: "\(message)")
Sources/Orgstar/CaptureView.swift +22 · view
@@ -37,6 +37,8 @@ struct CaptureView: View {
37 @State private var roam: RoamCapture? 37 @State private var roam: RoamCapture?
38 /// The `captureRequest` serial of an x-callback-url capture, whose caller hears how it ends. 38 /// The `captureRequest` serial of an x-callback-url capture, whose caller hears how it ends.
39 @State private var callbackSerial: Int? 39 @State private var callbackSerial: Int?
40 /// The capture's hooks are running.
41 @State private var finishing = false
40 @FocusState private var focused: Bool 42 @FocusState private var focused: Bool
41 @Environment(\.dismissWindow) private var dismissWindow 43 @Environment(\.dismissWindow) private var dismissWindow
42 @Environment(\.openWindow) private var openWindow 44 @Environment(\.openWindow) private var openWindow
@@ -287,7 +289,27 @@ struct CaptureView: View {
287 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day, hour: time.hour, minute: time.minute, second: time.second)) ?? now 289 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day, hour: time.hour, minute: time.minute, second: time.second)) ?? now
288 } 290 }
289 291
292 /// Files the capture once the `capture-before-finalize` hooks have run on it; a hook that
293 /// fails cancels it, with the window left open.
290 private func finish(refile: Bool = false) { 294 private func finish(refile: Bool = false) {
295 guard let template, !finishing else { return }
296 guard session.hasHooks(.captureBeforeFinalize) else { return file(refile: refile) }
297 finishing = true
298 Task {
299 let hooked = await session.runCaptureHooks(text, template: template.key, interactive: true)
300 finishing = false
301 switch hooked {
302 case .failure(let error):
303 problem = error.message
304 if template.options.immediateFinish { editing = true }
305 case .success(let changed):
306 text = changed
307 file(refile: refile)
308 }
309 }
310 }
311
312 private func file(refile: Bool) {
291 guard let template else { return } 313 guard let template else { return }
292 let opened = context.now 314 let opened = context.now
293 let now = Date() 315 let now = Date()
Sources/Orgstar/ContentView.swift +12 · view
@@ -365,6 +365,18 @@ struct ContentView: View {
365 .onAppear { 365 .onAppear {
366 commands.externalHandler = runExternal 366 commands.externalHandler = runExternal
367 commands.userCommandHandler = runUserCommand 367 commands.userCommandHandler = runUserCommand
368 var hookAccess = UserCommandWorkspace(workspace: workspace, clock: clock)
369 hookAccess.userName = NSFullUserName()
370 // Hooks run from the agenda and the capture window too, so the question is an alert.
371 session.hooks = UserHookHost(trust: trust, ask: { question, reply in
372 let alert = NSAlert()
373 alert.messageText = question.title
374 alert.informativeText = question.message
375 let answers: [UserCommandTrust.Answer] = [.dontRun, .runOnce, .always]
376 for answer in answers { alert.addButton(withTitle: answer.title) }
377 let index = alert.runModal().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue
378 reply(answers.indices.contains(index) ? answers[index] : nil)
379 }, report: { commands.show($0) }, workspace: hookAccess)
368 commands.filesHandler = { attachActions.drop($0) } 380 commands.filesHandler = { attachActions.drop($0) }
369 commands.imageHandler = { attachActions.yankImage($0, ext: $1) } 381 commands.imageHandler = { attachActions.yankImage($0, ext: $1) }
370 #if APPSTORE 382 #if APPSTORE
Sources/Orgstar/PaneView.swift +1 · view
@@ -147,6 +147,7 @@ struct PaneView: NSViewRepresentable {
147 NSPasteboard.general.setString(text, forType: .string) 147 NSPasteboard.general.setString(text, forType: .string)
148 case .refreshSetup: session?.refreshSetup() 148 case .refreshSetup: session?.refreshSetup()
149 case .timer(let timer): TimerModel.shared.set(timer) 149 case .timer(let timer): TimerModel.shared.set(timer)
150 case .todoStateChanged: session?.afterTodoStateChange([effect], in: path)
150 case .message, .sparseTree, .fold, .snippet: break 151 case .message, .sparseTree, .fold, .snippet: break
151 } 152 }
152 } 153 }
Sources/OrgstarCLI/CaptureCommand.swift +7 · view
@@ -95,6 +95,13 @@ enum CaptureCommand {
95 throw Failure(.failure, "Can't create \(path): \(error.localizedDescription)") 95 throw Failure(.failure, "Can't create \(path): \(error.localizedDescription)")
96 } 96 }
97 } 97 }
98 // Hooks run in the app's WebKit worker, which the command-line tool doesn't have.
99 var ignored: [String] = []
100 if let manifest = try? String(contentsOf: workspace.configFile(UserCommands.fileName), encoding: .utf8),
101 let hooks = try? UserCommands.manifest(manifest, problems: &ignored, exists: { _ in true }).hooks,
102 hooks.contains(where: { $0.event == .captureBeforeFinalize }) {
103 workspace.host.error("orgstar: \(UserHook.Event.captureBeforeFinalize.rawValue) hooks in \(UserCommands.fileName) run only in the app; captured without them\n")
104 }
98 let (result, text) = try workspace.perform(CapturePlacement(text: filled.text, template: chosen), path: path, at: 0) 105 let (result, text) = try workspace.perform(CapturePlacement(text: filled.text, template: chosen), path: path, at: 0)
99 let offset = result.selection?.first?.lowerBound ?? 0 106 let offset = result.selection?.first?.lowerBound ?? 0
100 workspace.host.print("Captured to \(path):\(Workspace.line(of: offset, in: text))") 107 workspace.host.print("Captured to \(path):\(Workspace.line(of: offset, in: text))")
Sources/OrgstarMobile/CaptureIntent.swift +2 −2 · view
@@ -26,14 +26,14 @@ struct CaptureIntent: AppIntent {
26 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar+") } 26 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar+") }
27 let model = MobileModel.shared 27 let model = MobileModel.shared
28 guard let workspace = model.workspace else { throw Failure(message: model.failure ?? "orgstar isn't ready") } 28 guard let workspace = model.workspace else { throw Failure(message: model.failure ?? "orgstar isn't ready") }
29 let placed = model.session.capture( 29 let placed = await model.session.captureRunningHooks(
30 text, templateKey: template, templates: CaptureTemplates.load().templates, workspace: workspace, clock: model.clock, 30 text, templateKey: template, templates: CaptureTemplates.load().templates, workspace: workspace, clock: model.clock,
31 clipboard: "", userName: "" 31 clipboard: "", userName: ""
32 ) 32 )
33 switch placed { 33 switch placed {
34 case .failure(let error): 34 case .failure(let error):
35 throw Failure(message: error.message) 35 throw Failure(message: error.message)
36 case .success(let chosen): 36 case .success(let (chosen, _, _)):
37 for path in model.session.dirtyPaths { _ = model.session.save(path) } 37 for path in model.session.dirtyPaths { _ = model.session.save(path) }
38 let message = "Captured with \(chosen.name)" 38 let message = "Captured with \(chosen.name)"
39 return .result(value: message, dialog: "\(message)") 39 return .result(value: message, dialog: "\(message)")
Sources/OrgstarMobile/CaptureScreen.swift +26 −4 · view
@@ -37,6 +37,8 @@ struct CaptureScreen: View {
37 /// The entry's date or tags sheet: on the form, not its section, which may not be in the window. 37 /// The entry's date or tags sheet: on the form, not its section, which may not be in the window.
38 @State private var planning: EntryPlanning? 38 @State private var planning: EntryPlanning?
39 @State private var choosingTags = false 39 @State private var choosingTags = false
40 /// The capture's hooks are running.
41 @State private var finishing = false
40 @FocusState private var focused: Bool 42 @FocusState private var focused: Bool
41 43
42 private var template: CaptureTemplate? { templates.first { $0.key == key } } 44 private var template: CaptureTemplate? { templates.first { $0.key == key } }
@@ -94,11 +96,11 @@ struct CaptureScreen: View {
94 .toolbar { 96 .toolbar {
95 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } 97 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
96 if editing, template?.kind == .entry, request.roam == nil { 98 if editing, template?.kind == .entry, request.roam == nil {
97 ToolbarItem(placement: .bottomBar) { Button("Refile…") { file(refile: true) } } 99 ToolbarItem(placement: .bottomBar) { Button("Refile…") { finish(refile: true) } }
98 } 100 }
99 ToolbarItem(placement: .confirmationAction) { 101 ToolbarItem(placement: .confirmationAction) {
100 if editing { 102 if editing {
101 Button("Capture") { file() }.disabled(template == nil) 103 Button("Capture") { finish() }.disabled(template == nil)
102 } else { 104 } else {
103 Button("Continue", action: fill) 105 Button("Continue", action: fill)
104 } 106 }
@@ -173,7 +175,7 @@ struct CaptureScreen: View {
173 problem = nil 175 problem = nil
174 editing = true 176 editing = true
175 focused = true 177 focused = true
176 if template.options.immediateFinish { file() } 178 if template.options.immediateFinish { finish() }
177 case .failure(.message(let message)): 179 case .failure(.message(let message)):
178 problem = message 180 problem = message
179 } 181 }
@@ -200,7 +202,27 @@ struct CaptureScreen: View {
200 return calendar.date(from: parts) ?? Date() 202 return calendar.date(from: parts) ?? Date()
201 } 203 }
202 204
203 private func file(refile: Bool = false) { 205 /// Files the capture once the `capture-before-finalize` hooks have run on it; a hook that
206 /// fails cancels it, with the sheet left open.
207 private func finish(refile: Bool = false) {
208 guard let template, !finishing else { return }
209 guard session.hasHooks(.captureBeforeFinalize) else { return file(refile: refile) }
210 finishing = true
211 Task {
212 let hooked = await session.runCaptureHooks(text, template: template.key, interactive: true)
213 finishing = false
214 switch hooked {
215 case .failure(let error):
216 problem = error.message
217 editing = true
218 case .success(let changed):
219 text = changed
220 file(refile: refile)
221 }
222 }
223 }
224
225 private func file(refile: Bool) {
204 guard let template else { return } 226 guard let template else { return }
205 let now = Date() 227 let now = Date()
206 let placed: Result<(path: String, offset: Int), CaptureError> 228 let placed: Result<(path: String, offset: Int), CaptureError>
Sources/OrgstarMobile/EditorScreen.swift +1 · view
@@ -548,6 +548,7 @@ struct EditorScreen: View {
548 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } } 548 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
549 editor.onUserCommand = { request, finished in runUserCommand(request, finished: finished) } 549 editor.onUserCommand = { request, finished in runUserCommand(request, finished: finished) }
550 editor.onRefreshSetup = { session.refreshSetup() } 550 editor.onRefreshSetup = { session.refreshSetup() }
551 editor.onTodoStateChange = { [path] in session.afterTodoStateChange($0, in: path) }
551 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) } 552 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
552 editor.keymap = model.keymap 553 editor.keymap = model.keymap
553 editor.modal = model.modalKeys 554 editor.modal = model.modalKeys
Sources/OrgstarMobile/MobileEditor.swift +3 · view
@@ -131,6 +131,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
131 var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)? 131 var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)?
132 /// The file's setup files to read again (C-c C-c on a keyword line). 132 /// The file's setup files to read again (C-c C-c on a keyword line).
133 var onRefreshSetup: (() -> Void)? 133 var onRefreshSetup: (() -> Void)?
134 /// TODO keyword changes a command made, for the `after-todo-state-change` hooks.
135 var onTodoStateChange: (([Effect]) -> Void)?
134 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `). 136 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
135 var onEditBlock: ((BlockEdit) -> Void)? 137 var onEditBlock: ((BlockEdit) -> Void)?
136 /// A followed timestamp's agenda days: the first (a `Days` number) and how many. 138 /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
@@ -396,6 +398,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
396 state.folds.insert(start) 398 state.folds.insert(start)
397 setFolds(state) 399 setFolds(state)
398 case .refreshSetup: onRefreshSetup?() 400 case .refreshSetup: onRefreshSetup?()
401 case .todoStateChanged: onTodoStateChange?([effect])
399 case .timer(let timer): TimerModel.shared.set(timer) 402 case .timer(let timer): TimerModel.shared.set(timer)
400 case .snippet(let session): startSnippet(session) 403 case .snippet(let session): startSnippet(session)
401 default: break 404 default: break
Sources/OrgstarMobile/MobileModel.swift +3 · view
@@ -117,6 +117,9 @@ final class MobileModel {
117 guard let self else { return } 117 guard let self else { return }
118 _ = self.clock.textChanged(path, self.session) 118 _ = self.clock.textChanged(path, self.session)
119 } 119 }
120 // Shortcuts' capture can run without a window; the window's view asks and shows messages.
121 session.hooks = UserHookHost(trust: TrustStore(), ask: nil, report: { _ in },
122 workspace: workspace.map { UserCommandWorkspace(workspace: $0, clock: clock) })
120 // A new Dynamic Type size restyles editors and the reader. 123 // A new Dynamic Type size restyles editors and the reader.
121 sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in 124 sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
122 MainActor.assumeIsolated { self?.settingsVersion += 1 } 125 MainActor.assumeIsolated { self?.settingsVersion += 1 }
Sources/OrgstarMobile/OrgstarMobileApp.swift +18 · view
@@ -461,6 +461,8 @@ struct RootView: View {
461 } 461 }
462 .task { 462 .task {
463 TimerModel.shared.onDone = { message = $0 } 463 TimerModel.shared.onDone = { message = $0 }
464 session.hooks = UserHookHost(trust: TrustStore(), ask: askHookTrust, report: { message = $0 },
465 workspace: UserCommandWorkspace(workspace: workspace, clock: model.clock))
464 if let lost = UnsavedHeldFiles.atLaunch { message = lost } 466 if let lost = UnsavedHeldFiles.atLaunch { message = lost }
465 takeShared() 467 takeShared()
466 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac. 468 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
@@ -671,6 +673,22 @@ struct RootView: View {
671 } 673 }
672 } 674 }
673} 675}
676
677/// Asks whether a hook from a file not yet trusted here may run, as an alert over whatever is on
678/// screen: hooks run from the editor, the agenda, the board and the capture sheet.
679@MainActor
680private func askHookTrust(_ question: UserCommandTrust.Question, reply: @escaping (UserCommandTrust.Answer?) -> Void) {
681 let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows)
682 guard var top = windows.first(where: \.isKeyWindow)?.rootViewController else { return reply(nil) }
683 while let presented = top.presentedViewController, !presented.isBeingDismissed { top = presented }
684 let alert = UIAlertController(title: question.title, message: question.message, preferredStyle: .alert)
685 for answer in UserCommandTrust.Answer.allCases {
686 alert.addAction(UIAlertAction(title: answer.title, style: answer == .dontRun ? .cancel : .default) { _ in reply(answer) })
687 }
688 top.present(alert, animated: true)
689 // Nothing on screen could show it.
690 if alert.presentingViewController == nil { reply(nil) }
691}
674#else 692#else
675/// The iOS app has nothing to run elsewhere. 693/// The iOS app has nothing to run elsewhere.
676@main 694@main
Tests/OrgAppTests/UserHookTests.swift added +194 · view
@@ -0,0 +1,194 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// `[[hook]]`s run through the real command host after TODO changes and before captures.
8@MainActor
9@Suite(.serialized)
10struct UserHookTests {
11 static let manifest = """
12 api = 1
13
14 [[hook]]
15 event = "after-todo-state-change"
16 file = "todo.js"
17 function = "logState"
18
19 [[hook]]
20 event = "capture-before-finalize"
21 file = "capture.js"
22 function = "check"
23 """
24 static let todo = """
25 export async function logState(org, { entry, from, to }) {
26 if (entry.title === "Broken") throw new Error("broken");
27 if (entry.title === "Again") {
28 await org.run("org.todo.cycle");
29 await org.message(`again ${from ?? "none"} -> ${to}`);
30 return;
31 }
32 if (entry.title === "Typed") await org.message("typing");
33 const text = await org.text();
34 const line = text.indexOf("\\n", entry.start) + 1;
35 await org.message(`${entry.title}: ${from ?? "none"} -> ${to ?? "none"}`);
36 return { edits: [{ from: line, text: `- State ${to ?? "none"} from ${from ?? "none"}\\n` }] };
37 }
38 """
39 static let capture = """
40 export async function check(org, { text, template }) {
41 if (text.includes("cancel")) return org.fail(`Not filed with ${template}`);
42 if (template === "s") return { selection: 0 };
43 const heading = await org.heading(0);
44 return { edits: [{ from: heading.titleStart, to: heading.titleEnd, text: heading.title.toUpperCase() }], message: "checked" };
45 }
46 """
47 static let file = "* Plan\nbody\n* Broken\n* Again\n* Typed\n"
48
49 let config: Folder
50 let notes: Folder
51 let path: String
52 let session: DocumentSession
53 let buffer: StateBuffer
54 let trust: TrustStore
55 var reported: [String] { messages.list }
56 let messages = Messages()
57 final class Messages { var list: [String] = [] }
58
59 init() throws {
60 config = try Folder()
61 notes = try Folder()
62 try config.write("commands.toml", Self.manifest)
63 try config.write("commands/todo.js", Self.todo)
64 try config.write("commands/capture.js", Self.capture)
65 path = try notes.write("a.org", Self.file).path
66 session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
67 session.saveMode = .explicit
68 session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
69 session.userCommands = UserCommands()
70 #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
71 session.open(path)
72 buffer = StateBuffer(try #require(session.document))
73 session.attach(buffer)
74 trust = TrustStore(file: notes.url.appendingPathComponent("trusted.json"))
75 let messages = messages
76 session.hooks = UserHookHost(trust: trust, ask: { _, reply in reply(.runOnce) }, report: { messages.list.append($0) })
77 }
78
79 /// Changes the TODO keyword of the heading titled `title`, as the agenda does, and waits for
80 /// the hooks.
81 func cycle(_ title: String, in path: String? = nil) async throws {
82 let path = path ?? self.path
83 let text = try #require(session.document(of: path)?.text ?? (try? String(contentsOfFile: path, encoding: .utf8)))
84 let found = (text as NSString).range(of: " \(title)\n")
85 try #require(found.location != NSNotFound)
86 let offset = (text as NSString).lineRange(for: found).location
87 guard case .commit = session.perform(TodoCycle(), path: path, at: offset, expect: nil) else {
88 Issue.record("cycling \(title) didn't commit")
89 return
90 }
91 await session.hooksFinished()
92 }
93
94 @Test func aStateChangeHookEditsAsItsOwnUndoStep() async throws {
95 try await cycle("Plan")
96 #expect(buffer.document.text == "* TODO Plan\n- State TODO from none\nbody\n* Broken\n* Again\n* Typed\n")
97 #expect(reported == ["Plan: none -> TODO"])
98 #expect(buffer.update { $0.undo() } != nil)
99 #expect(buffer.document.text == "* TODO Plan\nbody\n* Broken\n* Again\n* Typed\n")
100 #expect(buffer.update { $0.undo() } != nil)
101 #expect(buffer.document.text == Self.file)
102 }
103
104 /// The editor's route: the command's effect, handed to the session.
105 @Test func runsForTheEditorsCommands() async throws {
106 buffer.selection = [2..<2]
107 guard case .commit(let result) = buffer.perform(SetTodo(keyword: "DONE"), now: Date(), answers: [:]) else {
108 Issue.record("SetTodo didn't commit")
109 return
110 }
111 session.afterTodoStateChange(result.effects, in: path)
112 await session.hooksFinished()
113 #expect(buffer.document.text.hasPrefix("* DONE Plan\n- State DONE from none\n"))
114 }
115
116 /// A hook's own TODO changes, through `org.run`, run no hooks.
117 @Test func aHooksOwnChangesRunNoHooks() async throws {
118 try await cycle("Again")
119 #expect(reported == ["again none -> TODO"])
120 #expect(buffer.document.text.contains("* DONE Again\n"))
121 }
122
123 @Test func aFailingHookLeavesTheChangeAndReports() async throws {
124 try await cycle("Broken")
125 #expect(reported == ["logState in commands/todo.js: broken"])
126 #expect(buffer.document.text == "* Plan\nbody\n* TODO Broken\n* Again\n* Typed\n")
127 }
128
129 /// Typing while a hook runs refuses its edits.
130 @Test func aChangedBufferRefusesTheHooksEdits() async throws {
131 let messages = messages
132 session.hooks?.report = { [buffer] message in
133 messages.list.append(message)
134 if message == "typing" {
135 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:])
136 }
137 }
138 try await cycle("Typed")
139 #expect(reported == ["typing", "Typed: none -> TODO", "a.org changed while logState in commands/todo.js ran; its changes weren't made."])
140 #expect(buffer.document.text == "* Plan\nbody\n* Broken\n* Again\n* TODO Typed\ntyped\n")
141 }
142
143 /// A file that isn't open is changed on disk.
144 @Test func runsForAFileThatIsntOpen() async throws {
145 let other = try notes.write("b.org", "* Call\n").path
146 try await cycle("Call", in: other)
147 #expect(try String(contentsOfFile: other, encoding: .utf8) == "* TODO Call\n- State TODO from none\n")
148 }
149
150 @Test func untrustedHooksDontRunSilently() async throws {
151 // Where orgstar can't ask, they are skipped with a message.
152 session.hooks?.ask = nil
153 try await cycle("Plan")
154 #expect(reported == ["logState in commands/todo.js: commands/todo.js isn't trusted on this device yet, and orgstar can't ask here."])
155 #expect(buffer.document.text == "* TODO Plan\nbody\n* Broken\n* Again\n* Typed\n")
156 // Don't Run runs nothing; Always runs it and doesn't ask again.
157 var asked: [UserCommandTrust.Question] = []
158 session.hooks?.ask = { question, reply in
159 asked.append(question)
160 reply(.dontRun)
161 }
162 try await cycle("Plan")
163 #expect(reported.last == "logState in commands/todo.js: Not run")
164 #expect(asked == [UserCommandTrust.Question(file: "commands/todo.js", hook: .afterTodoStateChange)])
165 session.hooks?.ask = { question, reply in
166 asked.append(question)
167 reply(.always)
168 }
169 try await cycle("Plan")
170 try await cycle("Plan")
171 #expect(asked.count == 2)
172 #expect(buffer.document.text.hasPrefix("* TODO Plan\n- State TODO from none\n- State none from DONE\nbody\n"))
173 }
174
175 @Test func aCaptureHookRewritesTheTextOrCancels() async throws {
176 #expect(await session.runCaptureHooks("* buy milk :shop:\n", template: "t", interactive: true) == .success("* BUY MILK :shop:\n"))
177 #expect(reported == ["checked"])
178 #expect(await session.runCaptureHooks("* cancel this\n", template: "t", interactive: true)
179 == .failure(CaptureError(message: "Not filed with t")))
180 #expect(await session.runCaptureHooks("* x\n", template: "s", interactive: true)
181 == .failure(CaptureError(message: "check in commands/capture.js: a hook returns only edits and message")))
182 // Without a way to ask, an untrusted hook is skipped and the capture goes on unchanged.
183 session.hooks?.ask = { _, _ in Issue.record("asked without a way to ask") }
184 #expect(await session.runCaptureHooks("* cancel this\n", template: "t", interactive: false) == .success("* cancel this\n"))
185 #expect(reported.last == "check in commands/capture.js: commands/capture.js isn't trusted on this device yet, and orgstar can't ask here.")
186 }
187
188 @Test func noHostRunsNoHooks() async throws {
189 session.hooks = nil
190 try await cycle("Plan")
191 #expect(buffer.document.text == "* TODO Plan\nbody\n* Broken\n* Again\n* Typed\n")
192 #expect(await session.runCaptureHooks("* cancel\n", template: "t", interactive: true) == .success("* cancel\n"))
193 }
194}
Tests/OrgAppTests/XCallbackTests.swift +25 · view
@@ -142,6 +142,31 @@ struct XCallbackRunnerTests {
142 #expect(todo.contains(" :shop:\nfor the weekend\n* Project\n")) 142 #expect(todo.contains(" :shop:\nfor the weekend\n* Project\n"))
143 } 143 }
144 144
145 /// `capture-before-finalize` hooks run on captures without the sheet; one from a file not
146 /// trusted here is skipped, since nothing can ask.
147 @Test func captureHooksRunWithoutTheSheet() async throws {
148 let config = try Folder()
149 try config.write("commands.toml", "api = 1\n[[hook]]\nevent = \"capture-before-finalize\"\nfile = \"check.js\"\nfunction = \"check\"\n")
150 try config.write("commands/check.js", """
151 export function check(org, { text, template }) {
152 if (text.includes("cancel")) throw new Error(`not with ${template}`);
153 return { edits: [{ from: 0, to: text.length, text: text.replace("TODO", "NEXT") }] };
154 }
155 """)
156 session.userCommands = UserCommands()
157 #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
158 var reported: [String] = []
159 let trust = TrustStore(file: config.url.appendingPathComponent("trusted.json"))
160 session.hooks = UserHookHost(trust: trust, ask: { _, _ in Issue.record("asked") }, report: { reported.append($0) })
161 #expect(await runner.run(allowed("capture?template=t&text=Skipped")) == .reply(.success(["template": "t", "file": "todo.org"])))
162 #expect(reported == ["check in commands/check.js: commands/check.js isn't trusted on this device yet, and orgstar can't ask here."])
163 let modules = config.url.appendingPathComponent("commands")
164 trust.trust(path: modules.appendingPathComponent("check.js").path, content: try #require(UserCommandFile.trustedText("check.js", modules: modules)))
165 #expect(await runner.run(allowed("capture?template=t&text=Read")) == .reply(.success(["template": "t", "file": "todo.org"])))
166 #expect(await runner.run(allowed("capture?template=t&text=cancel")) == .reply(.failure(.captureFailed, "check in commands/check.js: not with t")))
167 #expect(todo.hasPrefix("* Inbox\n** TODO Skipped\n** NEXT Read\n* Project\n"))
168 }
169
145 @Test func capturesALinkAsOrgProtocolDoes() async { 170 @Test func capturesALinkAsOrgProtocolDoes() async {
146 let step = await runner.run(allowed("capture?template=t&text=Read&url=https%3A%2F%2Fexample.com&title=Example")) 171 let step = await runner.run(allowed("capture?template=t&text=Read&url=https%3A%2F%2Fexample.com&title=Example"))
147 #expect(step == .reply(.success(["template": "t", "file": "todo.org"]))) 172 #expect(step == .reply(.success(["template": "t", "file": "todo.org"])))
Tests/OrgCoreTests/UserCommandTests.swift +77 · view
@@ -119,6 +119,83 @@ struct UserCommandManifestTests {
119 #expect(problems == ["command bad: workspace must be true or false"]) 119 #expect(problems == ["command bad: workspace must be true or false"])
120 } 120 }
121 121
122 @Test func readsHooksAndTheirProblems() throws {
123 var problems: [String] = []
124 let manifest = try UserCommands.manifest("""
125 api = 1
126
127 [[hook]]
128 event = "after-todo-state-change"
129 file = "review.js"
130 function = "logState"
131
132 [[hook]]
133 event = "capture-before-finalize"
134 file = "lib/dates.mjs"
135 function = "check"
136 timeout = 5
137 workspace = true
138
139 [[hook]]
140 event = "post-command"
141 file = "review.js"
142 function = "f"
143
144 [[hook]]
145 file = "review.js"
146 function = "f"
147
148 [[hook]]
149 event = "after-todo-state-change"
150 file = "gone.js"
151 function = "f"
152 name = "x"
153
154 [[hook]]
155 event = "capture-before-finalize"
156 file = "review.js"
157 function = "f"
158 timeout = 0
159 """, problems: &problems) { ["review.js", "lib/dates.mjs"].contains($0) }
160 #expect(manifest.commands == [])
161 #expect(manifest.hooks == [
162 UserHook(event: .afterTodoStateChange, file: "review.js", function: "logState"),
163 UserHook(event: .captureBeforeFinalize, file: "lib/dates.mjs", function: "check", timeout: 5, workspace: true),
164 ])
165 #expect(problems == [
166 "hook at line 15: unknown event post-command; the events are after-todo-state-change and capture-before-finalize",
167 "hook at line 20: missing event",
168 "hook at line 24: unknown key name",
169 "hook at line 24: no file commands/gone.js",
170 "hook at line 30: timeout must be 1 to 30 seconds",
171 ])
172 #expect(manifest.hooks[0].title == "logState in commands/review.js")
173 let store = UserCommands()
174 store.replace([], hooks: manifest.hooks, folder: nil)
175 #expect(store.hooks(.captureBeforeFinalize) == [manifest.hooks[1]])
176 // Hooks need the api line as commands do.
177 problems = []
178 _ = try UserCommands.manifest("[[hook]]\nevent = \"after-todo-state-change\"\nfile = \"review.js\"\nfunction = \"f\"\n", problems: &problems) { _ in true }
179 #expect(problems == ["missing api = 1"])
180 }
181
182 /// Every route `org-todo` takes reports the change, with the heading where it starts after
183 /// the edits; a repeating entry reports the done keyword it was given.
184 @Test func todoChangesAreEffects() {
185 func changes(_ text: String, at caret: Int, _ command: any OrgCommand) -> [TodoStateChange] {
186 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
187 guard case .commit(let result) = command.run(in: context) else { return [] }
188 return result.effects.compactMap { if case .todoStateChanged(let change) = $0 { change } else { nil } }
189 }
190 let text = "* Parent [0/1]\n** Child\n"
191 #expect(changes(text, at: 17, TodoCycle()) == [TodoStateChange(heading: 15, from: nil, to: "TODO")])
192 #expect(changes("* TODO Task\n", at: 3, SetTodo(keyword: "DONE")) == [TodoStateChange(heading: 0, from: "TODO", to: "DONE")])
193 #expect(changes("* TODO Task\n", at: 3, SetTodo(keyword: "TODO")) == [])
194 let repeating = "* TODO Water\nSCHEDULED: <2026-11-27 Fri +1w>\n"
195 #expect(changes(repeating, at: 3, TodoShift(right: true)) == [TodoStateChange(heading: 0, from: "TODO", to: "DONE")])
196 #expect(changes("* Plan\n", at: 0, PromoteHeading()) == [])
197 }
198
122 @Test func needsAKnownAPI() throws { 199 @Test func needsAKnownAPI() throws {
123 let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n" 200 let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n"
124 #expect(try parse(command) == ([], ["missing api = 1"])) 201 #expect(try parse(command) == ([], ["missing api = 1"]))
Tests/OrgstarCLITests/ToolTests.swift +12 · view
@@ -167,6 +167,18 @@ struct CaptureTests {
167 #expect(unknown.status == 3) 167 #expect(unknown.status == 3)
168 #expect(unknown.err.contains("j (Journal)")) 168 #expect(unknown.err.contains("j (Journal)"))
169 } 169 }
170
171 /// Capture hooks run only in the app: the tool files without them and says so.
172 @Test func filesWithoutCaptureHooks() throws {
173 let sandbox = try Sandbox()
174 try sandbox.write(Self.templates, "capture.toml", in: sandbox.config)
175 try sandbox.write("api = 1\n[[hook]]\nevent = \"capture-before-finalize\"\nfile = \"check.js\"\nfunction = \"check\"\n", "commands.toml", in: sandbox.config)
176 try sandbox.write("* Inbox\n* Meetings\n", "inbox.org")
177 let (status, _, err) = sandbox.run("capture", "t", "Buy milk")
178 #expect(status == 0)
179 #expect(err == "orgstar: capture-before-finalize hooks in commands.toml run only in the app; captured without them\n")
180 #expect(try sandbox.read("inbox.org") == "* Inbox\n** TODO Buy milk\n* Meetings\n")
181 }
170} 182}
171 183
172@MainActor 184@MainActor
docs/manual/guide/17-command-line.org +2 · view
@@ -67,6 +67,8 @@ Questions are answered with =--set Prompt=value=, by the prompt's text: =%^{Who}
67 67
68Targets work as in the app: a file is made when missing, =id= finds the heading in your folders, =clock= files under the running clock. =clock-in= with =clock-keep= starts the clock on the new entry; without =clock-keep= there's nothing to time, since the capture finishes at once. Templates with =denote = true= are refused; use them in the app. 68Targets work as in the app: a file is made when missing, =id= finds the heading in your folders, =clock= files under the running clock. =clock-in= with =clock-keep= starts the clock on the new entry; without =clock-keep= there's nothing to time, since the capture finishes at once. Templates with =denote = true= are refused; use them in the app.
69 69
70=capture-before-finalize= hooks (see [[file:18-user-commands.org::*Hooks][Hooks]]) run only in the app. When =commands.toml= has one, the tool files the entry without it and says so on standard error: "capture-before-finalize hooks in commands.toml run only in the app; captured without them". No command of the tool runs =after-todo-state-change= hooks, including =clock in= with =org-clock-in-switch-to-state=.
71
70** clock 72** clock
71 73
72#+BEGIN_SRC sh 74#+BEGIN_SRC sh
docs/manual/guide/18-user-commands.org +97 −2 · view
@@ -1,5 +1,5 @@
1#+TITLE: User commands 1#+TITLE: User commands
2#+DESCRIPTION: Your own editing commands in JavaScript: commands.toml, the commands folder, the org API, trust, limits, and porting commands from Emacs Lisp. 2#+DESCRIPTION: Your own editing commands in JavaScript: commands.toml, the commands folder, the org API, hooks, trust, limits, and porting commands from Emacs Lisp.
3#+LEDE: Write your own editing commands in JavaScript. They run on the Mac and on iPhone and iPad, from the palette, keys and the key bar. 3#+LEDE: Write your own editing commands in JavaScript. They run on the Mac and on iPhone and iPad, from the palette, keys and the key bar.
4 4
5* Overview 5* Overview
@@ -58,6 +58,7 @@ Problems are reported like those of the other configuration files (see [[file:13
58- =commands.toml: command slow: timeout must be 1 to 30 seconds= 58- =commands.toml: command slow: timeout must be 1 to 30 seconds=
59- =commands.toml: command review: unknown context headline= 59- =commands.toml: command review: unknown context headline=
60- =commands.toml: command find: workspace must be true or false= 60- =commands.toml: command find: workspace must be true or false=
61- =commands.toml: hook at line 12: unknown event post-command; the events are after-todo-state-change and capture-before-finalize= (see [[*Hooks][Hooks]])
61- =commands.toml: api 2 needs a newer orgstar= (no command is registered) 62- =commands.toml: api 2 needs a newer orgstar= (no command is registered)
62- =commands.toml: missing api = 1= (no command is registered) 63- =commands.toml: missing api = 1= (no command is registered)
63- =commands.toml: commands/review.js isn't downloaded from iCloud yet= (iPhone and iPad; the download starts) 64- =commands.toml: commands/review.js isn't downloaded from iCloud yet= (iPhone and iPad; the download starts)
@@ -267,6 +268,94 @@ Any change to the file or to a module it imports asks again, including a change
267 268
268Edit ▸ Cancel Running Task (=⌘.=, =app.babel.cancel=) stops a running command; the Commands list on iPhone and iPad has the same command. Nothing it returned is applied. Running another user command cancels the one before it. 269Edit ▸ Cancel Running Task (=⌘.=, =app.babel.cancel=) stops a running command; the Commands list on iPhone and iPad has the same command. Nothing it returned is applied. Running another user command cancels the one before it.
269 270
271* Hooks
272
273A hook is a function that runs when something happens rather than from a key: after you change an entry's TODO state, or before a capture is filed. Declare it in =commands.toml= as =[[hook]]=, beside the commands:
274
275#+BEGIN_SRC toml
276api = 1
277
278[[hook]]
279event = "after-todo-state-change" # org-after-todo-state-change-hook
280file = "todo.js"
281function = "logState"
282timeout = 2 # optional, as for commands
283workspace = false # optional, as for commands
284
285[[hook]]
286event = "capture-before-finalize" # org-capture-before-finalize-hook
287file = "capture.js"
288function = "check"
289#+END_SRC
290
291| Key | Required | What it sets |
292|-------------+----------+-------------------------------------------------------------------------------------------------|
293| =event= | Yes | =after-todo-state-change= or =capture-before-finalize=. |
294| =file= | Yes | As for a command. |
295| =function= | Yes | As for a command. |
296| =timeout= | No | As for a command: 1 to 30 seconds, 2 when not given. |
297| =workspace= | No | As for a command: =true= gives the hook the calls of [[*Reading your folders and capturing][Reading your folders and capturing]]. |
298
299An event may have several hooks; they run one after another, in the order of the file, as the functions of an Emacs hook do. Problems are reported by line, as =commands.toml: hook at line 12: no file commands/todo.js=, and the hook with the problem isn't used.
300
301The function is called with =org= and a second argument that describes the event. It returns =edits= and =message= as a command does, or nothing; =selection= and =copy= fail the hook with "/function/ in /file/: a hook returns only edits and message". =org.prompt= throws in a hook, and so does =org.run= with a command that asks: a hook can run where nobody can answer.
302
303There are no hooks that run on every key or every change (=post-command-hook=, =after-change-functions=, =post-self-insert-hook=): a hook runs in the same engine as a command, which takes too long for that.
304
305** after-todo-state-change
306
307Runs after a change of an entry's TODO keyword has been made: by the TODO commands in the editor (=C-c C-t=, =S-right=, =S-left=, the TODO keyword picker), =C-c C-c= on a heading, setting the =TODO= property, and clocking in with =org-clock-in-switch-to-state=; and in the agenda, the board, column view, the entry sheet on iPhone and iPad and the Apple Watch's Done. The second argument is:
308
309| Field | Value |
310|---------+----------------------------------------------------------------------------------------------------------|
311| =entry= | The entry after the change, as =org.heading()= describes it. |
312| =from= | The keyword before, or =null=. |
313| =to= | The keyword set, or =null=. For a repeating entry marked done it is the done keyword, though the repeat has put the entry back to =TODO=, as =org-state= is in Org's hook. |
314
315The hook runs on the file as the change left it: =org.text()=, =org.heading()= and =org.outline()= read that text, and the caret is at the start of the entry's heading. Its edits apply as a step of undo of their own, after the change's, so undoing once takes back the hook's edits and leaves the change. In a file that isn't open (a change from the agenda), the file is written at once. If the file changes before the hook's edits apply, as when you type while it runs, they aren't made: "/file/ changed while /function/ in /file/ ran; its changes weren't made."
316
317The change itself stays whatever the hook does. A hook that fails, throws or runs out of time shows why, and the next hook runs.
318
319Changes a hook or a user command makes don't run hooks: a hook that runs =org.run("org.todo.cycle")= doesn't run itself again. Nor do the command-line tool, Replace in Files and renaming a keyword in every file. Encrypted files and buffers with decrypted entries run no hooks, as they run no commands.
320
321#+BEGIN_SRC js
322// commands/todo.js: a line under the heading when an entry is done.
323export async function logState(org, { entry, from, to }) {
324 if (to !== "DONE") return
325 const text = await org.text()
326 const lineEnd = text.indexOf("\n", entry.start) + 1
327 return {
328 edits: [{ from: lineEnd, text: `- Done; was ${from ?? "no keyword"}\n` }],
329 message: `Done: ${entry.title}`,
330 }
331}
332#+END_SRC
333
334** capture-before-finalize
335
336Runs when you file a capture, before the entry is placed: from the capture window on the Mac, the capture sheet on iPhone and iPad, an x-callback-url =capture= without the sheet, and Shortcuts' Capture to Orgstar. The second argument is ={text, template}=: the entry as the template filled it and you edited it, and the template's key.
337
338The hook works on the capture as Emacs's does in the capture buffer: =org.text()= is the capture's text, =org.heading()= and =org.outline()= read its headings, =org.file()= gives =null=, and its =edits= change it. The entry is filed with the changed text. =org.fail(text)=, an error or the timeout cancels the capture: nothing is filed and the reason is shown, in the window or sheet, which stays open, or in the reply to the x-callback-url or the Shortcuts action.
339
340#+BEGIN_SRC js
341// commands/capture.js: tag entries about bills, and refuse an empty title.
342export async function check(org, { text, template }) {
343 const heading = await org.heading(0)
344 if (heading && !heading.title.trim()) return org.fail("The entry needs a title")
345 if (template !== "t" || !/\bbill\b/i.test(text)) return
346 const lineEnd = text.indexOf("\n")
347 return { edits: [{ from: lineEnd < 0 ? text.length : lineEnd, text: " :money:" }] }
348}
349#+END_SRC
350
351Capture hooks don't run for =org.capture= in a user command or a hook, for org-roam and dailies captures made without the capture window, or for =orgstar capture= (see [[file:17-command-line.org::*capture][capture]]), which files without them and says so.
352
353** Trust for hooks
354
355A hook's file is trusted as a command's is (see [[*Trust][Trust]]), and the same trust covers both: Always for one of the file's commands also lets its hooks run, and the other way round. The first time a hook from a file not trusted on this device would run, orgstar asks "Run hooks from commands/todo.js?", with a line saying when the hook runs. The question is an alert on the Mac, since hooks run from the agenda and the capture window too, and on iPhone and iPad.
356
357Where orgstar can't ask (an x-callback-url capture without the sheet, Shortcuts), a hook from a file not trusted here is skipped and the capture is filed without it, with "/function/ in /file/: commands/capture.js isn't trusted on this device yet, and orgstar can't ask here." Don't Run skips the hook this time, with "Not run".
358
270* Limits 359* Limits
271 360
272- *Time.* A command that runs longer than its =timeout= (2 seconds by default, at most 30) is stopped with "/title/ didn't finish within /n/ s and was stopped." Time waiting for a prompt doesn't count. 361- *Time.* A command that runs longer than its =timeout= (2 seconds by default, at most 30) is stopped with "/title/ didn't finish within /n/ s and was stopped." Time waiting for a prompt doesn't count.
@@ -287,7 +376,7 @@ What Emacs Lisp has that user commands don't:
287- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead. 376- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
288- The Org API: =org-element-*=, =org-entry-put=. Read headings with =org.heading()= and =org.outline()=, and write the text yourself or run Org's commands with =org.run=. Over several files, a command with =workspace = true= reads with =org.search= and =org.outlineOf= and writes only with =org.capture=. 377- The Org API: =org-element-*=, =org-entry-put=. Read headings with =org.heading()= and =org.outline()=, and write the text yourself or run Org's commands with =org.run=. Over several files, a command with =workspace = true= reads with =org.search= and =org.outlineOf= and writes only with =org.capture=.
289- Other buffers, =find-file= and =with-temp-buffer=; changes to other files except by capture. 378- Other buffers, =find-file= and =with-temp-buffer=; changes to other files except by capture.
290- Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables. 379- Hooks other than =org-after-todo-state-change-hook= and =org-capture-before-finalize-hook= (see [[*Hooks][Hooks]]): no =post-command-hook=, =after-change-functions= or other per-keystroke hooks. Advice, minor modes and buffer-local variables.
291- =interactive= codes other than the prompts above; =C-u= prefix arguments. 380- =interactive= codes other than the prompts above; =C-u= prefix arguments.
292- Timers, processes and shell commands. 381- Timers, processes and shell commands.
293 382
@@ -327,3 +416,9 @@ What Emacs Lisp has that user commands don't:
327| =(org-agenda-get-day-entries file date)=, =(org-agenda-list)= | =await org.agenda({from, to})= (=workspace = true=) | 416| =(org-agenda-get-day-entries file date)=, =(org-agenda-list)= | =await org.agenda({from, to})= (=workspace = true=) |
328| =(org-capture-string "Milk" "t")=, =(org-capture nil "t")= | =await org.capture("t", "Milk", {…})= (=workspace = true=) | 417| =(org-capture-string "Milk" "t")=, =(org-capture nil "t")= | =await org.capture("t", "Milk", {…})= (=workspace = true=) |
329| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= | 418| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= |
419| =(add-hook 'org-after-todo-state-change-hook #'my/fn)= | =[[hook]]= with =event = "after-todo-state-change"= |
420| =org-state=, =org-last-state= in that hook | =to= and =from= of the hook's second argument |
421| =(add-hook 'org-capture-before-finalize-hook #'my/fn)= | =[[hook]]= with =event = "capture-before-finalize"= |
422| =(buffer-string)= in the capture buffer | =await org.text()=, or =text= of the hook's second argument |
423| =(plist-get org-capture-plist :key)= | =template= of the hook's second argument |
424| =(user-error …)= in a capture hook | =return org.fail(…)=: the capture is canceled |
l10n/Localizable.xcstrings +210 · view
@@ -500,6 +500,41 @@
500 } 500 }
501 } 501 }
502 }, 502 },
503 "%@ changed before %@ ran, so it didn't run.": {
504 "comment": "An after-todo-state-change hook not run because its file changed",
505 "localizations": {
506 "de": {
507 "stringUnit": {
508 "state": "translated",
509 "value": "%1$@ hat sich geändert, bevor %2$@ lief, daher wurde der Hook nicht ausgeführt."
510 }
511 },
512 "es": {
513 "stringUnit": {
514 "state": "translated",
515 "value": "%1$@ cambió antes de que se ejecutara %2$@, así que no se ejecutó."
516 }
517 },
518 "fr": {
519 "stringUnit": {
520 "state": "translated",
521 "value": "%1$@ a changé avant l’exécution de %2$@, qui n’a donc pas été exécuté."
522 }
523 },
524 "ja": {
525 "stringUnit": {
526 "state": "translated",
527 "value": "%2$@ の実行前に %1$@ が変更されたため、実行しませんでした。"
528 }
529 },
530 "pt-BR": {
531 "stringUnit": {
532 "state": "translated",
533 "value": "%1$@ mudou antes de %2$@ ser executado, então ele não foi executado."
534 }
535 }
536 }
537 },
503 "%@ changed on disk while saving, and the changes conflict with yours; both are in the editor between conflict markers.": { 538 "%@ changed on disk while saving, and the changes conflict with yours; both are in the editor between conflict markers.": {
504 "localizations": { 539 "localizations": {
505 "de": { 540 "de": {
@@ -534,6 +569,41 @@
534 } 569 }
535 } 570 }
536 }, 571 },
572 "%@ changed while %@ ran; its changes weren't made.": {
573 "comment": "An after-todo-state-change hook's edits refused because its file changed",
574 "localizations": {
575 "de": {
576 "stringUnit": {
577 "state": "translated",
578 "value": "%1$@ hat sich geändert, während %2$@ lief; seine Änderungen wurden nicht vorgenommen."
579 }
580 },
581 "es": {
582 "stringUnit": {
583 "state": "translated",
584 "value": "%1$@ cambió mientras se ejecutaba %2$@; sus cambios no se aplicaron."
585 }
586 },
587 "fr": {
588 "stringUnit": {
589 "state": "translated",
590 "value": "%1$@ a changé pendant l’exécution de %2$@ ; ses modifications n’ont pas été appliquées."
591 }
592 },
593 "ja": {
594 "stringUnit": {
595 "state": "translated",
596 "value": "%2$@ の実行中に %1$@ が変更されたため、その変更は反映されませんでした。"
597 }
598 },
599 "pt-BR": {
600 "stringUnit": {
601 "state": "translated",
602 "value": "%1$@ mudou enquanto %2$@ era executado; as alterações dele não foram feitas."
603 }
604 }
605 }
606 },
537 "%@ didn't finish within %lld s and was stopped.": { 607 "%@ didn't finish within %lld s and was stopped.": {
538 "comment": "A user command passed its time limit", 608 "comment": "A user command passed its time limit",
539 "localizations": { 609 "localizations": {
@@ -1159,6 +1229,41 @@
1159 } 1229 }
1160 } 1230 }
1161 }, 1231 },
1232 "%@ isn't trusted on this device yet, and orgstar can't ask here.": {
1233 "comment": "A hook from a file not yet trusted, skipped where orgstar can't ask, as for a capture from Shortcuts",
1234 "localizations": {
1235 "de": {
1236 "stringUnit": {
1237 "state": "translated",
1238 "value": "%@ ist auf diesem Gerät noch nicht vertrauenswürdig, und orgstar kann hier nicht nachfragen."
1239 }
1240 },
1241 "es": {
1242 "stringUnit": {
1243 "state": "translated",
1244 "value": "%@ aún no es de confianza en este dispositivo y orgstar no puede preguntar aquí."
1245 }
1246 },
1247 "fr": {
1248 "stringUnit": {
1249 "state": "translated",
1250 "value": "%@ n’est pas encore approuvé sur cet appareil, et orgstar ne peut pas demander ici."
1251 }
1252 },
1253 "ja": {
1254 "stringUnit": {
1255 "state": "translated",
1256 "value": "%@ はこのデバイスでまだ信頼されておらず、ここでは確認できません。"
1257 }
1258 },
1259 "pt-BR": {
1260 "stringUnit": {
1261 "state": "translated",
1262 "value": "%@ ainda não é confiável neste dispositivo, e o orgstar não pode perguntar aqui."
1263 }
1264 }
1265 }
1266 },
1162 "%@ late": { 1267 "%@ late": {
1163 "localizations": { 1268 "localizations": {
1164 "de": { 1269 "de": {
@@ -42038,6 +42143,41 @@
42038 } 42143 }
42039 } 42144 }
42040 }, 42145 },
42146 "Run hooks from %@?": {
42147 "comment": "Asked before a user hook from a file not yet trusted on this device runs",
42148 "localizations": {
42149 "de": {
42150 "stringUnit": {
42151 "state": "translated",
42152 "value": "Hooks aus %@ ausführen?"
42153 }
42154 },
42155 "es": {
42156 "stringUnit": {
42157 "state": "translated",
42158 "value": "¿Ejecutar los hooks de %@?"
42159 }
42160 },
42161 "fr": {
42162 "stringUnit": {
42163 "state": "translated",
42164 "value": "Exécuter les hooks de %@ ?"
42165 }
42166 },
42167 "ja": {
42168 "stringUnit": {
42169 "state": "translated",
42170 "value": "%@ のフックを実行しますか?"
42171 }
42172 },
42173 "pt-BR": {
42174 "stringUnit": {
42175 "state": "translated",
42176 "value": "Executar hooks de %@?"
42177 }
42178 }
42179 }
42180 },
42041 "Run this %@ block? (%@)": { 42181 "Run this %@ block? (%@)": {
42042 "comment": "Echo area prompt: the block's language, then the answers it accepts (yes, no, always), which stay in English", 42182 "comment": "Echo area prompt: the block's language, then the answers it accepts (yes, no, always), which stay in English",
42043 "localizations": { 42183 "localizations": {
@@ -51392,6 +51532,76 @@
51392 } 51532 }
51393 } 51533 }
51394 }, 51534 },
51535 "This hook runs after you change an entry's TODO state.": {
51536 "comment": "When an after-todo-state-change hook runs, in the question before it runs",
51537 "localizations": {
51538 "de": {
51539 "stringUnit": {
51540 "state": "translated",
51541 "value": "Dieser Hook läuft, nachdem du den TODO-Status eines Eintrags änderst."
51542 }
51543 },
51544 "es": {
51545 "stringUnit": {
51546 "state": "translated",
51547 "value": "Este hook se ejecuta después de cambiar el estado TODO de una entrada."
51548 }
51549 },
51550 "fr": {
51551 "stringUnit": {
51552 "state": "translated",
51553 "value": "Ce hook s’exécute après la modification de l’état TODO d’une entrée."
51554 }
51555 },
51556 "ja": {
51557 "stringUnit": {
51558 "state": "translated",
51559 "value": "このフックは、項目の TODO 状態を変更した後に実行されます。"
51560 }
51561 },
51562 "pt-BR": {
51563 "stringUnit": {
51564 "state": "translated",
51565 "value": "Este hook é executado depois que você muda o estado TODO de uma entrada."
51566 }
51567 }
51568 }
51569 },
51570 "This hook runs before a capture is filed and can change or cancel it.": {
51571 "comment": "When a capture-before-finalize hook runs, in the question before it runs",
51572 "localizations": {
51573 "de": {
51574 "stringUnit": {
51575 "state": "translated",
51576 "value": "Dieser Hook läuft, bevor eine Notiz abgelegt wird, und kann sie ändern oder abbrechen."
51577 }
51578 },
51579 "es": {
51580 "stringUnit": {
51581 "state": "translated",
51582 "value": "Este hook se ejecuta antes de archivar una captura y puede cambiarla o cancelarla."
51583 }
51584 },
51585 "fr": {
51586 "stringUnit": {
51587 "state": "translated",
51588 "value": "Ce hook s’exécute avant le classement d’une capture et peut la modifier ou l’annuler."
51589 }
51590 },
51591 "ja": {
51592 "stringUnit": {
51593 "state": "translated",
51594 "value": "このフックはキャプチャを保存する前に実行され、内容を変更したり取り消したりできます。"
51595 }
51596 },
51597 "pt-BR": {
51598 "stringUnit": {
51599 "state": "translated",
51600 "value": "Este hook é executado antes de uma captura ser arquivada e pode alterá-la ou cancelá-la."
51601 }
51602 }
51603 }
51604 },
51395 "This is the only pane.": { 51605 "This is the only pane.": {
51396 "comment": "Close Pane with one pane", 51606 "comment": "Close Pane with one pane",
51397 "localizations": { 51607 "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