Commit 73b5c3d293

73b5c3d29343d6a3801f3a9a591fa434c01c9f06

parent: 4d8e517de5

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-27 16:56 UTC

User commands: workspace reads and capture

workspace = true on a [[command]] in commands.toml enables org.search
(the index search, at most 50 matches as {file, title, outline, start,
heading, snippet}), org.outlineOf (an org file in the folders, symlinks
resolved, as org.outline() gives it), org.agenda({from, to}) (entries
in the x-callback-url agenda shape, at most 366 days and 200 entries)
and org.capture(key, text, fields) (the x-callback-url non-interactive
rules: every prompt answered or nothing is filed; not to the command's
own file). Other commands get an error from these calls. Index and
disk reads run off the main thread.

Text encrypted on disk is never returned: .gpg files are refused or
left out, buffers with decrypted entries are read as on disk, and
matches in encrypted entries have no snippet.

The trust question for such files says they can read the folders and
capture; that trust is stored apart from buffer-only trust, so adding
workspace = true asks again. Manual chapter 18 updated.

Closes #247

Layout: unified · split

Changed files (12)
Sources/OrgApp/CommandHost.swift +4 · view
@@ -424,6 +424,10 @@ public final class CommandHost {
424 prompt: options => call("prompt", typeof options === "string" ? { message: options } : options ?? {}), 424 prompt: options => call("prompt", typeof options === "string" ? { message: options } : options ?? {}),
425 message: text => call("message", String(text)), 425 message: text => call("message", String(text)),
426 run: id => call("run", String(id)), 426 run: id => call("run", String(id)),
427 search: query => call("search", String(query)),
428 outlineOf: path => call("outlineOf", String(path)),
429 agenda: span => call("agenda", span ?? {}),
430 capture: (template, text, fields) => call("capture", { template: String(template), text: text ?? null, fields: fields ?? null }),
427 fail, 431 fail,
428 }); 432 });
429 } 433 }
Sources/OrgApp/DocumentSession.swift +14 −3 · view
@@ -1493,13 +1493,14 @@ public final class DocumentSession {
1493 /// context at the request's revision; the message comes back through `report`. `file` is 1493 /// context at the request's revision; the message comes back through `report`. `file` is
1494 /// the file's path relative to its folder, for `org.file()`. Prompts go to `ask`. `finished` 1494 /// the file's path relative to its folder, for `org.file()`. Prompts go to `ask`. `finished`
1495 /// gets the message once the command has ended, nil when its result was applied. 1495 /// gets the message once the command has ended, nil when its result was applied.
1496 public func startUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?, 1496 /// `workspace` answers the calls of commands with `workspace = true`.
1497 public func startUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?, workspace: UserCommandWorkspace? = nil,
1497 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void, 1498 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
1498 report: @escaping @MainActor (String) -> Void, 1499 report: @escaping @MainActor (String) -> Void,
1499 finished: @escaping @MainActor (String?) -> Void = { _ in }) { 1500 finished: @escaping @MainActor (String?) -> Void = { _ in }) {
1500 userCommandTask?.cancel() 1501 userCommandTask?.cancel()
1501 isRunningUserCommand = true 1502 isRunningUserCommand = true
1502 let task = Task { await runUserCommand(request, context: context, file: file, ask: ask, report: report) } 1503 let task = Task { await runUserCommand(request, context: context, file: file, workspace: workspace, ask: ask, report: report) }
1503 userCommandTask = task 1504 userCommandTask = task
1504 Task { 1505 Task {
1505 let message = await task.value 1506 let message = await task.value
@@ -1527,7 +1528,7 @@ public final class DocumentSession {
1527 1528
1528 /// Runs `request` in the focused buffer and applies what it returns as one change at the 1529 /// Runs `request` in the focused buffer and applies what it returns as one change at the
1529 /// request's revision. The message to show; nil when the command's own messages were shown. 1530 /// request's revision. The message to show; nil when the command's own messages were shown.
1530 func runUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?, 1531 func runUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?, workspace: UserCommandWorkspace? = nil,
1531 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void, 1532 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
1532 report: @escaping @MainActor (String) -> Void) async -> String? { 1533 report: @escaping @MainActor (String) -> Void) async -> String? {
1533 let command = request.command 1534 let command = request.command
@@ -1593,6 +1594,16 @@ public final class DocumentSession {
1593 case "fail": 1594 case "fail":
1594 state.failure = value as? String ?? "" 1595 state.failure = value as? String ?? ""
1595 return NSNull() 1596 return NSNull()
1597 case _ where UserCommandWorkspace.calls.contains(name):
1598 guard command.workspace else {
1599 throw CommandHost.Failure.script("org.\(name) needs workspace = true on the command in \(UserCommands.fileName).")
1600 }
1601 guard let workspace else { throw CommandHost.Failure.script("org.\(name) isn't available here.") }
1602 do throws(UserCommandWorkspace.Failure) {
1603 return try await workspace.answer(name, value, session: self, path: path)
1604 } catch {
1605 throw CommandHost.Failure.script(error.message)
1606 }
1596 default: 1607 default:
1597 throw CommandHost.Failure.script("org.\(name) isn't in API version \(UserCommands.apiVersion).") 1608 throw CommandHost.Failure.script("org.\(name) isn't in API version \(UserCommands.apiVersion).")
1598 } 1609 }
Sources/OrgApp/UserCommandFile.swift +12 −4 · view
@@ -136,6 +136,10 @@ public enum UserCommandTrust {
136 } 136 }
137 } 137 }
138 138
139 /// Put before the trusted text of a file trusted for commands with `workspace = true`. The
140 /// trusted text itself always starts with `// `, so no buffer-only text can match.
141 static let workspaceTrust = "\u{0}workspace\n"
142
139 public struct Question: Equatable, Sendable { 143 public struct Question: Equatable, Sendable {
140 /// The command's file, as `commands/review.js`. 144 /// The command's file, as `commands/review.js`.
141 public let file: String 145 public let file: String
@@ -173,7 +177,9 @@ public enum UserCommandTrust {
173 177
174 /// Runs `run` at once when the command's file and its imports are trusted, else asks: Run 178 /// Runs `run` at once when the command's file and its imports are trusted, else asks: Run
175 /// Once runs it, Always trusts the files as they are now and runs it, anything else says 179 /// Once runs it, Always trusts the files as they are now and runs it, anything else says
176 /// why nothing ran through `refuse`. 180 /// why nothing ran through `refuse`. Trust for commands with `workspace = true` is kept
181 /// apart: it covers the file's other commands too, but trust given without it doesn't
182 /// cover them.
177 public static func check(_ command: UserCommand, modules: URL, trust: TrustStore, 183 public static func check(_ command: UserCommand, modules: URL, trust: TrustStore,
178 ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void, 184 ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void,
179 run: @escaping () -> Void, refuse: @escaping (String) -> Void) { 185 run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
@@ -182,15 +188,17 @@ public enum UserCommandTrust {
182 } 188 }
183 let text = UserCommandFile.trustedText(texts) 189 let text = UserCommandFile.trustedText(texts)
184 let path = modules.appendingPathComponent(command.file).path 190 let path = modules.appendingPathComponent(command.file).path
185 if trust.isTrusted(path: path, content: text) { return run() } 191 let workspaceText = workspaceTrust + text
192 let accepted = command.workspace ? [workspaceText] : [text, workspaceText]
193 if accepted.contains(where: { trust.isTrusted(path: path, content: $0) }) { return run() }
186 let imports = texts.filter { $0.key != command.file && $0.value != nil }.keys.sorted() 194 let imports = texts.filter { $0.key != command.file && $0.value != nil }.keys.sorted()
187 let question = Question(file: "\(UserCommands.folderName)/\(command.file)", 195 let question = Question(file: "\(UserCommands.folderName)/\(command.file)",
188 imports: imports.map { "\(UserCommands.folderName)/\($0)" }) 196 imports: imports.map { "\(UserCommands.folderName)/\($0)" }, workspace: command.workspace)
189 ask(question) { answer in 197 ask(question) { answer in
190 switch answer { 198 switch answer {
191 case .runOnce: run() 199 case .runOnce: run()
192 case .always: 200 case .always:
193 trust.trust(path: path, content: text) 201 trust.trust(path: path, content: accepted[0])
194 run() 202 run()
195 case .dontRun, nil: refuse(String(localized: "Not run")) 203 case .dontRun, nil: refuse(String(localized: "Not run"))
196 } 204 }
Sources/OrgApp/UserCommandWorkspace.swift added +227 · view
@@ -0,0 +1,227 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import OrgIndex
5
6/// The calls a user command with `workspace = true` makes beyond its buffer: `org.search`,
7/// `org.outlineOf`, `org.agenda` and `org.capture`. Reads never return text that is encrypted
8/// on disk: `.gpg` files are refused or left out, buffers holding decrypted entries are read
9/// from disk, and a search match in an encrypted entry has no snippet.
10@MainActor
11public struct UserCommandWorkspace {
12 public let workspace: WorkspaceModel
13 public let clock: ClockModel
14 public var templates: () -> [CaptureTemplate] = { CaptureTemplates.load().templates }
15 /// `%n` in capture templates.
16 public var userName = ""
17 public var now: () -> Date = Date.init
18 public var calendar = Calendar.current
19
20 /// The calls, by name, that need `workspace = true`.
21 public static let calls: Set<String> = ["search", "outlineOf", "agenda", "capture"]
22 /// The most `org.search` returns.
23 public static let searchLimit = 50
24 /// The most `org.agenda` returns, as many as the x-callback-url `agenda` action may.
25 public static let agendaLimit = XCallbackRunner.maximumLimit
26 /// The longest span `org.agenda` covers.
27 public static let maximumDays = 366
28
29 public init(workspace: WorkspaceModel, clock: ClockModel) {
30 self.workspace = workspace
31 self.clock = clock
32 }
33
34 public struct Failure: Error, Equatable {
35 public let message: String
36 init(_ message: String) { self.message = message }
37 }
38
39 /// The answer to `name`, one of `calls`, for a command running in `path`'s buffer.
40 func answer(_ name: String, _ value: Any, session: DocumentSession, path: String) async throws(Failure) -> Any {
41 switch name {
42 case "search": return try await search(value, session: session)
43 case "outlineOf": return try await outline(value, session: session)
44 case "agenda": return try await agenda(value, session: session)
45 case "capture": return try capture(value, session: session, path: path)
46 default: throw Failure("No call \(name).")
47 }
48 }
49
50 // MARK: - Search
51
52 /// `{file, title, outline, start, heading, snippet}` for each match, best first: `outline`
53 /// is the titles of the headings above it, `heading` false for a match in the text before
54 /// a file's first heading (then `title` is the file's), `snippet` the text around the match
55 /// or null.
56 func search(_ value: Any, session: DocumentSession) async throws(Failure) -> Any {
57 guard let query = value as? String else { throw Failure("org.search needs a query string.") }
58 // Unsaved buffers are searched as they are, except those holding decrypted entries,
59 // which are searched as they are on disk.
60 let shown = session.openTexts
61 let overlay = workspace.overlay(session.openDocuments.filter { shown[$0.path] != nil })
62 let index = workspace.index
63 let roots = workspace.rootPaths
64 let limit = Self.searchLimit
65 let found: [Match]
66 do {
67 found = try await Task.detached {
68 try index.search(query, overlay: overlay, limit: limit).compactMap { location -> Match? in
69 guard !CryptVault.isEncryptedFile(location.path) else { return nil }
70 let body = try? index.text(of: location, overlay: overlay)
71 let encrypted = body?.contains("-----BEGIN PGP MESSAGE-----") == true
72 return Match(file: UserCommandFile.relativePath(location.path, roots: roots), title: location.title,
73 outline: Array(location.outlinePath.dropLast()), start: location.start,
74 heading: location.ordinal != HeadingLocation.fileOrdinal,
75 snippet: encrypted ? nil : location.snippet?.text)
76 }
77 }.value
78 } catch {
79 throw Failure("Can't read the index: \(error.localizedDescription)")
80 }
81 return found.map { match -> [String: Any] in
82 ["file": match.file, "title": match.title, "outline": match.outline, "start": match.start, "heading": match.heading,
83 "snippet": match.snippet ?? NSNull()]
84 }
85 }
86
87 struct Match: Sendable {
88 let file: String
89 let title: String
90 let outline: [String]
91 let start: Int
92 let heading: Bool
93 let snippet: String?
94 }
95
96 // MARK: - Outline of another file
97
98 /// The headings of an org file in the folders, as `org.outline()` gives them: a path
99 /// relative to a folder or absolute inside one, after symlinks are resolved.
100 func outline(_ value: Any, session: DocumentSession) async throws(Failure) -> Any {
101 guard let given = value as? String, !given.isEmpty else { throw Failure("org.outlineOf needs a path.") }
102 guard let path = Self.resolve(given, roots: workspace.rootPaths) else { throw Failure("No file \(given) in orgstar's folders.") }
103 guard !CryptVault.isEncryptedFile(path) else { throw Failure("\(given) is encrypted, so user commands can't read it.") }
104 guard path.hasSuffix(".org") || path.hasSuffix(".org_archive") else { throw Failure("\(given) isn't an org file.") }
105 let context: EditContext
106 if session.refusesUserCommand(path) == nil, let document = session.document(of: path) {
107 context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [0..<0])
108 } else {
109 // Not open, or holding decrypted entries: what's on disk.
110 let defaults = session.defaults
111 guard let read = await Task.detached(operation: { () -> EditContext? in
112 guard let data = FileManager.default.contents(atPath: path) else { return nil }
113 let text = SourceText(bytes: [UInt8](data)).text
114 return EditContext(revision: 0, text: text, tree: OrgParser.parse(text, defaults: defaults), selection: [0..<0])
115 }).value else { throw Failure("Can't read \(given).") }
116 context = read
117 }
118 return UserCommandAPI.answer("outline", NSNull(), context: context, file: nil) ?? []
119 }
120
121 /// `given` relative to the first folder that has it, or absolute (or `~/…`) inside one,
122 /// when it is a file whose real path, symlinks resolved, is inside that folder's.
123 nonisolated static func resolve(_ given: String, roots: [String]) -> String? {
124 func real(_ path: String) -> String? {
125 realpath(path, nil).map { defer { free($0) }; return String(cString: $0) }
126 }
127 let candidates = given.hasPrefix("/") || given.hasPrefix("~")
128 ? [(OrgPaths.expandingTilde(given) as NSString).standardizingPath]
129 : roots.map { ((($0 as NSString).appendingPathComponent(given)) as NSString).standardizingPath }
130 for candidate in candidates {
131 guard let file = real(candidate) else { continue }
132 var directory: ObjCBool = false
133 guard FileManager.default.fileExists(atPath: file, isDirectory: &directory), !directory.boolValue else { continue }
134 let inside = roots.contains { root in
135 guard let root = real(root) else { return false }
136 return file.hasPrefix(root.hasSuffix("/") ? root : root + "/")
137 }
138 if inside { return candidate }
139 }
140 return nil
141 }
142
143 // MARK: - Agenda
144
145 /// The agenda's entries from `from` to `to` (`YYYY-MM-DD`, both included; today and `from`
146 /// when not given), in the shape of the x-callback-url `agenda` action's.
147 func agenda(_ value: Any, session: DocumentSession) async throws(Failure) -> Any {
148 let options = value as? [String: Any] ?? [:]
149 let today = Days.absolute(now(), calendar: calendar)
150 func day(_ key: String) throws(Failure) -> Int? {
151 guard let raw = options[key], !(raw is NSNull) else { return nil }
152 guard let text = raw as? String, let day = Self.day(text) else { throw Failure("org.agenda: \(key) must be a date as YYYY-MM-DD.") }
153 return day
154 }
155 let from = try day("from") ?? today
156 let to = try day("to") ?? from
157 guard to >= from else { throw Failure("org.agenda: to is before from.") }
158 guard to - from < Self.maximumDays else { throw Failure("org.agenda: a span of at most \(Self.maximumDays) days.") }
159 let model = AgendaModel(workspace: workspace)
160 XCallbackRunner.configure(model)
161 model.mode = .agenda(span: to - from + 1, startOffset: nil)
162 model.start = from
163 model.startOnWeekday = nil
164 await model.refresh(open: session.openTexts, now: now(), calendar: calendar)
165 let roots = workspace.rootPaths
166 let entries = XCallbackRunner.entries(model, calendar: calendar) { UserCommandFile.relativePath($0, roots: roots) }
167 .filter { $0.file.map { !CryptVault.isEncryptedFile($0) } ?? true }
168 let encoder = JSONEncoder()
169 guard let data = try? encoder.encode(Array(entries.prefix(Self.agendaLimit))),
170 let json = try? JSONSerialization.jsonObject(with: data) else { return [Any]() }
171 return json
172 }
173
174 /// The day `YYYY-MM-DD` names, as `Days` numbers it.
175 nonisolated static func day(_ text: String) -> Int? {
176 let parts = text.split(separator: "-", omittingEmptySubsequences: false)
177 guard parts.count == 3, parts[0].count == 4, parts[1].count == 2, parts[2].count == 2,
178 let year = Int(parts[0]), let month = Int(parts[1]), let day = Int(parts[2]),
179 (1...12).contains(month), (1...31).contains(day) else { return nil }
180 let absolute = Days.absolute(year: year, month: month, day: day)
181 let back = Days.date(absolute)
182 return back.month == month && back.day == day ? absolute : nil
183 }
184
185 // MARK: - Capture
186
187 /// Files `text` with the template keyed `template`, without the capture window, as the
188 /// x-callback-url `capture` action does: every prompt of the template must have an answer
189 /// in `fields`, by its prompt text, or nothing is filed. `{template, file}` with the file
190 /// relative to its folder.
191 func capture(_ value: Any, session: DocumentSession, path: String) throws(Failure) -> Any {
192 let options = value as? [String: Any] ?? [:]
193 guard let key = options["template"] as? String, !key.isEmpty else { throw Failure("org.capture needs a template key.") }
194 guard let text = options["text"] as? String else { throw Failure("org.capture needs the text to capture.") }
195 var fields: [String: String] = [:]
196 if let raw = options["fields"], !(raw is NSNull) {
197 guard let given = raw as? [String: Any] else { throw Failure("org.capture: fields must be an object of strings.") }
198 for (name, answer) in given {
199 guard let answer = answer as? String else { throw Failure("org.capture: field \(name) must be a string.") }
200 fields[name] = answer
201 }
202 }
203 let templates = templates()
204 guard let template = templates.first(where: { $0.key == key }) else { throw Failure("No capture template \"\(key)\".") }
205 if template.options.denote || template.asksTreeDate {
206 throw Failure("Template \"\(key)\" makes a Denote note or asks for a date tree's day, which needs the capture window.")
207 }
208 let missing = XCallbackRunner.unanswered(template, text: text, properties: [:], given: Set(fields.keys))
209 guard missing.isEmpty else {
210 throw Failure("Template \"\(key)\" asks for \(missing.joined(separator: ", ")); give \(missing.count == 1 ? "it" : "them") in fields.")
211 }
212 let target: String
213 switch template.resolved(workspace: workspace, session: session, clock: clock) {
214 case .failure(let error): throw Failure(error.message)
215 case .success(let resolved): target = resolved.file ?? DocumentSession.resolve(resolved.template.target.file, root: workspace.rootPaths.first)
216 }
217 // Its own buffer changes only through the edits the command returns, as one undo step.
218 let real = { (path: String) in URL(fileURLWithPath: path).resolvingSymlinksInPath().path }
219 guard real(target) != real(path) else { throw Failure("org.capture can't file to the file the command runs in; return edits instead.") }
220 switch session.capture(text, templateKey: key, templates: [template], workspace: workspace, clock: clock,
221 clipboard: "", userName: userName, answers: fields) {
222 case .failure(let error): throw Failure(error.message)
223 case .success(let placed):
224 return ["template": key, "file": UserCommandFile.relativePath(placed.path, roots: workspace.rootPaths)]
225 }
226 }
227}
Sources/OrgApp/XCallback.swift +29 −14 · view
@@ -260,11 +260,16 @@ public struct XCallbackRunner {
260 guard let key = request.value("template"), let text = request.parameters["text"], 260 guard let key = request.value("template"), let text = request.parameters["text"],
261 let template = templates().first(where: { $0.key == key }) else { return true } 261 let template = templates().first(where: { $0.key == key }) else { return true }
262 if template.options.denote || template.asksTreeDate { return true } 262 if template.options.denote || template.asksTreeDate { return true }
263 return !Self.unanswered(template, text: text, properties: Self.properties(request), given: Set(request.parameters.keys)).isEmpty
264 }
265
266 /// The prompts of `template` that `given` has no answer for, by prompt text, in order.
267 static func unanswered(_ template: CaptureTemplate, text: String, properties: [String: String], given: Set<String>) -> [String] {
263 var context = CaptureContext(initial: text) 268 var context = CaptureContext(initial: text)
264 context.linkProperties = Self.properties(request) 269 context.linkProperties = properties
265 return Capture.questions(template.template, context: context).contains { question in 270 return Capture.questions(template.template, context: context).compactMap { question in
266 if case .clipboard = question.kind { return false } 271 if case .clipboard = question.kind { return nil }
267 return request.parameters[question.prompt] == nil 272 return given.contains(question.prompt) ? nil : question.prompt
268 } 273 }
269 } 274 }
270 275
@@ -386,6 +391,18 @@ public struct XCallbackRunner {
386 let model = AgendaModel(workspace: workspace) 391 let model = AgendaModel(workspace: workspace)
387 model.viewSettings = AgendaViewLoader.settings(views) 392 model.viewSettings = AgendaViewLoader.settings(views)
388 model.mode = view.mode 393 model.mode = view.mode
394 Self.configure(model)
395 await model.refresh(open: session.openTexts, now: now(), calendar: calendar)
396 let entries = entries(model)
397 let kept = Array(entries.prefix(limit))
398 let encoder = JSONEncoder()
399 encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
400 let json = (try? encoder.encode(kept)).map { String(decoding: $0, as: UTF8.self) } ?? "[]"
401 return .success(["view": view.name, "result": json, "count": String(kept.count), "total": String(entries.count)])
402 }
403
404 /// The agenda settings of the app's preferences.
405 static func configure(_ model: AgendaModel) {
389 model.span = OrgPreferences.agendaSpan() 406 model.span = OrgPreferences.agendaSpan()
390 model.startOffset = OrgPreferences.agendaStartOffset() 407 model.startOffset = OrgPreferences.agendaStartOffset()
391 model.startOnWeekday = OrgPreferences.agendaStartOnWeekday() 408 model.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
@@ -394,24 +411,22 @@ public struct XCallbackRunner {
394 model.hiddenFolders = HiddenFolders.shared.all 411 model.hiddenFolders = HiddenFolders.shared.all
395 model.agendaFiles = OrgPreferences.agendaFiles() 412 model.agendaFiles = OrgPreferences.agendaFiles()
396 model.options = OrgPreferences.agendaOptions(model.options) 413 model.options = OrgPreferences.agendaOptions(model.options)
397 await model.refresh(open: session.openTexts, now: now(), calendar: calendar)
398 let entries = entries(model)
399 let kept = Array(entries.prefix(limit))
400 let encoder = JSONEncoder()
401 encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
402 let json = (try? encoder.encode(kept)).map { String(decoding: $0, as: UTF8.self) } ?? "[]"
403 return .success(["view": view.name, "result": json, "count": String(kept.count), "total": String(entries.count)])
404 } 414 }
405 415
406 /// The view's lines, in order: each day's overdue entries and then its rows, or the list. 416 /// The view's lines, in order: each day's overdue entries and then its rows, or the list.
407 func entries(_ model: AgendaModel) -> [Entry] { 417 func entries(_ model: AgendaModel) -> [Entry] {
418 Self.entries(model, calendar: calendar, relative: relative)
419 }
420
421 /// `entries(_:)` with files named by `relative`.
422 static func entries(_ model: AgendaModel, calendar: Calendar, relative: (String) -> String) -> [Entry] {
408 let today = model.today 423 let today = model.today
409 func make(_ results: [(header: String?, days: [AgendaDay], list: [AgendaItem])]) -> [Entry] { 424 func make(_ results: [(header: String?, days: [AgendaDay], list: [AgendaItem])]) -> [Entry] {
410 results.flatMap { result -> [Entry] in 425 results.flatMap { result -> [Entry] in
411 let days = AgendaRows.groups(result.days, today: today, calendar: calendar).flatMap { group in 426 let days = AgendaRows.groups(result.days, today: today, calendar: calendar).flatMap { group in
412 (group.overdue + group.rows).map { line($0, day: group.day, section: result.header) } 427 (group.overdue + group.rows).map { Self.line($0, day: group.day, section: result.header, relative: relative) }
413 } 428 }
414 let list = result.list.compactMap { AgendaRow(item: $0, day: today, today: today) }.map { line($0, day: nil, section: result.header) } 429 let list = result.list.compactMap { AgendaRow(item: $0, day: today, today: today) }.map { Self.line($0, day: nil, section: result.header, relative: relative) }
415 return days + list 430 return days + list
416 } 431 }
417 } 432 }
@@ -421,7 +436,7 @@ public struct XCallbackRunner {
421 return make([(nil, model.days, model.list)]) 436 return make([(nil, model.days, model.list)])
422 } 437 }
423 438
424 private func line(_ row: AgendaRow, day: Int?, section: String?) -> Entry { 439 private static func line(_ row: AgendaRow, day: Int?, section: String?, relative: (String) -> String) -> Entry {
425 func date(_ day: Int) -> String { 440 func date(_ day: Int) -> String {
426 let d = Days.date(day) 441 let d = Days.date(day)
427 return String(format: "%04d-%02d-%02d", d.year, d.month, d.day) 442 return String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
Sources/OrgCore/Commands/UserCommands.swift +16 −3 · view
@@ -14,14 +14,19 @@ public struct UserCommand: OrgCommand, Equatable {
14 public let when: String? 14 public let when: String?
15 /// Seconds, at most `UserCommands.maximumTimeout`. 15 /// Seconds, at most `UserCommands.maximumTimeout`.
16 public let timeout: Int 16 public let timeout: Int
17 /// `workspace = true`: the command may also search the folders, read other files' outlines
18 /// and the agenda, and capture.
19 public let workspace: Bool
17 20
18 public init(name: String, title: String, file: String, function: String, when: String? = nil, timeout: Int = UserCommands.defaultTimeout) { 21 public init(name: String, title: String, file: String, function: String, when: String? = nil, timeout: Int = UserCommands.defaultTimeout,
22 workspace: Bool = false) {
19 self.name = name 23 self.name = name
20 self.title = title 24 self.title = title
21 self.file = file 25 self.file = file
22 self.function = function 26 self.function = function
23 self.when = when 27 self.when = when
24 self.timeout = timeout 28 self.timeout = timeout
29 self.workspace = workspace
25 } 30 }
26 31
27 public var id: String { UserCommands.commandPrefix + name } 32 public var id: String { UserCommands.commandPrefix + name }
@@ -86,7 +91,7 @@ public final class UserCommands: @unchecked Sendable {
86 } 91 }
87 } 92 }
88 93
89 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout"] 94 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout", "workspace"]
90 95
91 /// The commands of a `commands.toml`. Entries that can't be used are skipped and reported in 96 /// The commands of a `commands.toml`. Entries that can't be used are skipped and reported in
92 /// `problems`; with a missing or newer `api`, none is used. `exists` says whether a module 97 /// `problems`; with a missing or newer `api`, none is used. `exists` says whether a module
@@ -151,9 +156,17 @@ public final class UserCommands: @unchecked Sendable {
151 } 156 }
152 timeout = seconds 157 timeout = seconds
153 } 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 }
154 if let value = table.values["title"], value.string == nil { problem("title must be a string") } 167 if let value = table.values["title"], value.string == nil { problem("title must be a string") }
155 let title = table.values["title"]?.string.flatMap { $0.isEmpty ? nil : $0 } ?? name 168 let title = table.values["title"]?.string.flatMap { $0.isEmpty ? nil : $0 } ?? name
156 result.append(UserCommand(name: name, title: title, file: file, function: function, when: when, timeout: timeout)) 169 result.append(UserCommand(name: name, title: title, file: file, function: function, when: when, timeout: timeout, workspace: workspace))
157 } 170 }
158 guard let api else { 171 guard let api else {
159 if !result.isEmpty || tables.contains(where: { $0.name == "command" }) { problems.append("missing api = \(apiVersion)") } 172 if !result.isEmpty || tables.contains(where: { $0.name == "command" }) { problems.append("missing api = \(apiVersion)") }
Sources/OrgIndex/IndexStore.swift +14 −3 · view
@@ -40,6 +40,9 @@ public struct HeadingLocation: Sendable, Hashable {
40 public let contentHash: String 40 public let contentHash: String
41 /// The text around the match: a search's words, or a backlink's link. 41 /// The text around the match: a search's words, or a backlink's link.
42 public var snippet: Snippet? 42 public var snippet: Snippet?
43 /// The titles from the top-level heading down to this one; set by `search`, empty for the
44 /// file itself.
45 public var outlinePath: [String] = []
43 46
44 public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) { 47 public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) {
45 self.path = path 48 self.path = path
@@ -331,7 +334,7 @@ public final class IndexStore: Sendable {
331 let headings = try Row.fetchAll( 334 let headings = try Row.fetchAll(
332 db, 335 db,
333 sql: """ 336 sql: """
334 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, headings_fts.body, bm25(headings_fts) AS rank 337 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.outline_path, headings_fts.body, bm25(headings_fts) AS rank
335 FROM headings_fts 338 FROM headings_fts
336 JOIN headings h ON h.id = headings_fts.rowid 339 JOIN headings h ON h.id = headings_fts.rowid
337 JOIN files f ON f.id = h.file_id 340 JOIN files f ON f.id = h.file_id
@@ -340,7 +343,11 @@ public final class IndexStore: Sendable {
340 LIMIT ? 343 LIMIT ?
341 """, 344 """,
342 arguments: [match, limit + overlay.count * 10] 345 arguments: [match, limit + overlay.count * 10]
343 ).map { (location: withSnippet(location($0), $0["body"]), rank: $0["rank"] as Double) } 346 ).map { row in
347 var found = withSnippet(location(row), row["body"])
348 found.outlinePath = (row["outline_path"] as String).split(separator: "\u{1F}", omittingEmptySubsequences: false).map(String.init)
349 return (location: found, rank: row["rank"] as Double)
350 }
344 let files = try Row.fetchAll( 351 let files = try Row.fetchAll(
345 db, 352 db,
346 sql: """ 353 sql: """
@@ -362,7 +369,11 @@ public final class IndexStore: Sendable {
362 } 369 }
363 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in 370 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
364 let file = matches(record.preamble) ? [withSnippet(fileLocation(record.path, title: record.title, hash: record.hash), record.preamble)] : [] 371 let file = matches(record.preamble) ? [withSnippet(fileLocation(record.path, title: record.title, hash: record.hash), record.preamble)] : []
365 return file + record.headings.filter { matches($0.title + "\n" + $0.body) }.map { withSnippet(location(record, $0), $0.body) } 372 return file + record.headings.filter { matches($0.title + "\n" + $0.body) }.map { heading in
373 var found = withSnippet(location(record, heading), heading.body)
374 found.outlinePath = heading.outlinePath
375 return found
376 }
366 } 377 }
367 return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit)) 378 return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit))
368 } 379 }
Sources/Orgstar/ContentView.swift +3 −1 · view
@@ -1316,8 +1316,10 @@ struct ContentView: View {
1316 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: { 1316 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: {
1317 guard let editor = commands.editor else { return finished("") } 1317 guard let editor = commands.editor else { return finished("") }
1318 commands.show(String(localized: "Running \(request.command.title)… (⌘. to cancel)", comment: "A user command started")) 1318 commands.show(String(localized: "Running \(request.command.title)… (⌘. to cancel)", comment: "A user command started"))
1319 var access = UserCommandWorkspace(workspace: workspace, clock: clock)
1320 access.userName = NSFullUserName()
1319 session.startUserCommand(request, context: editor.context(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), 1321 session.startUserCommand(request, context: editor.context(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths),
1320 ask: editor.ask, report: { commands.show($0) }, finished: finished) 1322 workspace: access, ask: editor.ask, report: { commands.show($0) }, finished: finished)
1321 }, refuse: { 1323 }, refuse: {
1322 commands.show($0) 1324 commands.show($0)
1323 finished($0) 1325 finished($0)
Sources/OrgstarMobile/EditorScreen.swift +1 · view
@@ -456,6 +456,7 @@ struct EditorScreen: View {
456 guard let editor else { return finished("") } 456 guard let editor else { return finished("") }
457 message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad") 457 message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad")
458 session.startUserCommand(request, context: editor.editContext(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), 458 session.startUserCommand(request, context: editor.editContext(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths),
459 workspace: UserCommandWorkspace(workspace: workspace, clock: model.clock),
459 ask: editor.ask, report: { message = $0 }, finished: finished) 460 ask: editor.ask, report: { message = $0 }, finished: finished)
460 }, refuse: { 461 }, refuse: {
461 message = $0 462 message = $0
Tests/OrgAppTests/UserCommandWorkspaceTests.swift added +284 · view
@@ -0,0 +1,284 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// `org.search`, `org.outlineOf`, `org.agenda` and `org.capture` through the real command host.
8@MainActor
9@Suite(.serialized)
10struct UserCommandWorkspaceTests {
11 static let manifest = """
12 api = 1
13
14 [[command]]
15 name = "search"
16 file = "ws.js"
17 function = "search"
18 workspace = true
19
20 [[command]]
21 name = "outline"
22 file = "ws.js"
23 function = "outline"
24 workspace = true
25
26 [[command]]
27 name = "agenda"
28 file = "ws.js"
29 function = "agenda"
30 workspace = true
31
32 [[command]]
33 name = "capture"
34 file = "ws.js"
35 function = "capture"
36 workspace = true
37
38 [[command]]
39 name = "buffer-only"
40 file = "ws.js"
41 function = "all"
42 """
43 /// Each command asks for its arguments and shows what the call gave, or its error.
44 static let module = """
45 async function show(org, call) {
46 try {
47 await org.message(JSON.stringify(await call()));
48 } catch (error) {
49 await org.message("error: " + error.message);
50 }
51 }
52 export const search = org => show(org, async () => org.search(await org.prompt("Query: ")));
53 export const outline = org => show(org, async () => org.outlineOf(await org.prompt("Path: ")));
54 export const agenda = org => show(org, async () => org.agenda(JSON.parse(await org.prompt("Span: "))));
55 export const capture = org => show(org, async () =>
56 org.capture(await org.prompt("Template: "), await org.prompt("Text: "), JSON.parse(await org.prompt("Fields: "))));
57 export async function all(org) {
58 const errors = [];
59 for (const call of [() => org.search("x"), () => org.outlineOf("todo.org"), () => org.agenda(), () => org.capture("t", "x")]) {
60 try { await call(); } catch (error) { errors.push(error.message); }
61 }
62 await org.message(errors.join(" | "));
63 }
64 """
65 static let todo = """
66 * Inbox
67 * Project
68 ** TODO Write report about milk
69 SCHEDULED: <2026-11-26 Thu 10:00>
70 Milk prices for the report.
71 * TODO Call Sam :phone:
72
73 """
74 static let current = "* Current\nbody\n"
75
76 let config: Folder
77 let notes: Folder
78 let outside: Folder
79 let path: String
80 let workspace: WorkspaceModel
81 let session: DocumentSession
82 let buffer: StateBuffer
83 var access: UserCommandWorkspace
84
85 init() async throws {
86 config = try Folder()
87 notes = try Folder()
88 outside = try Folder()
89 try config.write("commands.toml", Self.manifest)
90 try config.write("commands/ws.js", Self.module)
91 try notes.write("todo.org", Self.todo)
92 try notes.write("sub/deep.org", "#+TITLE: Deep\n* Top\n** Inner :x:\n:PROPERTIES:\n:KIND: deep\n:END:\n")
93 try notes.write("crypt.org", "* Bank :crypt:\n-----BEGIN PGP MESSAGE-----\n\nhQEMAciphertext\n-----END PGP MESSAGE-----\n")
94 try OpenPGP.encryptedMessage(Data("* Vault milk\nmilk secret\n".utf8), passphrase: "pw").write(to: notes.url.appendingPathComponent("vault.org.gpg"))
95 try notes.write("b.org", "* Plain\n")
96 try outside.write("secret.org", "* Outside secret\n")
97 try FileManager.default.createSymbolicLink(at: notes.url.appendingPathComponent("link.org"), withDestinationURL: outside.url.appendingPathComponent("secret.org"))
98 try FileManager.default.createSymbolicLink(at: notes.url.appendingPathComponent("inner.org"), withDestinationURL: notes.url.appendingPathComponent("sub/deep.org"))
99 path = try notes.write("a.org", Self.current).path
100 workspace = try WorkspaceModel(directory: nil)
101 try await workspace.addRoot(notes.url)
102 await workspace.refresh()
103 session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
104 session.saveMode = .explicit
105 session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
106 session.userCommands = UserCommands()
107 #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
108 session.open(path)
109 buffer = StateBuffer(try #require(session.document))
110 session.attach(buffer)
111 access = UserCommandWorkspace(workspace: workspace, clock: ClockModel(file: notes.url.appendingPathComponent("clock.json"), defaults: TestDefaults("user-command-workspace")))
112 access.templates = {
113 [
114 CaptureTemplate(key: "t", name: "Todo", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %i"),
115 CaptureTemplate(key: "e", name: "Errand", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %^{What} %^g\n%i"),
116 CaptureTemplate(key: "here", name: "Here", target: .file("a.org"), template: "* %i"),
117 ]
118 }
119 let now = try #require(ISO8601DateFormatter().date(from: "2026-11-26T09:00:00Z"))
120 access.now = { now }
121 access.calendar = Calendar(identifier: .gregorian)
122 access.calendar.timeZone = TimeZone(identifier: "UTC")!
123 }
124
125 /// Runs `name` in a.org with `answers` to its prompts, in order; what it showed.
126 func run(_ name: String, _ answers: [String] = [], workspace: Bool = true) async throws -> String {
127 let command = try #require(session.userCommands.command("user." + name))
128 let document = buffer.document
129 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [0..<0])
130 guard case .external(.userCommand(let request)) = command.run(in: context) else { throw CancellationError() }
131 var answers = answers
132 var shown: [String] = []
133 let message = await session.runUserCommand(request, context: context, file: "a.org", workspace: workspace ? access : nil, ask: { _, reply in
134 reply(answers.isEmpty ? nil : answers.removeFirst())
135 }, report: { shown.append($0) })
136 #expect(message == nil)
137 return shown.joined(separator: "\n")
138 }
139
140 func json(_ text: String) throws -> Any {
141 try JSONSerialization.jsonObject(with: Data(text.utf8))
142 }
143
144 @Test func searchesTheIndex() async throws {
145 let results = try #require(try json(try await run("search", ["milk report"])) as? [[String: Any]])
146 #expect(results.count == 1)
147 let found = try #require(results.first)
148 #expect(found["file"] as? String == "todo.org")
149 #expect(found["title"] as? String == "Write report about milk")
150 #expect(found["outline"] as? [String] == ["Project"])
151 #expect(found["start"] as? Int == (Self.todo as NSString).range(of: "** TODO").location)
152 #expect(found["heading"] as? Bool == true)
153 #expect((found["snippet"] as? String)?.contains("Milk prices") == true)
154 // The text before a file's first heading.
155 let deep = try #require(try json(try await run("search", ["Deep"])) as? [[String: Any]])
156 #expect(deep.contains { $0["file"] as? String == "sub/deep.org" && $0["heading"] as? Bool == false && $0["title"] as? String == "Deep" })
157 }
158
159 @Test func readsAnotherFilesOutline() async throws {
160 let headings = try #require(try json(try await run("outline", ["sub/deep.org"])) as? [[String: Any]])
161 #expect(headings.map { $0["title"] as? String } == ["Top", "Inner"])
162 #expect(headings[1]["level"] as? Int == 2)
163 #expect(headings[1]["tags"] as? [String] == ["x"])
164 #expect(headings[1]["properties"] as? [String: String] == ["KIND": "deep"])
165 // Absolute inside a folder, and a symlink to a file inside one.
166 let absolute = notes.url.appendingPathComponent("todo.org").path
167 #expect((try json(try await run("outline", [absolute])) as? [[String: Any]])?.count == 4)
168 #expect((try json(try await run("outline", ["inner.org"])) as? [[String: Any]])?.count == 2)
169 }
170
171 @Test func refusesFilesOutsideTheFolders() async throws {
172 #expect(try await run("outline", ["link.org"]) == "error: No file link.org in orgstar's folders.")
173 #expect(try await run("outline", ["../" + outside.url.lastPathComponent + "/secret.org"])
174 == "error: No file ../\(outside.url.lastPathComponent)/secret.org in orgstar's folders.")
175 let secret = outside.url.appendingPathComponent("secret.org").path
176 #expect(try await run("outline", [secret]) == "error: No file \(secret) in orgstar's folders.")
177 #expect(try await run("outline", ["/etc/hosts"]) == "error: No file /etc/hosts in orgstar's folders.")
178 #expect(try await run("outline", ["sub"]) == "error: No file sub in orgstar's folders.")
179 }
180
181 @Test func readsTheAgendaForASpan() async throws {
182 let entries = try #require(try json(try await run("agenda", [#"{"from": "2026-11-26", "to": "2026-11-27"}"#])) as? [[String: Any]])
183 let report = try #require(entries.first { $0["title"] as? String == "Write report about milk" })
184 #expect(report["date"] as? String == "2026-11-26")
185 #expect(report["time"] as? String == "10:00")
186 #expect(report["kind"] as? String == "scheduled")
187 #expect(report["file"] as? String == "todo.org")
188 #expect(report["todo"] as? String == "TODO")
189 // A span with nothing in it.
190 #expect((try json(try await run("agenda", [#"{"from": "2026-12-10"}"#])) as? [Any])?.isEmpty == true)
191 #expect(try await run("agenda", [#"{"from": "2026-11-27", "to": "2026-11-26"}"#]) == "error: org.agenda: to is before from.")
192 #expect(try await run("agenda", [#"{"from": "2026-02-30"}"#]) == "error: org.agenda: from must be a date as YYYY-MM-DD.")
193 #expect(try await run("agenda", [#"{"from": "2026-01-01", "to": "2027-06-01"}"#]) == "error: org.agenda: a span of at most 366 days.")
194 }
195
196 @Test func capturesThroughATemplate() async throws {
197 let shown = try json(try await run("capture", ["e", "for the weekend", #"{"What": "Buy bread", "Tags": "shop"}"#])) as? [String: String]
198 #expect(shown == ["template": "e", "file": "todo.org"])
199 let todo = try String(contentsOf: notes.url.appendingPathComponent("todo.org"), encoding: .utf8)
200 #expect(todo.hasPrefix("* Inbox\n** TODO Buy bread "))
201 #expect(todo.contains(" :shop:\nfor the weekend\n* Project\n"))
202 // The buffer the command ran in is as it was, with nothing to undo.
203 #expect(buffer.document.text == Self.current)
204 #expect(!buffer.document.canUndo)
205 }
206
207 @Test func refusesCapturesItCantFill() async throws {
208 #expect(try await run("capture", ["e", "x", "{}"]) == "error: Template \"e\" asks for What, Tags; give them in fields.")
209 #expect(try await run("capture", ["e", "x", #"{"What": "Milk"}"#]) == "error: Template \"e\" asks for Tags; give it in fields.")
210 #expect(try await run("capture", ["zz", "x", "null"]) == "error: No capture template \"zz\".")
211 #expect(try await run("capture", ["e", "x", #"{"What": 1}"#]) == "error: org.capture: field What must be a string.")
212 #expect(try await run("capture", ["here", "x", "null"]) == "error: org.capture can't file to the file the command runs in; return edits instead.")
213 #expect(try String(contentsOf: notes.url.appendingPathComponent("todo.org"), encoding: .utf8) == Self.todo)
214 #expect(buffer.document.text == Self.current)
215 }
216
217 @Test func refusedWithoutWorkspace() async throws {
218 let needs = { (name: String) in "org.\(name) needs workspace = true on the command in commands.toml." }
219 #expect(try await run("buffer-only") == ["search", "outlineOf", "agenda", "capture"].map(needs).joined(separator: " | "))
220 // Where the app gives no access, a command with workspace = true is told so.
221 #expect(try await run("search", ["milk"], workspace: false) == "error: org.search isn't available here.")
222 }
223
224 /// Text encrypted on disk is never returned: not from `.gpg` files, not from buffers
225 /// holding decrypted entries, and not as a snippet of an encrypted entry.
226 @Test func encryptedTextIsNotReturned() async throws {
227 #expect(try await run("outline", ["vault.org.gpg"]) == "error: vault.org.gpg is encrypted, so user commands can't read it.")
228 let milk = try #require(try json(try await run("search", ["milk"])) as? [[String: Any]])
229 #expect(!milk.contains { ($0["file"] as? String)?.hasSuffix(".gpg") == true })
230 let cipher = try #require(try json(try await run("search", ["hQEMAciphertext"])) as? [[String: Any]])
231 #expect(cipher.count == 1 && cipher.first?["title"] as? String == "Bank" && cipher.first?["snippet"] is NSNull)
232
233 // A buffer with an entry decrypted and edited: search and outlines read the file on disk.
234 session.encryptsTaggedEntries = true
235 let other = notes.url.appendingPathComponent("b.org")
236 session.open(other.path)
237 let secret = StateBuffer(try #require(session.document))
238 session.attach(secret)
239 try secret.update { try $0.apply([TextEdit(range: 8..<8, replacement: "* Bank :crypt:\nAccount zebra12345\n")], baseRevision: $0.revision) }
240 session.bufferChanged()
241 #expect(session.openTexts[other.path] == nil)
242 session.open(path)
243 #expect(session.path == path)
244 #expect((try json(try await run("search", ["zebra12345"])) as? [Any])?.isEmpty == true)
245 let outline = try #require(try json(try await run("outline", ["b.org"])) as? [[String: Any]])
246 #expect(outline.map { $0["title"] as? String } == ["Plain"])
247 }
248
249 /// Trust for workspace access is kept apart from trust for the buffer alone.
250 @Test func workspaceAccessAsksForTrustAgain() throws {
251 let modules = config.url.appendingPathComponent("commands")
252 let file = config.url.appendingPathComponent("trusted.json")
253 let trust = TrustStore(file: file)
254 var asked: [UserCommandTrust.Question] = []
255 var runs = 0
256 func check(_ command: UserCommand, _ answer: UserCommandTrust.Answer?, in store: TrustStore) {
257 UserCommandTrust.check(command, modules: modules, trust: store, ask: { question, reply in
258 asked.append(question)
259 reply(answer)
260 }, run: { runs += 1 }, refuse: { _ in })
261 }
262 let bufferOnly = UserCommand(name: "a", title: "A", file: "ws.js", function: "all")
263 let withWorkspace = UserCommand(name: "a", title: "A", file: "ws.js", function: "all", workspace: true)
264 check(bufferOnly, .always, in: trust)
265 check(bufferOnly, nil, in: trust)
266 #expect(runs == 2 && asked == [UserCommandTrust.Question(file: "commands/ws.js")])
267 // `workspace = true` added: asked again, saying what it can read.
268 check(withWorkspace, nil, in: trust)
269 #expect(runs == 2 && asked.last == UserCommandTrust.Question(file: "commands/ws.js", workspace: true))
270 check(withWorkspace, .always, in: trust)
271 #expect(runs == 3 && asked.count == 3)
272 // Kept on the device: both kinds of command run without asking, and the workspace
273 // trust survives the buffer-only one being given again.
274 let relaunched = TrustStore(file: file)
275 check(withWorkspace, nil, in: relaunched)
276 check(bufferOnly, nil, in: relaunched)
277 #expect(runs == 5 && asked.count == 3)
278 // A file trusted only for the buffer, in a fresh store, doesn't cover workspace access.
279 let fresh = TrustStore(file: config.url.appendingPathComponent("other.json"))
280 check(bufferOnly, .always, in: fresh)
281 check(withWorkspace, nil, in: fresh)
282 #expect(runs == 6 && asked.count == 5)
283 }
284}
Tests/OrgCoreTests/UserCommandTests.swift +20 · view
@@ -99,6 +99,26 @@ struct UserCommandManifestTests {
99 ]) 99 ])
100 } 100 }
101 101
102 @Test func readsWorkspaceAccess() throws {
103 let (commands, problems) = try parse("""
104 api = 1
105
106 [[command]]
107 name = "find"
108 file = "review.js"
109 function = "find"
110 workspace = true
111
112 [[command]]
113 name = "bad"
114 file = "review.js"
115 function = "bad"
116 workspace = "yes"
117 """)
118 #expect(commands == [UserCommand(name: "find", title: "find", file: "review.js", function: "find", workspace: true)])
119 #expect(problems == ["command bad: workspace must be true or false"])
120 }
121
102 @Test func needsAKnownAPI() throws { 122 @Test func needsAKnownAPI() throws {
103 let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n" 123 let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n"
104 #expect(try parse(command) == ([], ["missing api = 1"])) 124 #expect(try parse(command) == ([], ["missing api = 1"]))
docs/manual/guide/18-user-commands.org +61 −4 · view
@@ -30,6 +30,7 @@ file = "headings.js" # in commands/
30function = "upcaseTitle" # an exported function 30function = "upcaseTitle" # an exported function
31when = "heading" # optional; default: everywhere 31when = "heading" # optional; default: everywhere
32timeout = 5 # optional, seconds; default 2, at most 30 32timeout = 5 # optional, seconds; default 2, at most 30
33workspace = false # optional; true lets it read your folders and capture
33 34
34[[command]] 35[[command]]
35name = "weekly-review" 36name = "weekly-review"
@@ -47,6 +48,7 @@ function = "weeklyReview"
47| =function= | Yes | The name of a function the file exports. It may be =async=. | 48| =function= | Yes | The name of a function the file exports. It may be =async=. |
48| =when= | No | A context from [[file:03-keys.org::*Contexts][Contexts]] (=heading=, =table=, =item=, =region=, …). Where it doesn't hold, the palette and the Commands list leave the command out and its keys fall through. | 49| =when= | No | A context from [[file:03-keys.org::*Contexts][Contexts]] (=heading=, =table=, =item=, =region=, …). Where it doesn't hold, the palette and the Commands list leave the command out and its keys fall through. |
49| =timeout= | No | Seconds the command may run, 1 to 30; 2 when not given. Time spent waiting for your answer to a prompt doesn't count. | 50| =timeout= | No | Seconds the command may run, 1 to 30; 2 when not given. Time spent waiting for your answer to a prompt doesn't count. |
51| =workspace= | No | =true= lets the command search your folders, read other files' outlines and the agenda, and capture (see [[*Reading your folders and capturing][Reading your folders and capturing]]). Default =false=. |
50 52
51orgstar reads the file without running any code, so commands are listed and bindable before you have run them. It reloads the file, and the list of commands, when the file or anything in =commands/= changes; on iPhone and iPad it reloads when the synced folder changes. 53orgstar reads the file without running any code, so commands are listed and bindable before you have run them. It reloads the file, and the list of commands, when the file or anything in =commands/= changes; on iPhone and iPad it reloads when the synced folder changes.
52 54
@@ -55,6 +57,7 @@ Problems are reported like those of the other configuration files (see [[file:13
55- =commands.toml: command weekly-review: no file commands/review.js= 57- =commands.toml: command weekly-review: no file commands/review.js=
56- =commands.toml: command slow: timeout must be 1 to 30 seconds= 58- =commands.toml: command slow: timeout must be 1 to 30 seconds=
57- =commands.toml: command review: unknown context headline= 59- =commands.toml: command review: unknown context headline=
60- =commands.toml: command find: workspace must be true or false=
58- =commands.toml: api 2 needs a newer orgstar= (no command is registered) 61- =commands.toml: api 2 needs a newer orgstar= (no command is registered)
59- =commands.toml: missing api = 1= (no command is registered) 62- =commands.toml: missing api = 1= (no command is registered)
60- =commands.toml: commands/review.js isn't downloaded from iCloud yet= (iPhone and iPad; the download starts) 63- =commands.toml: commands/review.js isn't downloaded from iCloud yet= (iPhone and iPad; the download starts)
@@ -81,6 +84,10 @@ Every call returns a promise; use =await=. Offsets are UTF-16 code units, as Jav
81| =org.message(text)= | Shows =text= in the echo area while the command runs. | 84| =org.message(text)= | Shows =text= in the echo area while the command runs. |
82| =org.fail(text)= | Ends the command: nothing changes and =text= is shown. Use it as =return org.fail("…")=. | 85| =org.fail(text)= | Ends the command: nothing changes and =text= is shown. Use it as =return org.fail("…")=. |
83| =org.run(id)= | Runs one of Org's commands by id (=org.todo.cycle=) and gives the text and selection after it as ={text, selection}=. See [[*Running Org's commands][Running Org's commands]]. | 86| =org.run(id)= | Runs one of Org's commands by id (=org.todo.cycle=) and gives the text and selection after it as ={text, selection}=. See [[*Running Org's commands][Running Org's commands]]. |
87| =org.search(query)= | With =workspace = true=: headings and files in your folders that match =query=. See [[*Reading your folders and capturing][Reading your folders and capturing]]. |
88| =org.outlineOf(path)= | With =workspace = true=: the headings of another org file in your folders, as =org.outline()= gives them. |
89| =org.agenda({from, to})= | With =workspace = true=: the agenda's entries for a span of days. |
90| =org.capture(key, text, fields)= | With =workspace = true=: files =text= with a capture template. |
84| =org.version= | =1=. | 91| =org.version= | =1=. |
85 92
86A heading is an object with: 93A heading is an object with:
@@ -137,6 +144,47 @@ export async function startTask(org) {
137 - the editor's own commands, which aren't Org's: folding (=org.cycle=), movement and editing keys (=edit.*=), snippets and keyboard macros; 144 - the editor's own commands, which aren't Org's: folding (=org.cycle=), movement and editing keys (=edit.*=), snippets and keyboard macros;
138 - work Org does outside the text: running a code block (=org.babel.execute=, or =C-c C-c= on one), table formulas that need Emacs, following a link, tangling, editing a block apart, column view and the agenda. =org.run= throws with "/id/ needs work outside the text here …" instead of starting it, since its result would come back after the command had ended. 145 - work Org does outside the text: running a code block (=org.babel.execute=, or =C-c C-c= on one), table formulas that need Emacs, following a link, tangling, editing a block apart, column view and the agenda. =org.run= throws with "/id/ needs work outside the text here …" instead of starting it, since its result would come back after the command had ended.
139 146
147** Reading your folders and capturing
148
149A command with =workspace = true= in =commands.toml= can also read the files in your folders and capture to them. Without it, these calls throw "org.search needs workspace = true on the command in commands.toml." Allowing such a command asks a separate question (see [[*Trust][Trust]]). Capture is the only way a command writes to a file other than its own.
150
151| Call | Gives |
152|-----------------------------------+------------------------------------------------------------------------------------------------------------------|
153| =org.search(query)= | The best 50 matches of the sidebar's search: headings whose title or text have every word of =query= as the start of a word, and files whose text before the first heading does. Unsaved changes in open files are searched. |
154| =org.outlineOf(path)= | The headings of an org file (=.org= or =.org_archive=) in your folders, in order, as =org.outline()= describes them; offsets are in that file's text. =path= is relative to one of your folders (the first that has it) or absolute inside one. An open file is read as its buffer has it. |
155| =org.agenda({from, to})= | The agenda's entries from =from= to =to=, both =YYYY-MM-DD= and both included; =from= defaults to today and =to= to =from=. At most 366 days and 200 entries. |
156| =org.capture(key, text, fields)= | Files =text= with the template keyed =key= in =capture.toml= and gives ={template, file}=, =file= relative to its folder. |
157
158A search match is an object with:
159
160| Field | Value |
161|-----------+---------------------------------------------------------------------------------------------------------|
162| =file= | The file, relative to its folder (=notes/plan.org=). |
163| =title= | The heading's title, or for a match before the first heading the file's =#+TITLE= or name. |
164| =outline= | The titles of the headings above it, top first; =[]= for a top-level heading or the file. |
165| =start= | Where the heading starts in its file, as =org.heading()='s =start=; =0= for the file. |
166| =heading= | =false= for a match in the text before the file's first heading. |
167| =snippet= | The text around the match, or =null=. |
168
169Agenda entries have the shape of those the x-callback-url =agenda= action returns (see [[file:15-alongside-emacs.org::*agenda][agenda]]): =title=, =todo=, =priority=, =tags=, =category=, =file=, =status=, =date=, =time=, =end= and =kind=, those without a value left out, in the agenda's order with each day's overdue entries first. The agenda uses your agenda settings and files; calendar events and reminders are left out.
170
171=org.capture= files without the capture window, by the rules of the x-callback-url =capture= action (see [[file:15-alongside-emacs.org::*capture][capture]]): =fields= answers the template's prompts by their text (={What: "Milk", Tags: "shop"}= for =%^{What}= and =%^g=), and every prompt must have an answer, or nothing is filed and the call throws naming the missing ones. =%^C= and =%^L= insert nothing and =%c= is empty, since commands don't read the clipboard. Templates that make a Denote note or ask for a date tree's day are refused, and so is a template whose target is the file the command runs in: return =edits= for that. The entry is filed when the call returns, even if the command fails later, as a change of the target file alone; the undo history of the command's own file is unchanged.
172
173#+BEGIN_SRC js
174// commands.toml: workspace = true
175export async function followUp(org) {
176 const here = await org.heading()
177 if (!here) return org.fail("Not in an entry")
178 const elsewhere = (await org.search(here.title)).filter(m => m.start !== here.start)
179 const see = elsewhere.length ? ` (see ${elsewhere[0].file})` : ""
180 await org.capture("t", `Follow up: ${here.title}${see}`)
181 const today = await org.agenda()
182 return { message: `Captured; ${today.length} entries on today's agenda` }
183}
184#+END_SRC
185
186Text that is encrypted on disk is never returned. =org.search= leaves out =.gpg= files, searches open files with entries decrypted as they are on disk, and gives =null= as the snippet of a match in an encrypted entry. =org.outlineOf= refuses =.gpg= files and reads a file with entries decrypted from disk. The agenda reads such files from disk, as it always does.
187
140* Examples 188* Examples
141 189
142=commands/headings.js= upcases the current heading's title: 190=commands/headings.js= upcases the current heading's title:
@@ -203,12 +251,16 @@ It imports commands/lib/dates.js.
203They can read and change the file you run them in, and nothing else: no other files and no network. 251They can read and change the file you run them in, and nothing else: no other files and no network.
204#+END_EXAMPLE 252#+END_EXAMPLE
205 253
254For a command with =workspace = true=, the last line is "They can read and change the file you run them in, read every file in your folders and capture to them, but not use the network."
255
206The question names the file's full path under =commands/= and every module it imports, directly or through another module; the line about imports is left out when there are none. On the Mac the question is in the echo area, with the answers listed above it; on iPhone and iPad it is an alert. [[*Limits][Limits]] has the details of what a command can't reach. The answers are Run Once, Always and Don't Run: 256The question names the file's full path under =commands/= and every module it imports, directly or through another module; the line about imports is left out when there are none. On the Mac the question is in the echo area, with the answers listed above it; on iPhone and iPad it is an alert. [[*Limits][Limits]] has the details of what a command can't reach. The answers are Run Once, Always and Don't Run:
207 257
208- Run Once runs it this time and asks again next time. 258- Run Once runs it this time and asks again next time.
209- Always runs it and doesn't ask again while the file and every module it imports stay as they are. 259- Always runs it and doesn't ask again while the file and every module it imports stay as they are.
210- Don't Run, or cancelling, runs nothing. 260- Don't Run, or cancelling, runs nothing.
211 261
262Trust for =workspace = true= is kept apart from trust for the buffer alone. A file you allowed with Always for commands without it asks again the first time one of its commands has =workspace = true=, including when you add =workspace = true= to a command you have run before. Always for a command with it also covers the file's other commands.
263
212Any change to the file or to a module it imports asks again, including a change that arrives by sync from another device. Trust is kept on each device, in =trusted.json= in orgstar's data folder, not in the configuration folder, so a command synced from another device runs here only after you allow it here. Code blocks and Lisp table formulas use the same store (see [[file:11-code-blocks.org][Code blocks]]). 264Any change to the file or to a module it imports asks again, including a change that arrives by sync from another device. Trust is kept on each device, in =trusted.json= in orgstar's data folder, not in the configuration folder, so a command synced from another device runs here only after you allow it here. Code blocks and Lisp table formulas use the same store (see [[file:11-code-blocks.org][Code blocks]]).
213 265
214** Cancelling 266** Cancelling
@@ -219,8 +271,9 @@ Edit ▸ Cancel Running Task (=⌘.=, =app.babel.cancel=) stops a running comman
219 271
220- *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. 272- *Time.* A command that runs longer than its =timeout= (2 seconds by default, at most 30) is stopped with "/title/ didn't finish within /n/ s and was stopped." Time waiting for a prompt doesn't count.
221- *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh. 273- *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh.
222- *The buffer only.* A command reads and changes the buffer it runs in, nothing else: no files, no network (=fetch=, =XMLHttpRequest=, =WebSocket=, =importScripts= and the rest are removed), no other buffers, no clipboard reads, no notifications, Calendar or other system services. 274- *The buffer only.* A command reads and changes the buffer it runs in, nothing else: no files, no network (=fetch=, =XMLHttpRequest=, =WebSocket=, =importScripts= and the rest are removed), no other buffers, no clipboard reads, no notifications, Calendar or other system services. With =workspace = true= it can also read your folders through the calls in [[*Reading your folders and capturing][Reading your folders and capturing]] and capture to them, and nothing more: no files outside your folders (a symlink that leads out of them is refused) and still no network.
223- *Encrypted text.* Commands don't run in an encrypted file or in a buffer with entries decrypted that are encrypted on disk: "/file/ has decrypted entries, so user commands don't run in it." 275- *Encrypted text.* Commands don't run in an encrypted file or in a buffer with entries decrypted that are encrypted on disk: "/file/ has decrypted entries, so user commands don't run in it." The calls that read your folders never return text that is encrypted on disk.
276- *Time in calls.* Time the app spends answering a call (a prompt, a search, reading the agenda) doesn't count against the =timeout=.
224- *Keyboard macros* record a key bound to a user command with the answers to its prompts, and wait for the command to finish when they play (see [[file:03-keys.org::*Keyboard macros][Keyboard macros]]). 277- *Keyboard macros* record a key bound to a user command with the answers to its prompts, and wait for the command to finish when they play (see [[file:03-keys.org::*Keyboard macros][Keyboard macros]]).
225- *Startup.* When you have commands, the engine that runs them starts when an editor opens, so the first run doesn't wait for it. It stops after five minutes without a run. 278- *Startup.* When you have commands, the engine that runs them starts when an editor opens, so the first run doesn't wait for it. It stops after five minutes without a run.
226 279
@@ -232,8 +285,8 @@ What Emacs Lisp has that user commands don't:
232 285
233- Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read. 286- Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read.
234- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead. 287- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
235- The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=. Read headings with =org.heading()= and =org.outline()=, and write the text yourself or run Org's commands with =org.run=. 288- The Org API: =org-element-*=, =org-entry-put=. Read headings with =org.heading()= and =org.outline()=, and write the text yourself or run Org's commands with =org.run=. Over several files, a command with =workspace = true= reads with =org.search= and =org.outlineOf= and writes only with =org.capture=.
236- Other buffers and files, =find-file=, =with-temp-buffer=, capture from a command. 289- Other buffers, =find-file= and =with-temp-buffer=; changes to other files except by capture.
237- Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables. 290- Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables.
238- =interactive= codes other than the prompts above; =C-u= prefix arguments. 291- =interactive= codes other than the prompts above; =C-u= prefix arguments.
239- Timers, processes and shell commands. 292- Timers, processes and shell commands.
@@ -269,4 +322,8 @@ What Emacs Lisp has that user commands don't:
269| =(org-promote-subtree)=, =(org-demote-subtree)= | =await org.run("org.subtree.promote")=, =org.run("org.subtree.demote")= | 322| =(org-promote-subtree)=, =(org-demote-subtree)= | =await org.run("org.subtree.promote")=, =org.run("org.subtree.demote")= |
270| =(org-toggle-checkbox)= | =await org.run("org.checkbox.toggle")= | 323| =(org-toggle-checkbox)= | =await org.run("org.checkbox.toggle")= |
271| =(save-buffer)= | =await org.run("app.save")= | 324| =(save-buffer)= | =await org.run("app.save")= |
325| =(org-ql-select (org-agenda-files) '(regexp "milk"))= | =await org.search("milk")= (=workspace = true=) |
326| =(org-map-entries … nil 'agenda)= over files | =await org.outlineOf(file)= for each file (=workspace = true=) |
327| =(org-agenda-get-day-entries file date)=, =(org-agenda-list)= | =await org.agenda({from, to})= (=workspace = true=) |
328| =(org-capture-string "Milk" "t")=, =(org-capture nil "t")= | =await org.capture("t", "Milk", {…})= (=workspace = true=) |
272| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= | 329| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= |
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form