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 {
6363 _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
6464 clipboard: String, userName: String, answers: [String: String] = [:], properties: [String: String] = [:]
6565 ) -> 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> {
66102 let key = key.flatMap { $0.isEmpty ? nil : $0 }
67103 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
68104 return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
@@ -75,9 +111,7 @@ extension DocumentSession {
75111 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
76112 return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\""))
77113 }
78 return chosen.resolved(workspace: workspace, session: self, clock: clock).flatMap { resolved in
79 capture(filled.text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
80 }.map { (chosen, $0.path, $0.offset) }
114 return .success((chosen, filled.text))
81115 }
82116}
83117
Sources/OrgApp/CommandHost.swift +17 −11 · view
@@ -70,9 +70,11 @@ public final class CommandHost {
7070
7171 /// Calls `function` exported by `module`, a path in `commands/`, with the JSON `context` and a
7272 /// 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`
74 /// is at most `maximumTimeout`.
75 public func run(module: String, function: String, context: String, timeout: Duration = defaultTimeout, api: Int? = nil) async throws -> String {
73 /// function gets that version's `org` object instead, whose calls reach `calls`, and then
74 /// `context` unless it is `null`. `timeout` is at most `maximumTimeout`. `answer`, when
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 {
7678 guard Files.relative(module) != nil else { throw Failure.script("No module \(module) in commands/.") }
7779 let limit = min(timeout, Self.maximumTimeout)
7880 idleTask?.cancel()
@@ -87,7 +89,7 @@ public final class CommandHost {
8789 throw Failure.stopped
8890 }
8991 try Task.checkCancellation()
90 let run = Run(limit: limit)
92 let run = Run(limit: limit, answer: answer)
9193 engine.runs[id] = run
9294 defer { engine.runs[id] = nil }
9395 let reply: String
@@ -141,8 +143,8 @@ public final class CommandHost {
141143 if self.engine === engine { unload() } else { engine.close() }
142144 }
143145
144 func call(_ name: String, _ value: Any) async throws -> Any {
145 try await calls(name, value)
146 func call(_ name: String, _ value: Any, run: Run) async throws -> Any {
147 try await (run.answer ?? calls)(name, value)
146148 }
147149
148150 /// 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 {
150152 @MainActor
151153 final class Run {
152154 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)?
153157 private var remaining: Duration
154158 private var since = ContinuousClock.now
155159 private var timer: Task<Void, Never>?
@@ -157,8 +161,9 @@ public final class CommandHost {
157161 private(set) var ended = false
158162 private var continuation: CheckedContinuation<String, Error>?
159163
160 init(limit: Duration) {
164 init(limit: Duration, answer: (@MainActor (String, Any) async throws -> Any)? = nil) {
161165 self.limit = limit
166 self.answer = answer
162167 remaining = limit
163168 }
164169
@@ -286,7 +291,7 @@ public final class CommandHost {
286291 run.pause()
287292 defer { run.resume() }
288293 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)
290295 } catch let Failure.script(message) {
291296 return (nil, message)
292297 } catch {
@@ -392,8 +397,8 @@ public final class CommandHost {
392397 """
393398
394399 /// 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
396 /// result as JSON.
400 /// the function with the context and `call`, or for API version 1 with `org` and the
401 /// context unless it is null, and posts the result as JSON.
397402 static let worker = """
398403 const post = self.postMessage.bind(self);
399404 for (const name of ["fetch", "XMLHttpRequest", "WebSocket", "EventSource", "importScripts", "indexedDB", "caches", "Worker", "SharedWorker"]) {
@@ -442,7 +447,8 @@ public final class CommandHost {
442447 try {
443448 const module = await import("./commands/" + m.module);
444449 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]));
446452 post({ result: JSON.stringify(value) ?? "null" });
447453 } catch (error) {
448454 post({ error: String(error && error.message || error) });
Sources/OrgApp/DocumentSession.swift +253 −45 · view
@@ -1213,7 +1213,10 @@ public final class DocumentSession {
12131213 do {
12141214 let options = self.options
12151215 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 }
12171220 return step
12181221 } catch {
12191222 return .failed("\(error)")
@@ -1230,7 +1233,10 @@ public final class DocumentSession {
12301233 if case .commit = step, state.isDirty, case .conflict = try closedFileSaver.save(&state, to: url) {
12311234 return .failed("\(name) changed on disk; nothing was changed.")
12321235 }
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 }
12341240 return step
12351241 } catch {
12361242 return .failed("Can't change \(name): \(error.localizedDescription)")
@@ -1487,6 +1493,10 @@ public final class DocumentSession {
14871493 }
14881494 #endif
14891495 @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>?
14901500 public private(set) var isRunningUserCommand = false
14911501
14921502 /// Runs a user command on the focused buffer in the background, with `context` the editor's
@@ -1537,41 +1547,95 @@ public final class DocumentSession {
15371547 guard entry.buffer.document.revision == request.revision, context.revision == request.revision else { return "The file changed; try again." }
15381548 #if canImport(WebKit)
15391549 guard let host = userCommandHost() else { return "No \(UserCommands.fileName)." }
1540 final class State {
1541 var failure: String?
1542 var quit = false
1543 /// `org.run("app.save")` ran.
1544 var save = false
1545 var buffer: UserCommandState
1546 init(_ buffer: UserCommandState) { self.buffer = buffer }
1547 }
1548 let state = State(UserCommandState(
1549 EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection,
1550 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags),
1551 defaults: entry.buffer.document.defaults))
1550 let state = UserScript(file: command.file, function: command.function, timeout: command.timeout, workspace: command.workspace,
1551 title: command.title, buffer: UserCommandState(
1552 EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection,
1553 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags),
1554 defaults: entry.buffer.document.defaults))
1555 let json: String
1556 switch await run(state, host: host, path: path, file: file, workspace: workspace, ask: ask, report: report) {
1557 case .failure(let message): return message.text
1558 case .success(let returned): json = returned
1559 }
1560 guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") }
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> {
15521615 /// The answer to `prompt`; a canceled prompt throws.
15531616 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
15551619 ask(prompt) { answer in
15561620 guard let answer else {
1557 state.quit = true
1621 script.quit = true
15581622 return continuation.resume(throwing: CommandHost.Failure.script("Quit"))
15591623 }
15601624 continuation.resume(returning: answer)
15611625 }
15621626 }
15631627 }
1564 host.calls = { name, value in
1565 if let answer = UserCommandAPI.answer(name, value, context: state.buffer.context, file: file) { return answer }
1628 let calls: @MainActor (String, Any) async throws -> Any = { name, value in
1629 if let answer = UserCommandAPI.answer(name, value, context: script.buffer.context, file: file) { return answer }
15661630 switch name {
15671631 case "prompt":
15681632 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)
15701634 case "run":
15711635 let id = value as? String ?? ""
15721636 if UserCommandAPI.safeAppCommands.contains(id) {
1573 state.save = true
1574 return state.buffer.reply
1637 script.save = true
1638 return script.buffer.reply
15751639 }
15761640 let command: any OrgCommand
15771641 switch UserCommandAPI.builtIn(id) {
@@ -1581,8 +1645,8 @@ public final class DocumentSession {
15811645 // A built-in command's prompts go through the same prompt as the command's own.
15821646 var answers: [String: String] = [:]
15831647 while true {
1584 switch state.buffer.run(command, answers: answers) {
1585 case .commit: return state.buffer.reply
1648 switch script.buffer.run(command, answers: answers) {
1649 case .commit: return script.buffer.reply
15861650 case .failed(let message): throw CommandHost.Failure.script(message)
15871651 case .external: throw CommandHost.Failure.script(UserCommandAPI.external(id).message)
15881652 case .prompt(let prompt): answers[prompt.key] = try await reply(to: prompt)
@@ -1592,10 +1656,10 @@ public final class DocumentSession {
15921656 report(value as? String ?? "")
15931657 return NSNull()
15941658 case "fail":
1595 state.failure = value as? String ?? ""
1659 script.failure = value as? String ?? ""
15961660 return NSNull()
15971661 case _ where UserCommandWorkspace.calls.contains(name):
1598 guard command.workspace else {
1662 guard script.workspace else {
15991663 throw CommandHost.Failure.script("org.\(name) needs workspace = true on the command in \(UserCommands.fileName).")
16001664 }
16011665 guard let workspace else { throw CommandHost.Failure.script("org.\(name) isn't available here.") }
@@ -1608,39 +1672,183 @@ public final class DocumentSession {
16081672 throw CommandHost.Failure.script("org.\(name) isn't in API version \(UserCommands.apiVersion).")
16091673 }
16101674 }
1675 let title = script.title
16111676 let json: String
16121677 do {
1613 json = try await host.run(module: command.file, function: command.function, context: "null",
1614 timeout: .seconds(command.timeout), api: UserCommands.apiVersion)
1678 json = try await host.run(module: script.file, function: script.function, context: script.argument,
1679 timeout: .seconds(script.timeout), api: UserCommands.apiVersion, answer: calls)
16151680 } catch let CommandHost.Failure.timedOut(limit) {
16161681 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")))
16181683 } catch CommandHost.Failure.script(let message) {
1619 if let failure = state.failure { return failure }
1620 return state.quit ? "Quit" : "\(command.title): \(message)"
1684 if let failure = script.failure { return .failure(ScriptFailure(text: failure)) }
1685 return .failure(ScriptFailure(text: script.quit ? "Quit" : "\(title): \(message)"))
16211686 } 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")))
16231688 } 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")))
16251690 }
1626 if let failure = state.failure { return failure }
1627 guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") }
1628 switch state.buffer.result(json) {
1629 case .failure(let problem):
1630 return "\(command.title): \(problem.message)"
1631 case .success(let result):
1632 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the command finished." }
1633 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1634 if !result.edits.isEmpty { changed(entry) }
1635 // A save that fails shows why, as Save does.
1636 if state.save { save(entry) }
1691 if let failure = script.failure { return .failure(ScriptFailure(text: failure)) }
1692 return .success(json)
1693 }
1694 #endif
1695
1696 // MARK: - Hooks
1697
1698 /// Whether `commands.toml` has hooks for `event`.
1699 public func hasHooks(_ event: UserHook.Event) -> Bool {
1700 hooks != nil && !userCommands.hooks(event).isEmpty
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 }
16371709 return nil
16381710 }
1639 #else
1640 return "User commands aren't available here."
1711 guard !changes.isEmpty, hasHooks(.afterTodoStateChange), let text = text ?? entry(path)?.buffer.document.text else { return }
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 }
16411809 #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 }
16421829 }
16431830
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
16441852 // MARK: - Locations
16451853
16461854 /// 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
55public enum UserCommandFile {
66 /// Reads `commands.toml` in `folder` into `store`, without running anything. The problems
77 /// 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.
99 @discardableResult
1010 public static func load(into store: UserCommands = .shared, folder: URL, read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }) -> [String] {
1111 let modules = folder.appendingPathComponent(UserCommands.folderName)
@@ -15,17 +15,18 @@ public enum UserCommandFile {
1515 }
1616 var problems: [String] = []
1717 var commands: [UserCommand] = []
18 var hooks: [UserHook] = []
1819 do {
19 commands = try UserCommands.parse(text, problems: &problems) { path in
20 (commands, hooks) = try UserCommands.manifest(text, problems: &problems) { path in
2021 FileManager.default.fileExists(atPath: modules.appendingPathComponent(path).path) || placeholder(modules.appendingPathComponent(path)) != nil
2122 }
2223 } catch {
2324 problems.append("\(error)")
2425 }
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)) {
2627 problems.append("\(UserCommands.folderName)/\(file) isn't downloaded from iCloud yet")
2728 }
28 store.replace(commands, folder: commands.isEmpty ? nil : modules)
29 store.replace(commands, hooks: hooks, folder: commands.isEmpty && hooks.isEmpty ? nil : modules)
2930 return problems.map { "\(UserCommands.fileName): \($0)" }
3031 }
3132
@@ -148,20 +149,35 @@ public enum UserCommandTrust {
148149 public let imports: [String]
149150 /// Its commands can also read every file in the folders and capture to them.
150151 public let workspace: Bool
152 /// Asked for a hook on this event rather than a command.
153 public let hook: UserHook.Event?
151154
152 public init(file: String, imports: [String] = [], workspace: Bool = false) {
155 public init(file: String, imports: [String] = [], workspace: Bool = false, hook: UserHook.Event? = nil) {
153156 self.file = file
154157 self.imports = imports
155158 self.workspace = workspace
159 self.hook = hook
156160 }
157161
158162 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")
160166 }
161167
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.
163170 public var message: String {
164171 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 }
165181 if !imports.isEmpty {
166182 let list = ListFormatter.localizedString(byJoining: imports)
167183 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 {
183199 public static func check(_ command: UserCommand, modules: URL, trust: TrustStore,
184200 ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void,
185201 run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
186 guard let texts = UserCommandFile.moduleTexts(command.file, modules: modules) else {
187 return refuse("No file \(UserCommands.folderName)/\(command.file)")
202 check(file: command.file, workspace: command.workspace, modules: modules, trust: trust, ask: ask, run: run, refuse: refuse)
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)")
188222 }
189223 let text = UserCommandFile.trustedText(texts)
190 let path = modules.appendingPathComponent(command.file).path
224 let path = modules.appendingPathComponent(file).path
191225 let workspaceText = workspaceTrust + text
192 let accepted = command.workspace ? [workspaceText] : [text, workspaceText]
226 let accepted = workspace ? [workspaceText] : [text, workspaceText]
193227 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()
195 let question = Question(file: "\(UserCommands.folderName)/\(command.file)",
196 imports: imports.map { "\(UserCommands.folderName)/\($0)" }, workspace: command.workspace)
228 let imports = texts.filter { $0.key != file && $0.value != nil }.keys.sorted()
229 let question = Question(file: "\(UserCommands.folderName)/\(file)",
230 imports: imports.map { "\(UserCommands.folderName)/\($0)" }, workspace: workspace, hook: hook)
197231 ask(question) { answer in
198232 switch answer {
199233 case .runOnce: run()
@@ -205,3 +239,24 @@ public enum UserCommandTrust {
205239 }
206240 }
207241}
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 {
232232 // A link that launched the app can come before the folders were first read.
233233 if workspace.files.isEmpty { await workspace.refresh() }
234234 switch action {
235 case .capture: return capture(request, sheet: interactive)
235 case .capture: return await capture(request, sheet: interactive)
236236 case .open: return open(request)
237237 case .agenda: return .reply(await agenda(request))
238238 case .clockIn: return .reply(await clockIn(request, ask: ask))
@@ -273,12 +273,12 @@ public struct XCallbackRunner {
273273 }
274274 }
275275
276 private func capture(_ request: XCallbackRequest, sheet: Bool) -> Step {
276 private func capture(_ request: XCallbackRequest, sheet: Bool) async -> Step {
277277 let properties = Self.properties(request)
278278 if sheet { return .capture(template: request.value("template"), properties: properties) }
279279 var answers = request.parameters
280280 for name in Self.reservedCaptureParameters { answers[name] = nil }
281 let placed = session.capture(
281 let placed = await session.captureRunningHooks(
282282 request.parameters["text"] ?? "", templateKey: request.value("template"), templates: templates(), workspace: workspace, clock: clock,
283283 clipboard: clipboard(), userName: userName, answers: answers, properties: properties
284284 )
Sources/OrgCore/Commands/Command.swift +20 · view
@@ -274,6 +274,26 @@ public enum Effect: Sendable, Equatable {
274274 case timer(OrgTimer?)
275275 /// A snippet was expanded; its fields are filled in next.
276276 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 }
277297}
278298
279299public struct EditResult: Sendable, Equatable {
Sources/OrgCore/Commands/EmacsBuffer.swift +4 −1 · view
@@ -40,6 +40,8 @@ final class EmacsBuffer {
4040 var lastInsertedTimestamp: String?
4141 /// Shown after the command commits, as `message`.
4242 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?)] = []
4345
4446 let options: EditingOptions
4547
@@ -501,7 +503,8 @@ func commitBuffer(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void)
501503 while prefix > 0, prefix < old.count, UTF16.isTrailSurrogate(old[prefix]) { prefix -= 1 }
502504 while suffix > 0, UTF16.isTrailSurrogate(old[old.count - suffix]) { suffix -= 1 }
503505 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)) }
505508 guard old.count != new.count || prefix != old.count else {
506509 return .commit(EditResult(baseRevision: context.revision, edits: [], selection: [caret..<caret], effects: effects))
507510 }
Sources/OrgCore/Commands/TodoLogging.swift +2 · view
@@ -183,9 +183,11 @@ extension EmacsBuffer {
183183
184184 /// What `org-todo` does after the keyword went from `previous` to the current one: CLOSED,
185185 /// 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.
186187 func afterTodoChange(previous: String?, answers: [String: String]) throws {
187188 let state = todoKeyword
188189 guard state != previous else { return }
190 if let heading = saveExcursion({ try? backToHeading() }) { todoChanges.append((marker(heading), previous, state)) }
189191 let log = logSettings()
190192 var setup = try saveExcursion { try todoLogging(previous: previous, state: state, log: log) }
191193 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 {
268268 var options = context.options
269269 for effect in result.effects {
270270 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
272273 case .timer(let timer): options.timer = timer
273274 default: break
274275 }
@@ -303,7 +304,7 @@ public struct UserCommandState: Sendable {
303304
304305 /// Ranges moved by edits that don't overlap: an offset inside or at the end of a replaced
305306 /// 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>] {
307308 let sorted = edits.sorted { $0.range.lowerBound < $1.range.lowerBound }
308309 func map(_ offset: Int) -> Int {
309310 var shift = 0
Sources/OrgCore/Commands/UserCommands.swift +116 −43 · view
@@ -53,6 +53,37 @@ public struct UserCommandRequest: Sendable, Equatable {
5353 }
5454}
5555
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
5687/// The commands of `commands.toml`, which the app reads from the configuration folder.
5788public final class UserCommands: @unchecked Sendable {
5889 public static let shared = UserCommands()
@@ -67,6 +98,7 @@ public final class UserCommands: @unchecked Sendable {
6798
6899 private let lock = NSLock()
69100 private var commands: [UserCommand] = []
101 private var hookList: [UserHook] = []
70102 private var modules: URL?
71103
72104 public init() {}
@@ -77,29 +109,44 @@ public final class UserCommands: @unchecked Sendable {
77109 /// The `commands` folder the modules are in; nil before a file was read.
78110 public var folder: URL? { lock.withLock { modules } }
79111
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
80117 public func command(_ id: String) -> UserCommand? {
81118 guard id.hasPrefix(Self.commandPrefix) else { return nil }
82119 let name = id.dropFirst(Self.commandPrefix.count)
83120 return lock.withLock { commands.first { $0.name == name } }
84121 }
85122
86 /// Replaces every command, as from the file, with the folder their modules are in.
87 public func replace(_ all: [UserCommand], folder: URL?) {
123 /// Replaces every command and hook, as from the file, with the folder their modules are in.
124 public func replace(_ all: [UserCommand], hooks: [UserHook] = [], folder: URL?) {
88125 lock.withLock {
89126 commands = all
127 hookList = hooks
90128 modules = folder
91129 }
92130 }
93131
94132 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout", "workspace"]
133 static let hookKeys: Set<String> = ["event", "file", "function", "timeout", "workspace"]
95134
96 /// The commands of a `commands.toml`. Entries that can't be used are skipped and reported in
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.
135 /// The commands of a `commands.toml`, as `manifest` reads them.
99136 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]) {
100146 let tables = try TOML.parse(toml)
101147 var api: Int?
102148 var result: [UserCommand] = []
149 var hooks: [UserHook] = []
103150 var names = Set<String>()
104151 for table in tables {
105152 if table.name.isEmpty {
@@ -113,10 +160,25 @@ public final class UserCommands: @unchecked Sendable {
113160 }
114161 continue
115162 }
116 guard table.name == "command", table.isArrayElement else {
163 guard ["command", "hook"].contains(table.name), table.isArrayElement else {
117164 problems.append("line \(table.line): unknown table [\(table.name)]")
118165 continue
119166 }
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 }
120182 guard let name = table.values["name"]?.string, NamedMacros.isValidName(name) else {
121183 problems.append("line \(table.line): command needs a name of letters, digits, - and _")
122184 continue
@@ -127,56 +189,67 @@ public final class UserCommands: @unchecked Sendable {
127189 problem("defined twice")
128190 continue
129191 }
130 guard let file = table.values["file"]?.string, !file.isEmpty else {
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 }
192 guard let module = module(table, exists: exists, problem: problem) else { continue }
146193 let when = table.values["when"]?.string
147194 if let when, !KeyContext.names.contains(when) {
148195 problem("unknown context \(when)")
149196 continue
150197 }
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 }
167198 if let value = table.values["title"], value.string == nil { problem("title must be a string") }
168199 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))
170202 }
171203 guard let api else {
172 if !result.isEmpty || tables.contains(where: { $0.name == "command" }) { problems.append("missing api = \(apiVersion)") }
173 return []
204 if !result.isEmpty || !hooks.isEmpty || tables.contains(where: { ["command", "hook"].contains($0.name) }) {
205 problems.append("missing api = \(apiVersion)")
206 }
207 return ([], [])
174208 }
175209 guard api == apiVersion else {
176210 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
178251 }
179 return result
252 return (file, function, timeout, workspace)
180253 }
181254
182255 /// 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 {
2929 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar+") }
3030 for _ in 0..<50 where Self.environment == nil { try? await Task.sleep(for: .milliseconds(100)) }
3131 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(
3333 text, templateKey: template, templates: CaptureTemplates.load().templates, workspace: workspace, clock: clock,
3434 clipboard: NSPasteboard.general.string(forType: .string) ?? "", userName: NSFullUserName()
3535 )
3636 switch placed {
3737 case .failure(let error):
3838 throw Failure(message: error.message)
39 case .success(let chosen):
39 case .success(let (chosen, _, _)):
4040 let message = "Captured to \(CaptureView.target(chosen))"
4141 commands.show(message)
4242 return .result(value: message, dialog: "\(message)")
Sources/Orgstar/CaptureView.swift +22 · view
@@ -37,6 +37,8 @@ struct CaptureView: View {
3737 @State private var roam: RoamCapture?
3838 /// The `captureRequest` serial of an x-callback-url capture, whose caller hears how it ends.
3939 @State private var callbackSerial: Int?
40 /// The capture's hooks are running.
41 @State private var finishing = false
4042 @FocusState private var focused: Bool
4143 @Environment(\.dismissWindow) private var dismissWindow
4244 @Environment(\.openWindow) private var openWindow
@@ -287,7 +289,27 @@ struct CaptureView: View {
287289 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
288290 }
289291
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.
290294 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) {
291313 guard let template else { return }
292314 let opened = context.now
293315 let now = Date()
Sources/Orgstar/ContentView.swift +12 · view
@@ -365,6 +365,18 @@ struct ContentView: View {
365365 .onAppear {
366366 commands.externalHandler = runExternal
367367 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)
368380 commands.filesHandler = { attachActions.drop($0) }
369381 commands.imageHandler = { attachActions.yankImage($0, ext: $1) }
370382 #if APPSTORE
Sources/Orgstar/PaneView.swift +1 · view
@@ -147,6 +147,7 @@ struct PaneView: NSViewRepresentable {
147147 NSPasteboard.general.setString(text, forType: .string)
148148 case .refreshSetup: session?.refreshSetup()
149149 case .timer(let timer): TimerModel.shared.set(timer)
150 case .todoStateChanged: session?.afterTodoStateChange([effect], in: path)
150151 case .message, .sparseTree, .fold, .snippet: break
151152 }
152153 }
Sources/OrgstarCLI/CaptureCommand.swift +7 · view
@@ -95,6 +95,13 @@ enum CaptureCommand {
9595 throw Failure(.failure, "Can't create \(path): \(error.localizedDescription)")
9696 }
9797 }
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 }
98105 let (result, text) = try workspace.perform(CapturePlacement(text: filled.text, template: chosen), path: path, at: 0)
99106 let offset = result.selection?.first?.lowerBound ?? 0
100107 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 {
2626 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar+") }
2727 let model = MobileModel.shared
2828 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(
3030 text, templateKey: template, templates: CaptureTemplates.load().templates, workspace: workspace, clock: model.clock,
3131 clipboard: "", userName: ""
3232 )
3333 switch placed {
3434 case .failure(let error):
3535 throw Failure(message: error.message)
36 case .success(let chosen):
36 case .success(let (chosen, _, _)):
3737 for path in model.session.dirtyPaths { _ = model.session.save(path) }
3838 let message = "Captured with \(chosen.name)"
3939 return .result(value: message, dialog: "\(message)")
Sources/OrgstarMobile/CaptureScreen.swift +26 −4 · view
@@ -37,6 +37,8 @@ struct CaptureScreen: View {
3737 /// The entry's date or tags sheet: on the form, not its section, which may not be in the window.
3838 @State private var planning: EntryPlanning?
3939 @State private var choosingTags = false
40 /// The capture's hooks are running.
41 @State private var finishing = false
4042 @FocusState private var focused: Bool
4143
4244 private var template: CaptureTemplate? { templates.first { $0.key == key } }
@@ -94,11 +96,11 @@ struct CaptureScreen: View {
9496 .toolbar {
9597 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
9698 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) } }
98100 }
99101 ToolbarItem(placement: .confirmationAction) {
100102 if editing {
101 Button("Capture") { file() }.disabled(template == nil)
103 Button("Capture") { finish() }.disabled(template == nil)
102104 } else {
103105 Button("Continue", action: fill)
104106 }
@@ -173,7 +175,7 @@ struct CaptureScreen: View {
173175 problem = nil
174176 editing = true
175177 focused = true
176 if template.options.immediateFinish { file() }
178 if template.options.immediateFinish { finish() }
177179 case .failure(.message(let message)):
178180 problem = message
179181 }
@@ -200,7 +202,27 @@ struct CaptureScreen: View {
200202 return calendar.date(from: parts) ?? Date()
201203 }
202204
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) {
204226 guard let template else { return }
205227 let now = Date()
206228 let placed: Result<(path: String, offset: Int), CaptureError>
Sources/OrgstarMobile/EditorScreen.swift +1 · view
@@ -548,6 +548,7 @@ struct EditorScreen: View {
548548 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
549549 editor.onUserCommand = { request, finished in runUserCommand(request, finished: finished) }
550550 editor.onRefreshSetup = { session.refreshSetup() }
551 editor.onTodoStateChange = { [path] in session.afterTodoStateChange($0, in: path) }
551552 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
552553 editor.keymap = model.keymap
553554 editor.modal = model.modalKeys
Sources/OrgstarMobile/MobileEditor.swift +3 · view
@@ -131,6 +131,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
131131 var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)?
132132 /// The file's setup files to read again (C-c C-c on a keyword line).
133133 var onRefreshSetup: (() -> Void)?
134 /// TODO keyword changes a command made, for the `after-todo-state-change` hooks.
135 var onTodoStateChange: (([Effect]) -> Void)?
134136 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
135137 var onEditBlock: ((BlockEdit) -> Void)?
136138 /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
@@ -396,6 +398,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
396398 state.folds.insert(start)
397399 setFolds(state)
398400 case .refreshSetup: onRefreshSetup?()
401 case .todoStateChanged: onTodoStateChange?([effect])
399402 case .timer(let timer): TimerModel.shared.set(timer)
400403 case .snippet(let session): startSnippet(session)
401404 default: break
Sources/OrgstarMobile/MobileModel.swift +3 · view
@@ -117,6 +117,9 @@ final class MobileModel {
117117 guard let self else { return }
118118 _ = self.clock.textChanged(path, self.session)
119119 }
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) })
120123 // A new Dynamic Type size restyles editors and the reader.
121124 sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
122125 MainActor.assumeIsolated { self?.settingsVersion += 1 }
Sources/OrgstarMobile/OrgstarMobileApp.swift +18 · view
@@ -461,6 +461,8 @@ struct RootView: View {
461461 }
462462 .task {
463463 TimerModel.shared.onDone = { message = $0 }
464 session.hooks = UserHookHost(trust: TrustStore(), ask: askHookTrust, report: { message = $0 },
465 workspace: UserCommandWorkspace(workspace: workspace, clock: model.clock))
464466 if let lost = UnsavedHeldFiles.atLaunch { message = lost }
465467 takeShared()
466468 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
@@ -671,6 +673,22 @@ struct RootView: View {
671673 }
672674 }
673675}
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}
674692#else
675693/// The iOS app has nothing to run elsewhere.
676694@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 {
142142 #expect(todo.contains(" :shop:\nfor the weekend\n* Project\n"))
143143 }
144144
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
145170 @Test func capturesALinkAsOrgProtocolDoes() async {
146171 let step = await runner.run(allowed("capture?template=t&text=Read&url=https%3A%2F%2Fexample.com&title=Example"))
147172 #expect(step == .reply(.success(["template": "t", "file": "todo.org"])))
Tests/OrgCoreTests/UserCommandTests.swift +77 · view
@@ -119,6 +119,83 @@ struct UserCommandManifestTests {
119119 #expect(problems == ["command bad: workspace must be true or false"])
120120 }
121121
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
122199 @Test func needsAKnownAPI() throws {
123200 let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n"
124201 #expect(try parse(command) == ([], ["missing api = 1"]))
Tests/OrgstarCLITests/ToolTests.swift +12 · view
@@ -167,6 +167,18 @@ struct CaptureTests {
167167 #expect(unknown.status == 3)
168168 #expect(unknown.err.contains("j (Journal)"))
169169 }
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 }
170182}
171183
172184@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}
6767
6868Targets 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.
6969
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
7072** clock
7173
7274#+BEGIN_SRC sh
docs/manual/guide/18-user-commands.org +97 −2 · view
@@ -1,5 +1,5 @@
11#+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.
33#+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.
44
55* Overview
@@ -58,6 +58,7 @@ Problems are reported like those of the other configuration files (see [[file:13
5858- =commands.toml: command slow: timeout must be 1 to 30 seconds=
5959- =commands.toml: command review: unknown context headline=
6060- =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]])
6162- =commands.toml: api 2 needs a newer orgstar= (no command is registered)
6263- =commands.toml: missing api = 1= (no command is registered)
6364- =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
267268
268269Edit ▸ 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.
269270
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
270359* Limits
271360
272361- *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:
287376- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
288377- 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=.
289378- 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.
291380- =interactive= codes other than the prompts above; =C-u= prefix arguments.
292381- Timers, processes and shell commands.
293382
@@ -327,3 +416,9 @@ What Emacs Lisp has that user commands don't:
327416| =(org-agenda-get-day-entries file date)=, =(org-agenda-list)= | =await org.agenda({from, to})= (=workspace = true=) |
328417| =(org-capture-string "Milk" "t")=, =(org-capture nil "t")= | =await org.capture("t", "Milk", {…})= (=workspace = true=) |
329418| =(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 @@
500500 }
501501 }
502502 },
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 },
503538 "%@ changed on disk while saving, and the changes conflict with yours; both are in the editor between conflict markers.": {
504539 "localizations": {
505540 "de": {
@@ -534,6 +569,41 @@
534569 }
535570 }
536571 },
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 },
537607 "%@ didn't finish within %lld s and was stopped.": {
538608 "comment": "A user command passed its time limit",
539609 "localizations": {
@@ -1159,6 +1229,41 @@
11591229 }
11601230 }
11611231 },
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 },
11621267 "%@ late": {
11631268 "localizations": {
11641269 "de": {
@@ -42038,6 +42143,41 @@
4203842143 }
4203942144 }
4204042145 },
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 },
4204142181 "Run this %@ block? (%@)": {
4204242182 "comment": "Echo area prompt: the block's language, then the answers it accepts (yes, no, always), which stay in English",
4204342183 "localizations": {
@@ -51392,6 +51532,76 @@
5139251532 }
5139351533 }
5139451534 },
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 },
5139551605 "This is the only pane.": {
5139651606 "comment": "Close Pane with one pane",
5139751607 "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