User commands: commands.toml, API version 1 and trust !527

merged merged by cmc on 2026-11-27 09:07 UTC · krz/orgstar:245-user-commands into main

25 files changed, +1989 −28

Layout: unified · split

Changed files (25)
Sources/OrgApp/CommandHost.swift +29 −9 · view
@@ -69,9 +69,10 @@ public final class CommandHost {
6969 }
7070
7171 /// Calls `function` exported by `module`, a path in `commands/`, with the JSON `context` and a
72 /// function the command calls the app with, and returns its result as JSON. `timeout` is at
73 /// most `maximumTimeout`.
74 public func run(module: String, function: String, context: String, timeout: Duration = defaultTimeout) async throws -> String {
72 /// function the command calls the app with, and returns its result as JSON. With `api`, the
73 /// function gets that version's `org` object instead, whose calls reach `calls`. `timeout`
74 /// is at most `maximumTimeout`.
75 public func run(module: String, function: String, context: String, timeout: Duration = defaultTimeout, api: Int? = nil) async throws -> String {
7576 guard Files.relative(module) != nil else { throw Failure.script("No module \(module) in commands/.") }
7677 let limit = min(timeout, Self.maximumTimeout)
7778 idleTask?.cancel()
@@ -97,8 +98,8 @@ public final class CommandHost {
9798 Task { @MainActor in
9899 do {
99100 let reply = try await engine.webView?.callAsyncJavaScript(
100 "return await run(id, module, name, context);",
101 arguments: ["id": id, "module": module, "name": function, "context": context],
101 "return await run(id, module, name, context, api);",
102 arguments: ["id": id, "module": module, "name": function, "context": context, "api": api ?? 0],
102103 contentWorld: .page
103104 )
104105 run.end(.success(reply as? String ?? ""))
@@ -365,7 +366,7 @@ public final class CommandHost {
365366 run.worker.terminate();
366367 run.resolve(JSON.stringify(reply));
367368 }
368 function run(id, module, name, context) {
369 function run(id, module, name, context, api) {
369370 prepare();
370371 const worker = ready;
371372 ready = null;
@@ -384,14 +385,15 @@ public final class CommandHost {
384385 if (runs.has(id)) worker.postMessage(reply);
385386 };
386387 worker.onerror = e => { e.preventDefault(); finish(id, { error: e.message || "The command didn't start." }); };
387 worker.postMessage({ module, name, context });
388 worker.postMessage({ module, name, context, api });
388389 });
389390 }
390391 function stop(id) { finish(id, {}); }
391392 """
392393
393394 /// Removes the ways out of the worker, then waits for a command: imports its module, calls
394 /// the function with the context and `call`, and posts the result as JSON.
395 /// the function with the context and `call`, or with `org` for API version 1, and posts the
396 /// result as JSON.
395397 static let worker = """
396398 const post = self.postMessage.bind(self);
397399 for (const name of ["fetch", "XMLHttpRequest", "WebSocket", "EventSource", "importScripts", "indexedDB", "caches", "Worker", "SharedWorker"]) {
@@ -406,6 +408,24 @@ public final class CommandHost {
406408 post({ kind: "call", seq, name, value });
407409 });
408410 }
411 function api1() {
412 const fail = async text => {
413 await call("fail", String(text));
414 throw new Error(String(text));
415 };
416 return Object.freeze({
417 version: 1,
418 text: () => call("text", null),
419 selection: () => call("selection", null),
420 heading: at => call("heading", at ?? null),
421 outline: () => call("outline", null),
422 file: () => call("file", null),
423 settings: () => call("settings", null),
424 prompt: options => call("prompt", typeof options === "string" ? { message: options } : options ?? {}),
425 message: text => call("message", String(text)),
426 fail,
427 });
428 }
409429 self.onmessage = async e => {
410430 const m = e.data;
411431 if (m.seq !== undefined) {
@@ -417,7 +437,7 @@ public final class CommandHost {
417437 try {
418438 const module = await import("./commands/" + m.module);
419439 if (typeof module[m.name] !== "function") throw new Error(`${m.module} exports no function ${m.name}.`);
420 const value = await module[m.name](JSON.parse(m.context), call);
440 const value = await module[m.name](...(m.api === 1 ? [api1()] : [JSON.parse(m.context), call]));
421441 post({ result: JSON.stringify(value) ?? "null" });
422442 } catch (error) {
423443 post({ error: String(error && error.message || error) });
Sources/OrgApp/ConfigSync.swift +14 −2 · view
@@ -29,6 +29,7 @@ public final class ConfigSync {
2929 @ObservationIgnored private var themeProblems: [String] = []
3030 @ObservationIgnored private var macroProblems: [String] = []
3131 @ObservationIgnored private var snippetProblems: [String] = []
32 @ObservationIgnored private var commandProblems: [String] = []
3233 /// Why the file couldn't be read or written, the last time a setting was to go into it.
3334 @ObservationIgnored private var fileProblem: String?
3435 @ObservationIgnored private var applying = false
@@ -69,6 +70,7 @@ public final class ConfigSync {
6970 }
7071 loadMacros()
7172 readSnippets()
73 loadCommands()
7274 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
7375 MainActor.assumeIsolated { self?.writeBack() }
7476 }
@@ -95,8 +97,11 @@ public final class ConfigSync {
9597 if self.isThemeFile(file) { self.readTheme() }
9698 if name == NamedMacros.fileName { self.loadMacros() }
9799 if name == Snippets.fileName { self.readSnippets() }
100 // A module added or removed changes which commands load.
101 let inCommands = file.path.hasPrefix(directory.path + "/" + UserCommands.folderName + "/")
102 if name == UserCommands.fileName || inCommands { self.loadCommands() }
98103 self.serial += 1
99 self.changedFile = (name, self.serial)
104 self.changedFile = (inCommands ? UserCommands.fileName : name, self.serial)
100105 }
101106 }
102107 }
@@ -116,6 +121,7 @@ public final class ConfigSync {
116121 themeProblems = []
117122 macroProblems = []
118123 snippetProblems = []
124 commandProblems = []
119125 fileProblem = nil
120126 self.url = url
121127 start(watch: watches)
@@ -142,6 +148,12 @@ public final class ConfigSync {
142148 updateProblems()
143149 }
144150
151 /// `commands.toml`, beside the file, into the user commands.
152 private func loadCommands() {
153 commandProblems = UserCommandFile.load(folder: url.deletingLastPathComponent())
154 updateProblems()
155 }
156
145157 /// `theme-file`, relative to the configuration folder.
146158 private var themeFile: URL? {
147159 guard let name = defaults.string(forKey: "themeFile"), !name.isEmpty else { return nil }
@@ -174,7 +186,7 @@ public final class ConfigSync {
174186 }
175187
176188 private func updateProblems() {
177 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems + macroProblems + snippetProblems
189 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems + macroProblems + snippetProblems + commandProblems
178190 if all != problems { problems = all }
179191 }
180192
Sources/OrgApp/DocumentSession.swift +130 · view
@@ -482,6 +482,10 @@ public final class DocumentSession {
482482 history.removeAll { $0 == entry.path }
483483 history.insert(entry.path, at: 0)
484484 refresh(pane)
485 // A worker ready ahead of the first user command run in this buffer.
486 #if canImport(WebKit)
487 if !userCommands.all.isEmpty { userCommandHost()?.prepare() }
488 #endif
485489 }
486490
487491 /// The buffer before or after the focused one, wrapping, in the focused pane.
@@ -1465,6 +1469,132 @@ public final class DocumentSession {
14651469 babelTask?.cancel()
14661470 }
14671471
1472 // MARK: - User commands
1473
1474 /// The commands of `commands.toml`; their folder is where the host loads modules from.
1475 @ObservationIgnored public var userCommands = UserCommands.shared
1476 #if canImport(WebKit)
1477 @ObservationIgnored private var commandHost: CommandHost?
1478
1479 /// The host for the commands' folder, made again when the folder changed.
1480 func userCommandHost() -> CommandHost? {
1481 guard let folder = userCommands.folder else { return nil }
1482 if commandHost?.folder != folder {
1483 commandHost?.unload()
1484 commandHost = CommandHost(folder: folder)
1485 }
1486 return commandHost
1487 }
1488 #endif
1489 @ObservationIgnored private var userCommandTask: Task<String?, Never>?
1490 public private(set) var isRunningUserCommand = false
1491
1492 /// Runs a user command on the focused buffer in the background, with `context` the editor's
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`.
1495 public func startUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?,
1496 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
1497 report: @escaping @MainActor (String) -> Void) {
1498 userCommandTask?.cancel()
1499 isRunningUserCommand = true
1500 let task = Task { await runUserCommand(request, context: context, file: file, ask: ask, report: report) }
1501 userCommandTask = task
1502 Task {
1503 let message = await task.value
1504 if userCommandTask == task {
1505 userCommandTask = nil
1506 isRunningUserCommand = false
1507 }
1508 if let message { report(message) }
1509 }
1510 }
1511
1512 /// Stops the running user command; nothing it returns is applied.
1513 public func cancelUserCommand() {
1514 userCommandTask?.cancel()
1515 }
1516
1517 /// Why a user command doesn't run in `path`'s buffer: it's an encrypted file or holds
1518 /// decrypted entries, which a command could copy elsewhere in the file. Nil when it runs.
1519 public func refusesUserCommand(_ path: String) -> String? {
1520 let name = (path as NSString).lastPathComponent
1521 guard Self.isEncryptedFile(path) || entry(path).map({ crypt.isPrivate($0.buffer.document.text, for: $0.path) }) == true else { return nil }
1522 return String(localized: "\(name) has decrypted entries, so user commands don't run in it.", comment: "A user command refused in a buffer holding decrypted text")
1523 }
1524
1525 /// Runs `request` in the focused buffer and applies what it returns as one change at the
1526 /// request's revision. The message to show; nil when the command's own messages were shown.
1527 func runUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?,
1528 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
1529 report: @escaping @MainActor (String) -> Void) async -> String? {
1530 let command = request.command
1531 guard let path, let entry = entry(path) else { return "No file is open." }
1532 if let refusal = refusesUserCommand(path) { return refusal }
1533 guard entry.buffer.document.revision == request.revision, context.revision == request.revision else { return "The file changed; try again." }
1534 #if canImport(WebKit)
1535 guard let host = userCommandHost() else { return "No \(UserCommands.fileName)." }
1536 final class State {
1537 var failure: String?
1538 var quit = false
1539 }
1540 let state = State()
1541 let context = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection,
1542 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags)
1543 host.calls = { name, value in
1544 if let answer = UserCommandAPI.answer(name, value, context: context, file: file) { return answer }
1545 switch name {
1546 case "prompt":
1547 let prompt = UserCommandAPI.prompt(value)
1548 return try await withCheckedThrowingContinuation { continuation in
1549 ask(prompt) { answer in
1550 guard let answer else {
1551 state.quit = true
1552 return continuation.resume(throwing: CommandHost.Failure.script("Quit"))
1553 }
1554 continuation.resume(returning: UserCommandAPI.answer(answer, to: prompt, now: Date(), calendar: context.calendar))
1555 }
1556 }
1557 case "message":
1558 report(value as? String ?? "")
1559 return NSNull()
1560 case "fail":
1561 state.failure = value as? String ?? ""
1562 return NSNull()
1563 default:
1564 throw CommandHost.Failure.script("org.\(name) isn't in API version \(UserCommands.apiVersion).")
1565 }
1566 }
1567 let json: String
1568 do {
1569 json = try await host.run(module: command.file, function: command.function, context: "null",
1570 timeout: .seconds(command.timeout), api: UserCommands.apiVersion)
1571 } catch let CommandHost.Failure.timedOut(limit) {
1572 let seconds = Int(limit.components.seconds)
1573 return String(localized: "\(command.title) didn't finish within \(seconds) s and was stopped.", comment: "A user command passed its time limit")
1574 } catch CommandHost.Failure.script(let message) {
1575 if let failure = state.failure { return failure }
1576 return state.quit ? "Quit" : "\(command.title): \(message)"
1577 } catch CommandHost.Failure.stopped {
1578 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")
1579 } catch {
1580 return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task")
1581 }
1582 if let failure = state.failure { return failure }
1583 guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") }
1584 switch UserCommandAPI.result(json, in: context) {
1585 case .failure(let problem):
1586 return "\(command.title): \(problem.message)"
1587 case .success(let result):
1588 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the command finished." }
1589 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1590 if !result.edits.isEmpty { changed(entry) }
1591 return nil
1592 }
1593 #else
1594 return "User commands aren't available here."
1595 #endif
1596 }
1597
14681598 // MARK: - Locations
14691599
14701600 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
Sources/OrgApp/EmacsImport.swift +7 · view
@@ -190,6 +190,8 @@ public struct EmacsImport: Sendable {
190190 var addedCommands: [(entry: Sexp, source: String)] = []
191191 var usesEvil = false
192192 var order = 0
193 /// Functions the configuration defines itself (`defun`).
194 var defuns: Set<String> = []
193195
194196 mutating func assign(_ name: String, _ value: Sexp, _ source: String, priority: Int, deferred: Bool) {
195197 assignments.append(Assignment(name: name, value: value, source: source, rank: priority * 2 + (deferred ? 1 : 0)))
@@ -253,6 +255,7 @@ public struct EmacsImport: Sendable {
253255 case "defun", "defun!", "add-hook!":
254256 // Doom sets org's defaults in the functions its module runs when org loads.
255257 if doom, head == "defun" { body(args.dropFirst(2), deferred: true) }
258 if !doom, head != "add-hook!", let name = args.first?.symbol { defuns.insert(name) }
256259 case "doom!":
257260 usesEvil = args.contains { $0.symbol == "evil" || $0.head == "evil" }
258261 case "map!":
@@ -505,6 +508,10 @@ public struct EmacsImport: Sendable {
505508 unsupported.append(Note(id: id(), name: binding.keys, reason: "bound to code, not a command", source: binding.source))
506509 continue
507510 }
511 if Self.commands[commandName] == nil, scanner.defuns.contains(commandName) {
512 unsupported.append(Note(id: id(), name: "\(binding.keys) → \(commandName)", reason: "your own function; write it as a user command in commands.toml", source: binding.source))
513 continue
514 }
508515 guard let command = Self.commands[commandName] else {
509516 unsupported.append(Note(id: id(), name: "\(binding.keys) → \(commandName)", reason: "orgstar has no such command", source: binding.source))
510517 continue
Sources/OrgApp/UserCommandFile.swift added +145 · view
@@ -0,0 +1,145 @@
1import Foundation
2import OrgCore
3
4/// `commands.toml` in the configuration folder and the modules in `commands/` beside it.
5public enum UserCommandFile {
6 /// Reads `commands.toml` in `folder` into `store`, without running anything. The problems
7 /// found, each starting with the file's name; a missing file is none. A module iCloud hasn't
8 /// downloaded is reported and its download started; its command is kept.
9 @discardableResult
10 public static func load(into store: UserCommands = .shared, folder: URL, read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }) -> [String] {
11 let modules = folder.appendingPathComponent(UserCommands.folderName)
12 guard let text = read(folder.appendingPathComponent(UserCommands.fileName)) else {
13 store.replace([], folder: nil)
14 return []
15 }
16 var problems: [String] = []
17 var commands: [UserCommand] = []
18 do {
19 commands = try UserCommands.parse(text, problems: &problems) { path in
20 FileManager.default.fileExists(atPath: modules.appendingPathComponent(path).path) || placeholder(modules.appendingPathComponent(path)) != nil
21 }
22 } catch {
23 problems.append("\(error)")
24 }
25 for file in Set(commands.map(\.file)).sorted() where needsDownload(modules.appendingPathComponent(file)) {
26 problems.append("\(UserCommands.folderName)/\(file) isn't downloaded from iCloud yet")
27 }
28 store.replace(commands, folder: commands.isEmpty ? nil : modules)
29 return problems.map { "\(UserCommands.fileName): \($0)" }
30 }
31
32 /// The `.name.icloud` file iCloud leaves for `url` until it is downloaded, when there is one.
33 static func placeholder(_ url: URL) -> URL? {
34 let placeholder = url.deletingLastPathComponent().appendingPathComponent("." + url.lastPathComponent + ".icloud")
35 return FileManager.default.fileExists(atPath: placeholder.path) ? placeholder : nil
36 }
37
38 /// Whether `url` is in iCloud and not downloaded; if so its download is started.
39 static func needsDownload(_ url: URL) -> Bool {
40 let values = try? url.resourceValues(forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey])
41 let missing = placeholder(url) != nil
42 || values?.isUbiquitousItem == true && values?.ubiquitousItemDownloadingStatus.map { $0 != .current } == true
43 if missing { try? FileManager.default.startDownloadingUbiquitousItem(at: url) }
44 return missing
45 }
46
47 /// `path` relative to the folder of `roots` it's in, for `org.file()`; its name when it's
48 /// in none.
49 public static func relativePath(_ path: String, roots: [String]) -> String {
50 let root = roots.filter { path.hasPrefix($0.hasSuffix("/") ? $0 : $0 + "/") }.max { $0.count < $1.count }
51 guard let root else { return (path as NSString).lastPathComponent }
52 return String(path.dropFirst(root.count).drop { $0 == "/" })
53 }
54
55 // MARK: - Trust
56
57 /// The text trust is kept for: `file` and every module it imports, each under its path, in
58 /// path order. Nil when `file` can't be read.
59 @MainActor
60 public static func trustedText(_ file: String, modules: URL) -> String? {
61 var seen: [String: String] = [:]
62 var pending = [file]
63 while let path = pending.popLast() {
64 guard seen[path] == nil else { continue }
65 #if canImport(WebKit)
66 let data = CommandHost.Files.file(path, in: modules)
67 #else
68 let data = FileManager.default.contents(atPath: modules.appendingPathComponent(path).path)
69 #endif
70 guard let data, let text = String(data: data, encoding: .utf8) else {
71 if path == file { return nil }
72 seen[path] = "(missing)"
73 continue
74 }
75 seen[path] = text
76 pending += imports(text, from: path)
77 }
78 return seen.keys.sorted().map { "// \($0)\n\(seen[$0]!)" }.joined(separator: "\n")
79 }
80
81 private static let importPatterns = [
82 #"\b(?:import|export)\s[^;'"]*?\bfrom\s*['"]([^'"\n]+)['"]"#,
83 #"\bimport\s*['"]([^'"\n]+)['"]"#,
84 #"\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)"#,
85 ].map { try! NSRegularExpression(pattern: $0) }
86
87 /// The modules `text`, at `path` in `commands/`, imports by relative path, as paths in
88 /// `commands/`; imports that leave the folder are left out, since they can't load.
89 static func imports(_ text: String, from path: String) -> [String] {
90 let ns = text as NSString
91 var result: [String] = []
92 for pattern in importPatterns {
93 for match in pattern.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
94 let specifier = ns.substring(with: match.range(at: 1))
95 guard specifier.hasPrefix("./") || specifier.hasPrefix("../") else { continue }
96 var parts = path.split(separator: "/").dropLast().map(String.init)
97 var inside = true
98 for part in specifier.split(separator: "/") {
99 switch part {
100 case ".": continue
101 case "..": if parts.popLast() == nil { inside = false }
102 default: parts.append(String(part))
103 }
104 }
105 let resolved = parts.joined(separator: "/")
106 if inside, UserCommands.isModulePath(resolved) { result.append(resolved) }
107 }
108 }
109 return result
110 }
111}
112
113/// The question before a command from a file this device hasn't trusted runs.
114@MainActor
115public enum UserCommandTrust {
116 static var runOnce: String { String(localized: "Run Once", comment: "Answer to the question before a user command runs") }
117 static var always: String { String(localized: "Always", comment: "Answer to the question before a user command runs") }
118 static var dontRun: String { String(localized: "Don't Run", comment: "Answer to the question before a user command runs") }
119
120 /// Runs `run` at once when the command's file and its imports are trusted, else asks: Run
121 /// Once runs it, Always trusts the files as they are now and runs it, anything else says
122 /// why nothing ran through `refuse`.
123 public static func check(_ command: UserCommand, modules: URL, trust: TrustStore,
124 ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
125 run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
126 guard let text = UserCommandFile.trustedText(command.file, modules: modules) else {
127 return refuse("No file \(UserCommands.folderName)/\(command.file)")
128 }
129 let path = modules.appendingPathComponent(command.file).path
130 if trust.isTrusted(path: path, content: text) { return run() }
131 let choices = [runOnce, always, dontRun]
132 let file = "\(UserCommands.folderName)/\(command.file)"
133 let message = String(localized: "Run commands from \(file)?",
134 comment: "Asked before a user command from a file not yet trusted on this device runs")
135 ask(Prompt(key: "confirm", message: message, choices: choices)) { answer in
136 switch answer {
137 case runOnce: run()
138 case always:
139 trust.trust(path: path, content: text)
140 run()
141 default: refuse(String(localized: "Not run"))
142 }
143 }
144 }
145}
Sources/OrgCore/Commands/Command.swift +2 · view
@@ -324,6 +324,8 @@ public enum ExternalRequest: Sendable, Equatable {
324324 case agenda(start: Int, days: Int)
325325 /// Write source blocks to their files (`org-babel-tangle`); the app knows the file's path.
326326 case tangle(Tangle.Scope)
327 /// Run a user command (`UserCommand`); its edits come back to apply at the request's revision.
328 case userCommand(UserCommandRequest)
327329}
328330
329331/// A named operation. Keys, menus, the palette and touch controls all run commands.
Sources/OrgCore/Commands/UserCommandAPI.swift added +208 · view
@@ -0,0 +1,208 @@
1import Foundation
2
3/// Version 1 of the API user commands call (`org.text()`, `org.heading()`, …) and of the value
4/// they return. Answers are JSON values (`String`, `Int`, `Bool`, `NSNull`, arrays and
5/// dictionaries of them) computed from the context the command started with; offsets are UTF-16,
6/// as JavaScript strings count them.
7public enum UserCommandAPI {
8 /// The answer to a call that reads the buffer: `text`, `selection`, `heading`, `outline`,
9 /// `file` or `settings`; nil for any other name. `file` is the file's path relative to its
10 /// folder.
11 public static func answer(_ name: String, _ value: Any, context: EditContext, file: String?) -> Any? {
12 switch name {
13 case "text": return context.text
14 case "selection": return context.selection.map(range)
15 case "heading":
16 let at = (value as? NSNumber).flatMap { integer($0) } ?? context.caret
17 let model = DocumentModel(tree: context.tree)
18 return heading(at: at, model: model, context: context).map { describe($0, model: model, context: context) } ?? NSNull()
19 case "outline":
20 let model = DocumentModel(tree: context.tree)
21 return model.headings.indices.map { describe($0, model: model, context: context) }
22 case "file": return file ?? NSNull()
23 case "settings": return settings(context)
24 default: return nil
25 }
26 }
27
28 static func range(_ range: Range<Int>) -> [String: Any] {
29 ["from": range.lowerBound, "to": range.upperBound]
30 }
31
32 /// The innermost heading whose subtree holds `offset`.
33 static func heading(at offset: Int, model: DocumentModel, context: EditContext) -> Int? {
34 let length = context.text.utf16.count
35 return model.headings.indices.last { index in
36 let section = model.headings[index].sectionRange
37 return section.contains(offset) || (offset == section.upperBound && offset == length)
38 }
39 }
40
41 static func describe(_ index: Int, model: DocumentModel, context: EditContext) -> [String: Any] {
42 let info = model.headings[index]
43 let text = context.text as NSString
44 var lineEnd = info.headingRange.upperBound
45 if lineEnd > info.headingRange.lowerBound, text.character(at: lineEnd - 1) == 0x0A { lineEnd -= 1 }
46 var node = context.tree.root
47 while node.kind != .heading, let child = node.child(containing: info.headingRange.lowerBound) { node = child }
48 let title = node.kind == .heading ? node.firstChild(.title)?.range : nil
49 var properties: [String: Any] = [:]
50 for property in info.properties { properties[property.key] = property.value }
51 var described: [String: Any] = [
52 "level": info.level,
53 "keyword": info.todo ?? NSNull(),
54 "done": info.isDone,
55 "priority": info.priority ?? NSNull(),
56 "title": info.title,
57 "tags": info.localTags,
58 "start": info.sectionRange.lowerBound,
59 "end": info.sectionRange.upperBound,
60 "titleStart": title?.lowerBound ?? lineEnd,
61 "titleEnd": title?.upperBound ?? lineEnd,
62 "properties": properties,
63 ]
64 let planning = Self.planning(text.substring(with: NSRange(location: info.headingRange.upperBound, length: max(0, nextLineEnd(after: info.headingRange.upperBound, in: text) - info.headingRange.upperBound))))
65 for kind in ["scheduled", "deadline", "closed"] { described[kind] = planning[kind] ?? NSNull() }
66 return described
67 }
68
69 static func nextLineEnd(after offset: Int, in text: NSString) -> Int {
70 guard offset < text.length else { return offset }
71 let line = text.lineRange(for: NSRange(location: offset, length: 0))
72 return NSMaxRange(line)
73 }
74
75 private static let planningPattern = try! NSRegularExpression(pattern: #"\b(SCHEDULED|DEADLINE|CLOSED):\s*([<\[][^>\]\n]*[>\]])"#)
76
77 /// The timestamps of a planning line, by lowercased keyword; empty for any other line.
78 static func planning(_ line: String) -> [String: String] {
79 guard line.trimmingCharacters(in: .whitespaces).range(of: #"^(SCHEDULED|DEADLINE|CLOSED):"#, options: .regularExpression) != nil else { return [:] }
80 var result: [String: String] = [:]
81 let ns = line as NSString
82 for match in planningPattern.matches(in: line, range: NSRange(location: 0, length: ns.length)) {
83 result[ns.substring(with: match.range(at: 1)).lowercased()] = ns.substring(with: match.range(at: 2))
84 }
85 return result
86 }
87
88 static func settings(_ context: EditContext) -> [String: Any] {
89 let settings = context.tree.settings
90 return [
91 "todoKeywords": settings.todoSequences.flatMap { $0.active.map(\.name) },
92 "doneKeywords": settings.todoSequences.flatMap { $0.done.map(\.name) },
93 "priorities": ["highest": settings.priorities.highest, "lowest": settings.priorities.lowest, "default": settings.priorities.default],
94 "fileTags": DocumentModel(tree: context.tree).fileTags,
95 "tags": context.knownTags(),
96 "fillColumn": context.options.fillColumn,
97 "tagsColumn": context.options.tagsColumn,
98 ]
99 }
100
101 // MARK: - Results
102
103 /// What a command returned, as JSON, read into a result for the context it ran in: `edits`
104 /// (`{from, to, text}` in the text it was given, non-overlapping), `selection` (`{from, to}`,
105 /// a list of them or an offset, in the text after the edits), `message` and `copy`. Null is
106 /// no change. A message saying what is wrong when the value can't be used.
107 public static func result(_ json: String, in context: EditContext) -> Result<EditResult, Problem> {
108 guard let value = try? JSONSerialization.jsonObject(with: Data(json.utf8), options: .fragmentsAllowed) else {
109 return .failure(Problem("returned something that isn't JSON"))
110 }
111 if value is NSNull { return .success(EditResult(baseRevision: context.revision, edits: [])) }
112 guard let object = value as? [String: Any] else { return .failure(Problem("returned something other than an object")) }
113 if let key = object.keys.sorted().first(where: { !["edits", "selection", "message", "copy"].contains($0) }) {
114 return .failure(Problem("returned an unknown key \(key)"))
115 }
116 let text = context.text as NSString
117 var edits: [TextEdit] = []
118 if let raw = object["edits"], !(raw is NSNull) {
119 guard let list = raw as? [Any] else { return .failure(Problem("edits must be a list")) }
120 for (number, item) in zip(1..., list) {
121 guard let edit = item as? [String: Any], let from = (edit["from"] as? NSNumber).flatMap(integer) else {
122 return .failure(Problem("edit \(number) needs a from offset"))
123 }
124 let to = edit["to"].map { ($0 as? NSNumber).flatMap(integer) } ?? from
125 guard let to else { return .failure(Problem("edit \(number) has a to that isn't an offset")) }
126 let replacement = edit["text"] ?? ""
127 guard let replacement = replacement as? String else { return .failure(Problem("edit \(number) has a text that isn't a string")) }
128 guard 0 <= from, from <= to, to <= text.length else { return .failure(Problem("edit \(number) is outside the text")) }
129 guard !splits(from, text), !splits(to, text) else { return .failure(Problem("edit \(number) splits a character")) }
130 edits.append(TextEdit(range: from..<to, replacement: replacement))
131 }
132 }
133 let sorted = edits.enumerated().sorted { ($0.element.range.lowerBound, $0.offset) < ($1.element.range.lowerBound, $1.offset) }.map(\.element)
134 for (a, b) in zip(sorted, sorted.dropFirst()) where b.range.lowerBound < a.range.upperBound || b.range.lowerBound == a.range.lowerBound {
135 return .failure(Problem("edits overlap"))
136 }
137 let length = text.length + sorted.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
138 var selection: [Range<Int>]?
139 if let raw = object["selection"], !(raw is NSNull) {
140 let items: [Any] = (raw as? [Any]) ?? [raw]
141 var ranges: [Range<Int>] = []
142 for item in items {
143 let bounds: (Int, Int)?
144 if let offset = (item as? NSNumber).flatMap(integer) {
145 bounds = (offset, offset)
146 } else if let range = item as? [String: Any], let from = (range["from"] as? NSNumber).flatMap(integer) {
147 bounds = range["to"].map { ($0 as? NSNumber).flatMap(integer).map { (from, $0) } } ?? (from, from)
148 } else {
149 bounds = nil
150 }
151 guard let (from, to) = bounds, 0 <= min(from, to), max(from, to) <= length else {
152 return .failure(Problem("selection is outside the text"))
153 }
154 ranges.append(min(from, to)..<max(from, to))
155 }
156 if !ranges.isEmpty { selection = ranges }
157 }
158 var effects: [Effect] = []
159 for key in ["message", "copy"] {
160 guard let raw = object[key], !(raw is NSNull) else { continue }
161 guard let string = raw as? String else { return .failure(Problem("\(key) must be a string")) }
162 effects.append(key == "message" ? .message(string) : .copy(string))
163 }
164 return .success(EditResult(baseRevision: context.revision, edits: sorted, selection: selection, effects: effects))
165 }
166
167 public struct Problem: Error, Equatable {
168 public let message: String
169 init(_ message: String) { self.message = message }
170 }
171
172 /// Whether `offset` falls between the two halves of a surrogate pair.
173 static func splits(_ offset: Int, _ text: NSString) -> Bool {
174 offset > 0 && offset < text.length && (0xDC00...0xDFFF).contains(text.character(at: offset))
175 }
176
177 static func integer(_ number: NSNumber) -> Int? {
178 guard CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }
179 let double = number.doubleValue
180 guard double.rounded() == double, abs(double) < 1e15 else { return nil }
181 return Int(double)
182 }
183
184 // MARK: - Prompts
185
186 /// A prompt from the value of `org.prompt(...)`: `message`, `initial`, `choices`,
187 /// `requireMatch` (default false) and `date`.
188 public static func prompt(_ value: Any) -> Prompt {
189 let options = value as? [String: Any] ?? [:]
190 let message = (options["message"] as? String) ?? (value as? String) ?? ""
191 let choices = (options["choices"] as? [Any])?.compactMap { $0 as? String } ?? []
192 let date = (options["date"] as? Bool) == true
193 return Prompt(
194 key: "user", message: message, initial: options["initial"] as? String ?? "", choices: choices,
195 requireMatch: (options["requireMatch"] as? Bool) == true && !choices.isEmpty,
196 date: date ? .init(defaultDate: nil) : nil
197 )
198 }
199
200 /// The answer the command gets: the text typed, or for a date prompt the date read from it,
201 /// `YYYY-MM-DD` or `YYYY-MM-DD HH:MM`.
202 public static func answer(_ text: String, to prompt: Prompt, now: Date, calendar: Calendar) -> String {
203 guard prompt.date != nil else { return text }
204 let read = ReadDate.read(text, default: nil, now: now, calendar: calendar)
205 let day = String(format: "%04d-%02d-%02d", read.year, read.month, read.day)
206 return read.timeGiven ? day + String(format: " %02d:%02d", read.hour, read.minute) : day
207 }
208}
Sources/OrgCore/Commands/UserCommands.swift added +180 · view
@@ -0,0 +1,180 @@
1import Foundation
2
3/// A command the user wrote: an exported function of a JavaScript module in the configuration
4/// folder's `commands/`, declared in `commands.toml`. Running it is the app's work, so `run`
5/// always asks for it as `.external(.userCommand)`.
6public struct UserCommand: OrgCommand, Equatable {
7 public let name: String
8 /// Shown as written; titles aren't translated.
9 public let title: String
10 /// The module, relative to `commands/`.
11 public let file: String
12 public let function: String
13 /// A `KeyContext` name; nil applies everywhere.
14 public let when: String?
15 /// Seconds, at most `UserCommands.maximumTimeout`.
16 public let timeout: Int
17
18 public init(name: String, title: String, file: String, function: String, when: String? = nil, timeout: Int = UserCommands.defaultTimeout) {
19 self.name = name
20 self.title = title
21 self.file = file
22 self.function = function
23 self.when = when
24 self.timeout = timeout
25 }
26
27 public var id: String { UserCommands.commandPrefix + name }
28
29 public func applies(in context: EditContext) -> Bool {
30 when.map { KeyContext.holds($0, in: context) } ?? true
31 }
32
33 public func run(in context: EditContext) -> CommandStep {
34 .external(.userCommand(UserCommandRequest(command: self, revision: context.revision, selection: context.selection)))
35 }
36}
37
38/// A user command to run against the buffer at `revision` with `selection`.
39public struct UserCommandRequest: Sendable, Equatable {
40 public let command: UserCommand
41 public let revision: Int
42 public let selection: [Range<Int>]
43
44 public init(command: UserCommand, revision: Int, selection: [Range<Int>]) {
45 self.command = command
46 self.revision = revision
47 self.selection = selection
48 }
49}
50
51/// The commands of `commands.toml`, which the app reads from the configuration folder.
52public final class UserCommands: @unchecked Sendable {
53 public static let shared = UserCommands()
54 public static let commandPrefix = "user."
55 public static let fileName = "commands.toml"
56 /// The folder beside `commands.toml` that holds the modules.
57 public static let folderName = "commands"
58 /// The newest `api` this version runs.
59 public static let apiVersion = 1
60 public static let defaultTimeout = 2
61 public static let maximumTimeout = 30
62
63 private let lock = NSLock()
64 private var commands: [UserCommand] = []
65 private var modules: URL?
66
67 public init() {}
68
69 /// In file order.
70 public var all: [UserCommand] { lock.withLock { commands } }
71
72 /// The `commands` folder the modules are in; nil before a file was read.
73 public var folder: URL? { lock.withLock { modules } }
74
75 public func command(_ id: String) -> UserCommand? {
76 guard id.hasPrefix(Self.commandPrefix) else { return nil }
77 let name = id.dropFirst(Self.commandPrefix.count)
78 return lock.withLock { commands.first { $0.name == name } }
79 }
80
81 /// Replaces every command, as from the file, with the folder their modules are in.
82 public func replace(_ all: [UserCommand], folder: URL?) {
83 lock.withLock {
84 commands = all
85 modules = folder
86 }
87 }
88
89 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout"]
90
91 /// 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
93 /// path (relative to `commands/`) is there. A file that isn't valid TOML throws.
94 public static func parse(_ toml: String, problems: inout [String], exists: (String) -> Bool) throws -> [UserCommand] {
95 let tables = try TOML.parse(toml)
96 var api: Int?
97 var result: [UserCommand] = []
98 var names = Set<String>()
99 for table in tables {
100 if table.name.isEmpty {
101 for key in table.keys where key != "api" { problems.append("unknown key \(key)") }
102 if let value = table.values["api"] {
103 guard let number = value.integer else {
104 problems.append("api must be a number")
105 continue
106 }
107 api = number
108 }
109 continue
110 }
111 guard table.name == "command", table.isArrayElement else {
112 problems.append("line \(table.line): unknown table [\(table.name)]")
113 continue
114 }
115 guard let name = table.values["name"]?.string, NamedMacros.isValidName(name) else {
116 problems.append("line \(table.line): command needs a name of letters, digits, - and _")
117 continue
118 }
119 func problem(_ text: String) { problems.append("command \(name): \(text)") }
120 for key in table.keys where !keys.contains(key) { problem("unknown key \(key)") }
121 guard names.insert(name).inserted else {
122 problem("defined twice")
123 continue
124 }
125 guard let file = table.values["file"]?.string, !file.isEmpty else {
126 problem("missing file")
127 continue
128 }
129 guard isModulePath(file) else {
130 problem("file must be a .js or .mjs file in \(folderName)/")
131 continue
132 }
133 guard exists(file) else {
134 problem("no file \(folderName)/\(file)")
135 continue
136 }
137 guard let function = table.values["function"]?.string, isIdentifier(function) else {
138 problem("function must be the name of an exported function")
139 continue
140 }
141 let when = table.values["when"]?.string
142 if let when, !KeyContext.names.contains(when) {
143 problem("unknown context \(when)")
144 continue
145 }
146 var timeout = defaultTimeout
147 if let value = table.values["timeout"] {
148 guard let seconds = value.integer, (1...maximumTimeout).contains(seconds) else {
149 problem("timeout must be 1 to \(maximumTimeout) seconds")
150 continue
151 }
152 timeout = seconds
153 }
154 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
156 result.append(UserCommand(name: name, title: title, file: file, function: function, when: when, timeout: timeout))
157 }
158 guard let api else {
159 if !result.isEmpty || tables.contains(where: { $0.name == "command" }) { problems.append("missing api = \(apiVersion)") }
160 return []
161 }
162 guard api == apiVersion else {
163 problems.append(api > apiVersion ? "api \(api) needs a newer orgstar" : "unknown api \(api)")
164 return []
165 }
166 return result
167 }
168
169 /// A path of `.js` or `.mjs` file below `commands/`, without `.`, `..` or empty parts.
170 public static func isModulePath(_ path: String) -> Bool {
171 let parts = path.split(separator: "/", omittingEmptySubsequences: false)
172 return parts.allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains(where: { "?#%\\".contains($0) }) }
173 && (path.hasSuffix(".js") || path.hasSuffix(".mjs"))
174 }
175
176 static func isIdentifier(_ name: String) -> Bool {
177 guard let first = name.unicodeScalars.first, !CharacterSet.decimalDigits.contains(first) else { return false }
178 return name.unicodeScalars.allSatisfy { $0.isASCII && (CharacterSet.alphanumerics.contains($0) || $0 == "_" || $0 == "$") }
179 }
180}
Sources/OrgEditorAppKit/EditorCommands.swift +10 −4 · view
@@ -4,8 +4,8 @@ import OrgCore
44
55/// Every command a key, menu or the palette can run, by id.
66public struct EditorCommand: Sendable {
7 /// The title as the string catalog translates it.
8 public var localizedTitle: String { CommandTitle.localized(title) }
7 /// The title as the string catalog translates it; a user command's as written.
8 public var localizedTitle: String { id.hasPrefix(UserCommands.commandPrefix) ? title : CommandTitle.localized(title) }
99
1010 public enum Action: Sendable {
1111 /// An `OrgCore` command, run through `OrgEditor.perform`.
@@ -37,8 +37,8 @@ public struct EditorCommand: Sendable {
3737}
3838
3939public enum EditorCommands {
40 /// Every command, with the named keyboard macros.
41 public static var all: [EditorCommand] { builtIn + namedMacros(NamedMacros.shared) }
40 /// Every command, with the named keyboard macros and the user commands.
41 public static var all: [EditorCommand] { builtIn + namedMacros(NamedMacros.shared) + userCommands(UserCommands.shared) }
4242
4343 public static let builtIn: [EditorCommand] = Commands.everything.map { EditorCommand(id: $0.id, title: $0.title, action: .text($0)) } + [
4444 EditorCommand(id: "org.cycle", title: "Cycle Visibility", action: .view),
@@ -272,6 +272,11 @@ public enum EditorCommands {
272272 store.names.map { EditorCommand(id: NamedMacros.commandPrefix + $0, title: $0, action: .view) }
273273 }
274274
275 /// The commands of `commands.toml`.
276 public static func userCommands(_ store: UserCommands) -> [EditorCommand] {
277 store.all.map { EditorCommand(id: $0.id, title: $0.title, action: .text($0)) }
278 }
279
275280 private static func movement(_ name: String, _ title: String, _ selector: String) -> EditorCommand {
276281 let extending = String(selector.dropLast()) + "AndModifySelection:"
277282 return EditorCommand(id: "edit.\(name)", title: title, action: .edit(selector: selector, extending: extending))
@@ -286,6 +291,7 @@ public enum EditorCommands {
286291 /// A command by id; any `macro.named.` id is one, which says so when no macro has its name.
287292 public static func command(_ id: String) -> EditorCommand? {
288293 if let command = byID[id] { return command }
294 if let command = UserCommands.shared.command(id) { return EditorCommand(id: id, title: command.title, action: .text(command)) }
289295 guard id.hasPrefix(NamedMacros.commandPrefix) else { return nil }
290296 return EditorCommand(id: id, title: String(id.dropFirst(NamedMacros.commandPrefix.count)), action: .view)
291297 }
Sources/Orgstar/ContentView.swift +17 −2 · view
@@ -517,7 +517,7 @@ struct ContentView: View {
517517 }
518518 .onChange(of: ConfigSync.shared.changedFile?.serial) {
519519 // Named macros are commands keymap.toml can bind.
520 if ["keymap.toml", NamedMacros.fileName].contains(ConfigSync.shared.changedFile?.name) { loadKeymap() }
520 if ["keymap.toml", NamedMacros.fileName, UserCommands.fileName].contains(ConfigSync.shared.changedFile?.name) { loadKeymap() }
521521 }
522522 .onChange(of: commands.jumpRequest?.id) {
523523 guard let request = commands.jumpRequest else { return }
@@ -1216,6 +1216,8 @@ struct ContentView: View {
12161216 case .tangle(let scope):
12171217 guard ProAccess.shared.allows(.babel), reach(session.tangleFiles(scope)) else { return }
12181218 commands.show(session.tangle(scope))
1219 case .userCommand(let request):
1220 runUserCommand(request)
12191221 case .agenda(let start, let days):
12201222 commands.agendaRequest = (start, days)
12211223 openWindow(id: "agenda")
@@ -1293,6 +1295,17 @@ struct ContentView: View {
12931295 }
12941296 }
12951297
1298 /// Runs a user command once its file is trusted on this device.
1299 private func runUserCommand(_ request: UserCommandRequest) {
1300 guard let path = session.path, let modules = session.userCommands.folder else { return }
1301 if let refusal = session.refusesUserCommand(path) { return commands.show(refusal) }
1302 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: commands.ask, run: {
1303 guard let context = commands.editor?.context() else { return }
1304 commands.show(String(localized: "Running \(request.command.title)… (⌘. to cancel)", comment: "A user command started"))
1305 session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: commands.ask) { commands.show($0) }
1306 }, refuse: { commands.show($0) })
1307 }
1308
12961309 /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does.
12971310 private func runElispLink(_ form: String) {
12981311 let run = { _ = Task { commands.show(await session.evaluateLink(form)) } }
@@ -1460,7 +1473,9 @@ struct ContentView: View {
14601473 focusPane(window)
14611474 case "app.window-new": openWindow(id: "editor")
14621475 case "app.babel.cancel":
1463 if session.isRunningBabel {
1476 if session.isRunningUserCommand {
1477 session.cancelUserCommand()
1478 } else if session.isRunningBabel {
14641479 session.cancelBabel()
14651480 } else if let task = commands.emacsTask {
14661481 task.cancel()
Sources/Orgstar/Keys.swift +7 −1 · view
@@ -314,7 +314,13 @@ struct PaletteView: View {
314314 @Environment(\.dismiss) private var dismiss
315315
316316 private var matches: (recent: [EditorCommand], rest: [EditorCommand]) {
317 CommandRanking.rank(EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) }, query: query,
317 // A user command's `when` leaves it out where it doesn't apply.
318 let context = commands.editor?.context()
319 func offered(_ command: EditorCommand) -> Bool {
320 guard case .text(let user as UserCommand) = command.action else { return true }
321 return context.map(user.applies) ?? false
322 }
323 return CommandRanking.rank(EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) && offered($0) }, query: query,
318324 id: \.id, titles: { [$0.localizedTitle, $0.title] })
319325 }
320326
Sources/Orgstar/OrgstarApp.swift +1 −1 · view
@@ -799,7 +799,7 @@ struct OrgstarApp: App {
799799 CommandGroup(after: .textEditing) {
800800 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
801801 .keyboardShortcut(".")
802 .disabled(!session.isRunningBabel && commands.emacsTask == nil)
802 .disabled(!session.isRunningBabel && !session.isRunningUserCommand && commands.emacsTask == nil)
803803 Button("Search Notes") { commands.focusSearch = true }
804804 .keyboardShortcut("f", modifiers: [.command, .shift])
805805 }
Sources/OrgstarMobile/EditorScreen.swift +26 −2 · view
@@ -420,6 +420,18 @@ struct EditorScreen: View {
420420 }
421421 }
422422
423 /// Runs a user command once its file is trusted on this device.
424 private func runUserCommand(_ request: UserCommandRequest) {
425 guard let modules = session.userCommands.folder else { return }
426 if let refusal = session.refusesUserCommand(path) { return message = refusal }
427 let ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { prompt = PromptRequest(prompt: $0, reply: $1) }
428 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: {
429 guard let context = editor?.editContext() else { return }
430 message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad")
431 session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: ask) { message = $0 }
432 }, refuse: { message = $0 })
433 }
434
423435 private func start() {
424436 let pane: EditorPane
425437 if let existing = self.pane {
@@ -502,6 +514,7 @@ struct EditorScreen: View {
502514 editor.onColumnView = { view in sheet = .columns(view) }
503515 editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
504516 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
517 editor.onUserCommand = { request in runUserCommand(request) }
505518 editor.onRefreshSetup = { session.refreshSetup() }
506519 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
507520 editor.keymap = model.keymap
@@ -515,6 +528,14 @@ struct EditorScreen: View {
515528 if let onPaneCommand { if let text = onPaneCommand(id) { message = text } } else { message = MobileEditor.unavailable(command: id) }
516529 } else if id == "app.save" {
517530 _ = session.save(path)
531 } else if id == "app.babel.cancel" {
532 if session.isRunningUserCommand {
533 session.cancelUserCommand()
534 } else if session.isRunningBabel {
535 session.cancelBabel()
536 } else {
537 message = String(localized: "Nothing is running")
538 }
518539 } else if id == "app.archive" {
519540 if let caret = self.editor?.editContext().caret { message = session.archive(from: (path, caret)) }
520541 } else if id == "app.copy-rich-text" {
@@ -1166,7 +1187,7 @@ struct CommandPalette: View {
11661187 ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"),
11671188 ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"),
11681189 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), ("app.lint", "Lint File"), ("app.lint-folders", "Lint All Folders"),
1169 ("app.flashcards.review", "Review Flashcards"),
1190 ("app.flashcards.review", "Review Flashcards"), ("app.babel.cancel", "Cancel Running Task"),
11701191 ("app.working-copy.sync", "Sync with Working Copy"),
11711192 ("app.cite.insert", "Insert Citation…"),
11721193 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
@@ -1228,6 +1249,8 @@ struct CommandPalette: View {
12281249 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
12291250 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
12301251 return Self.commands(macros: editor.namedMacros, panes: paneCommands)
1252 // A user command's `when` leaves it out where it doesn't apply.
1253 .filter { UserCommands.shared.command($0.id)?.applies(in: context) ?? true }
12311254 .map { command in
12321255 CommandRow(id: command.id, title: CommandTitle.localized(command.title), keys: editor.keymap.keyLabels(for: command.id).first,
12331256 reason: reason(command.id, context))
@@ -1237,7 +1260,8 @@ struct CommandPalette: View {
12371260 /// The commands listed, with English titles: `panes`, the editor's, and the named macros.
12381261 static func commands(macros: NamedMacros, panes: [(id: String, title: String)] = []) -> [(id: String, title: String)] {
12391262 var seen = Set<String>()
1240 return (panes + viewCommands + Commands.everything.map { ($0.id, $0.title) } + macros.names.map { (NamedMacros.commandPrefix + $0, $0) })
1263 return (panes + viewCommands + Commands.everything.map { ($0.id, $0.title) } + macros.names.map { (NamedMacros.commandPrefix + $0, $0) }
1264 + UserCommands.shared.all.map { ($0.id, $0.title) })
12411265 .filter { !AppStoreCommands.hidden.contains($0.id) && offered($0.id) && seen.insert($0.id).inserted }
12421266 }
12431267
Sources/OrgstarMobile/KeyBar.swift +3 · view
@@ -90,6 +90,9 @@ struct KeyBar: View {
9090 let name = String(id.dropFirst(NamedMacros.commandPrefix.count))
9191 return NamedMacros.shared.names.contains(name) ? Item(label: name, symbol: nil, action: .command(id)) : nil
9292 }
93 if id.hasPrefix(UserCommands.commandPrefix) {
94 return UserCommands.shared.command(id).map { Item(label: $0.title, symbol: nil, action: .command(id)) }
95 }
9396 guard !AppStoreCommands.hidden.contains(id), let title = commandTitles[id].map(CommandTitle.localized) else { return nil }
9497 return Item(label: title, symbol: commandSymbols[id], action: .command(id), face: KeyBarLayout.face(title: title))
9598 }
Sources/OrgstarMobile/MobileEditor.swift +9 −3 · view
@@ -124,6 +124,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
124124 var onTangle: ((Tangle.Scope) -> Void)?
125125 /// A source block to run (C-c C-c).
126126 var onBabel: ((BabelJob) -> Void)?
127 /// A user command to run.
128 var onUserCommand: ((UserCommandRequest) -> Void)?
127129 /// The file's setup files to read again (C-c C-c on a keyword line).
128130 var onRefreshSetup: (() -> Void)?
129131 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
@@ -408,6 +410,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
408410 onEditBlock?(edit)
409411 case .external(.babel(let job)) where onBabel != nil:
410412 onBabel?(job)
413 case .external(.userCommand(let request)) where onUserCommand != nil:
414 onUserCommand?(request)
411415 case .external(.tangle(let scope)) where onTangle != nil:
412416 onTangle?(scope)
413417 case .external(.agenda(let start, let count)) where onAgenda != nil:
@@ -503,8 +507,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
503507 case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
504508 if let onAppCommand { onAppCommand(id) } else { onMessage?(Self.unavailable(command: id)) }
505509 default:
506 if let command = Commands.command(id) {
510 if let command: any OrgCommand = Commands.command(id) ?? UserCommands.shared.command(id) {
507511 _ = perform(command)
512 } else if id.hasPrefix(UserCommands.commandPrefix) {
513 fail("No command \(id.dropFirst(UserCommands.commandPrefix.count)) in \(UserCommands.fileName)")
508514 } else {
509515 fail(Self.unavailable(command: id))
510516 }
@@ -516,7 +522,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
516522
517523 func applies(_ id: String, in context: EditContext) -> Bool {
518524 if refuses(id) { return false }
519 if let command = Commands.command(id) ?? Snippets.command(id) { return command.applies(in: context) }
525 if let command: any OrgCommand = Commands.command(id) ?? Snippets.command(id) ?? UserCommands.shared.command(id) { return command.applies(in: context) }
520526 switch id {
521527 case "org.snippet.next-field", "org.snippet.previous-field": return snippetSession != nil
522528 case "org.cycle":
@@ -538,7 +544,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
538544 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
539545 case "app.table-export", "app.table-export.tsv", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
540546 case "app.word-count", "app.recovery", "app.sync-conflicts", "app.lint", "app.lint-folders", "app.flashcards.review", "app.attach.photo", "app.attach.camera", "app.attach.scan",
541 "app.rename-tag", "app.rename-todo-keyword": return onAppCommand != nil
547 "app.rename-tag", "app.rename-todo-keyword", "app.babel.cancel": return onAppCommand != nil
542548 case _ where id.hasPrefix(NamedMacros.commandPrefix): return true
543549 case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
544550 case "app.export-dialog", "app.export-subtree-dialog", "app.share-subtree", "app.copy-rich-text", "app.export.html-open", "app.export-body-only", "app.export.icalendar-agenda", "app.export.icalendar-combined": return onAppCommand != nil
Sources/OrgstarMobile/MobileModel.swift +1 · view
@@ -163,6 +163,7 @@ final class MobileModel {
163163 modalKeys = preset.isModal
164164 configProblems += loaded.problems.map { "keymap.toml: " + $0 }
165165 configProblems += MacroFile.load().map { "\(NamedMacros.fileName): " + $0 }
166 configProblems += configFolder.map { UserCommandFile.load(folder: $0, read: Self.read) } ?? UserCommandFile.load(folder: UserConfig.directory)
166167 SnippetLibrary.shared.reload(from: UserConfig.file(Snippets.fileName), read: configFolder == nil ? { try? String(contentsOf: $0, encoding: .utf8) } : Self.read)
167168 configProblems += SnippetLibrary.shared.problems
168169 configProblems += KeyBar.problems()
Tests/OrgAppTests/UserCommandRunTests.swift added +278 · view
@@ -0,0 +1,278 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// User commands run through the real command host against a session's buffer.
8@MainActor
9@Suite(.serialized)
10struct UserCommandRunTests {
11 static let manifest = """
12 api = 1
13
14 [[command]]
15 name = "upcase-title"
16 title = "Upcase Heading Title"
17 file = "headings.js"
18 function = "upcaseTitle"
19 when = "heading"
20
21 [[command]]
22 name = "weekly-review"
23 title = "Add Weekly Review"
24 file = "review.js"
25 function = "weeklyReview"
26
27 [[command]]
28 name = "overlap"
29 file = "bad.js"
30 function = "overlap"
31
32 [[command]]
33 name = "loop"
34 file = "bad.js"
35 function = "loop"
36 timeout = 1
37
38 [[command]]
39 name = "refuse"
40 file = "bad.js"
41 function = "refuse"
42
43 [[command]]
44 name = "copy"
45 file = "bad.js"
46 function = "copy"
47 """
48 static let headings = """
49 import { upper } from "./lib/text.js";
50
51 export async function upcaseTitle(org) {
52 const heading = await org.heading();
53 if (!heading) return org.fail("Not in an entry");
54 const text = await org.text();
55 const title = text.slice(heading.titleStart, heading.titleEnd);
56 return {
57 edits: [{ from: heading.titleStart, to: heading.titleEnd, text: upper(title) }],
58 message: `Upcased ${title}`,
59 };
60 }
61 """
62 static let review = """
63 export async function weeklyReview(org) {
64 const heading = await org.heading();
65 if (!heading) return org.fail("Not on a heading");
66 const week = await org.prompt({ message: "Week: ", initial: "W48" });
67 return {
68 edits: [{ from: heading.end, to: heading.end, text: `${"*".repeat(heading.level + 1)} Review ${week}\\n` }],
69 selection: heading.end + heading.level + 2,
70 };
71 }
72 """
73 static let bad = """
74 export function overlap() { return { edits: [{ from: 0, to: 4 }, { from: 2, to: 6 }] }; }
75 export function loop() { for (;;) {} }
76 export async function refuse(org) { await org.fail("Not today"); }
77 export async function copy(org) { org.message("Copying"); return { copy: (await org.file()) ?? "none" }; }
78 """
79 static let file = "* Plan the week :work:\nbody\n* Next\n"
80
81 let config: Folder
82 let notes: Folder
83 let path: String
84 let session: DocumentSession
85 let buffer: StateBuffer
86
87 init() throws {
88 config = try Folder()
89 notes = try Folder()
90 try config.write("commands.toml", Self.manifest)
91 try config.write("commands/headings.js", Self.headings)
92 try config.write("commands/lib/text.js", "export const upper = s => s.toUpperCase();\n")
93 try config.write("commands/review.js", Self.review)
94 try config.write("commands/bad.js", Self.bad)
95 path = try notes.write("a.org", Self.file).path
96 session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
97 session.saveMode = .explicit
98 session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
99 session.userCommands = UserCommands()
100 #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
101 session.open(path)
102 buffer = StateBuffer(try #require(session.document))
103 session.attach(buffer)
104 }
105
106 func run(_ name: String, at caret: Int = 4, ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { _, reply in reply(nil) },
107 report: @escaping @MainActor (String) -> Void = { _ in }) async throws -> String? {
108 let command = try #require(session.userCommands.command("user." + name))
109 let document = buffer.document
110 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [caret..<caret])
111 guard case .external(.userCommand(let request)) = command.run(in: context) else { throw CancellationError() }
112 return await session.runUserCommand(request, context: context, file: "a.org", ask: ask, report: report)
113 }
114
115 @Test func upcasesTheHeadingTitle() async throws {
116 #expect(try await run("upcase-title") == nil)
117 #expect(buffer.document.text == "* PLAN THE WEEK :work:\nbody\n* Next\n")
118 // Before the first heading, `org.fail`'s text.
119 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: "intro\n" + Self.file), now: Date(), answers: [:])
120 #expect(try await run("upcase-title", at: 0) == "Not in an entry")
121 }
122
123 @Test func asksThroughThePrompt() async throws {
124 var asked: Prompt?
125 let message = try await run("weekly-review", ask: { prompt, reply in
126 asked = prompt
127 reply("W49")
128 })
129 #expect(message == nil)
130 #expect(asked == Prompt(key: "user", message: "Week: ", initial: "W48", requireMatch: false))
131 #expect(buffer.document.text == "* Plan the week :work:\nbody\n** Review W49\n* Next\n")
132 #expect(buffer.selection == [31..<31])
133 // A canceled prompt ends the command with nothing changed.
134 #expect(try await run("weekly-review") == "Quit")
135 #expect(buffer.document.text == "* Plan the week :work:\nbody\n** Review W49\n* Next\n")
136 }
137
138 @Test func anEditWhileItRanRefusesItsResult() async throws {
139 let message = try await run("weekly-review", ask: { [buffer] _, reply in
140 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:])
141 reply("W49")
142 })
143 #expect(message == "The file changed; try again.")
144 #expect(buffer.document.text == Self.file + "typed\n")
145 }
146
147 @Test func refusesWhatCantApply() async throws {
148 #expect(try await run("overlap") == "overlap: edits overlap")
149 #expect(try await run("refuse") == "Not today")
150 let start = ContinuousClock.now
151 #expect(try await run("loop") == "loop didn't finish within 1 s and was stopped.")
152 #expect(ContinuousClock.now - start < .seconds(10))
153 #expect(buffer.document.text == Self.file)
154 var reported: [String] = []
155 #expect(try await run("copy", report: { reported.append($0) }) == nil)
156 #expect(reported == ["Copying"])
157 }
158
159 @Test func cancelStopsTheCommand() async throws {
160 let document = buffer.document
161 let command = try #require(session.userCommands.command("user.loop"))
162 let request = UserCommandRequest(command: command, revision: document.revision, selection: [0..<0])
163 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [0..<0])
164 var reported: [String] = []
165 session.startUserCommand(request, context: context, file: nil, ask: { _, reply in reply(nil) }) { reported.append($0) }
166 #expect(session.isRunningUserCommand)
167 try await Task.sleep(for: .milliseconds(200))
168 session.cancelUserCommand()
169 for _ in 0..<100 where reported.isEmpty { try await Task.sleep(for: .milliseconds(20)) }
170 #expect(reported == ["loop canceled."])
171 #expect(!session.isRunningUserCommand)
172 }
173
174 @Test func refusedInBuffersWithDecryptedText() async throws {
175 let gpg = notes.url.appendingPathComponent("d.org.gpg")
176 try OpenPGP.encryptedMessage(Data("* Secret\n".utf8), passphrase: "pw").write(to: gpg)
177 session.open(gpg.path)
178 #expect(session.unlock("pw", for: gpg.path) == nil)
179 #expect(session.refusesUserCommand(gpg.path) == "d.org.gpg has decrypted entries, so user commands don't run in it.")
180 let document = try #require(session.document)
181 let command = try #require(session.userCommands.command("user.upcase-title"))
182 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [3..<3])
183 let request = UserCommandRequest(command: command, revision: document.revision, selection: [3..<3])
184 #expect(await session.runUserCommand(request, context: context, file: nil, ask: { _, _ in }, report: { _ in })
185 == "d.org.gpg has decrypted entries, so user commands don't run in it.")
186 #expect(session.document?.text == "* Secret\n")
187 #expect(session.refusesUserCommand(path) == nil)
188 }
189}
190
191@MainActor
192struct UserCommandFileTests {
193 @Test func reportsProblemsByFile() throws {
194 let config = try Folder()
195 let store = UserCommands()
196 #expect(UserCommandFile.load(into: store, folder: config.url) == [])
197 try config.write("commands.toml", "api = 1\n[[command]]\nname = \"a\"\nfile = \"a.js\"\nfunction = \"a\"\n")
198 #expect(UserCommandFile.load(into: store, folder: config.url) == ["commands.toml: command a: no file commands/a.js"])
199 #expect(store.all.isEmpty && store.folder == nil)
200 try config.write("commands/a.js", "export function a() {}\n")
201 #expect(UserCommandFile.load(into: store, folder: config.url) == [])
202 #expect(store.all.map(\.id) == ["user.a"])
203 #expect(store.folder?.lastPathComponent == "commands")
204 try config.write("commands.toml", "api = 1\n[[command]\n")
205 #expect(UserCommandFile.load(into: store, folder: config.url) == ["commands.toml: line 2: unclosed table header"])
206 #expect(store.all.isEmpty)
207 }
208
209 @Test func importsResolveInsideTheFolder() {
210 let text = """
211 import { a } from "./a.js";
212 import * as b from '../b.js';
213 export { c } from "./lib/c.mjs";
214 import "./side.js";
215 const d = await import("./d.js");
216 import e from "https://example.com/e.js";
217 """
218 #expect(UserCommandFile.imports(text, from: "sub/main.js").sorted() == ["b.js", "sub/a.js", "sub/d.js", "sub/lib/c.mjs", "sub/side.js"])
219 #expect(UserCommandFile.imports("import x from '../../x.js';", from: "main.js") == [])
220 }
221
222 @Test func relativePath() {
223 #expect(UserCommandFile.relativePath("/n/notes/a/b.org", roots: ["/n", "/n/notes"]) == "a/b.org")
224 #expect(UserCommandFile.relativePath("/elsewhere/c.org", roots: ["/n"]) == "c.org")
225 }
226
227 /// Always keeps trust for the file and its imports as they are; a change to either, as one
228 /// arriving by sync, asks again.
229 @Test func aChangedScriptAsksForTrustAgain() throws {
230 let config = try Folder()
231 try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return x; }\n")
232 try config.write("commands/lib.js", "export const x = null;\n")
233 let modules = config.url.appendingPathComponent("commands")
234 let trust = TrustStore(file: config.url.appendingPathComponent("trusted.json"))
235 let command = UserCommand(name: "go", title: "Go", file: "main.js", function: "go")
236 var asked: [String] = []
237 var runs = 0
238 var refusals: [String] = []
239 func check(_ answer: String?) {
240 UserCommandTrust.check(command, modules: modules, trust: trust, ask: { prompt, reply in
241 asked.append(prompt.message)
242 reply(answer)
243 }, run: { runs += 1 }, refuse: { refusals.append($0) })
244 }
245 check(UserCommandTrust.dontRun)
246 #expect(runs == 0 && refusals == ["Not run"])
247 #expect(asked == ["Run commands from commands/main.js?"])
248 check(UserCommandTrust.runOnce)
249 check(UserCommandTrust.runOnce)
250 #expect(runs == 2 && asked.count == 3)
251 check(UserCommandTrust.always)
252 check(nil)
253 #expect(runs == 4 && asked.count == 4)
254 try config.write("commands/lib.js", "export const x = 1;\n")
255 check(UserCommandTrust.always)
256 #expect(runs == 5 && asked.count == 5)
257 try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return 2; }\n")
258 check(nil)
259 #expect(runs == 5 && asked.count == 6 && refusals == ["Not run", "Not run"])
260 // Back to a version trusted before, it runs without asking.
261 try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return x; }\n")
262 check(nil)
263 #expect(runs == 6)
264 #expect(UserCommandFile.trustedText("gone.js", modules: modules) == nil)
265 }
266
267 @Test func emacsImportNotesBindingsToTheUsersFunctions() throws {
268 let folder = try Folder()
269 try folder.write("init.el", """
270 (defun my/weekly-review () (interactive) (org-insert-heading))
271 (global-set-key (kbd "C-c w") #'my/weekly-review)
272 (global-set-key (kbd "C-c q") #'some-package-command)
273 """)
274 let result = EmacsImport.scan(EmacsImport.files(in: folder.url))
275 #expect(result.unsupported.contains { $0.name == "C-c w → my/weekly-review" && $0.reason == "your own function; write it as a user command in commands.toml" })
276 #expect(result.unsupported.contains { $0.name == "C-c q → some-package-command" && $0.reason == "orgstar has no such command" })
277 }
278}
Tests/OrgCoreTests/UserCommandTests.swift added +241 · view
@@ -0,0 +1,241 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct UserCommandManifestTests {
6 func parse(_ toml: String, files: Set<String> = ["review.js", "lib/dates.mjs"]) throws -> ([UserCommand], [String]) {
7 var problems: [String] = []
8 let commands = try UserCommands.parse(toml, problems: &problems) { files.contains($0) }
9 return (commands, problems)
10 }
11
12 @Test func readsCommands() throws {
13 let (commands, problems) = try parse("""
14 api = 1
15
16 [[command]]
17 name = "weekly-review"
18 title = "Start Weekly Review"
19 file = "review.js"
20 function = "weeklyReview"
21 when = "heading"
22 timeout = 5
23
24 [[command]]
25 name = "dates"
26 file = "lib/dates.mjs"
27 function = "$fix_dates"
28 """)
29 #expect(problems == [])
30 #expect(commands == [
31 UserCommand(name: "weekly-review", title: "Start Weekly Review", file: "review.js", function: "weeklyReview", when: "heading", timeout: 5),
32 UserCommand(name: "dates", title: "dates", file: "lib/dates.mjs", function: "$fix_dates", timeout: 2),
33 ])
34 #expect(commands[0].id == "user.weekly-review")
35 }
36
37 @Test func reportsProblemsByCommandAndKey() throws {
38 let (commands, problems) = try parse("""
39 api = 1
40 extra = true
41
42 [[command]]
43 name = "ok"
44 file = "review.js"
45 function = "ok"
46 colour = "red"
47
48 [[command]]
49 name = "missing"
50 file = "gone.js"
51 function = "f"
52
53 [[command]]
54 name = "outside"
55 file = "../secret.js"
56 function = "f"
57
58 [[command]]
59 name = "bad function"
60 file = "review.js"
61 function = "f"
62
63 [[command]]
64 name = "fn"
65 file = "review.js"
66 function = "1f"
67
68 [[command]]
69 name = "ctx"
70 file = "review.js"
71 function = "f"
72 when = "everywhere"
73
74 [[command]]
75 name = "slow"
76 file = "review.js"
77 function = "f"
78 timeout = 60
79
80 [[command]]
81 name = "ok"
82 file = "review.js"
83 function = "again"
84
85 [other]
86 """)
87 #expect(commands.map(\.name) == ["ok"])
88 #expect(problems == [
89 "unknown key extra",
90 "command ok: unknown key colour",
91 "command missing: no file commands/gone.js",
92 "command outside: file must be a .js or .mjs file in commands/",
93 "line 20: command needs a name of letters, digits, - and _",
94 "command fn: function must be the name of an exported function",
95 "command ctx: unknown context everywhere",
96 "command slow: timeout must be 1 to 30 seconds",
97 "command ok: defined twice",
98 "line 47: unknown table [other]",
99 ])
100 }
101
102 @Test func needsAKnownAPI() throws {
103 let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n"
104 #expect(try parse(command) == ([], ["missing api = 1"]))
105 #expect(try parse("api = 2\n" + command) == ([], ["api 2 needs a newer orgstar"]))
106 #expect(try parse("api = 0\n" + command) == ([], ["unknown api 0"]))
107 #expect(try parse("") == ([], []))
108 #expect(throws: TOML.ParseError.self) { _ = try parse("api = \n[[command") }
109 }
110
111 @Test func whenHidesTheCommandWhereItDoesntApply() {
112 let text = "intro\n* Heading\nbody\n"
113 let command = UserCommand(name: "h", title: "H", file: "a.js", function: "h", when: "heading")
114 func context(_ caret: Int) -> EditContext { EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) }
115 #expect(!command.applies(in: context(0)))
116 #expect(command.applies(in: context(8)))
117 #expect(UserCommand(name: "e", title: "E", file: "a.js", function: "e").applies(in: context(0)))
118 #expect(command.run(in: context(8)) == .external(.userCommand(UserCommandRequest(command: command, revision: 3, selection: [8..<8]))))
119 }
120
121 @Test func registry() {
122 let store = UserCommands()
123 let command = UserCommand(name: "a", title: "A", file: "a.js", function: "a")
124 store.replace([command], folder: URL(fileURLWithPath: "/c/commands"))
125 #expect(store.command("user.a") == command)
126 #expect(store.command("user.b") == nil)
127 #expect(store.command("a") == nil)
128 #expect(store.folder?.path == "/c/commands")
129 }
130}
131
132struct UserCommandAPITests {
133 static let text = """
134 #+FILETAGS: :home:
135 intro
136 * TODO [#A] Plan the week :work:
137 SCHEDULED: <2026-11-30 Mon> DEADLINE: <2026-12-04 Fri>
138 :PROPERTIES:
139 :EFFORT: 1:00
140 :END:
141 ** Sub é
142 * Done
143 """
144
145 func context(_ caret: Int, selection: [Range<Int>]? = nil) -> EditContext {
146 EditContext(revision: 7, text: Self.text, tree: OrgParser.parse(Self.text), selection: selection ?? [caret..<caret], knownTags: { ["work", "home"] })
147 }
148
149 func offset(_ needle: String) -> Int { (Self.text as NSString).range(of: needle).location }
150
151 @Test func headingAtThePoint() throws {
152 let context = context(offset("EFFORT"))
153 let heading = try #require(UserCommandAPI.answer("heading", NSNull(), context: context, file: nil) as? [String: Any])
154 #expect(heading["level"] as? Int == 1)
155 #expect(heading["keyword"] as? String == "TODO")
156 #expect(heading["done"] as? Bool == false)
157 #expect(heading["priority"] as? String == "A")
158 #expect(heading["title"] as? String == "Plan the week")
159 #expect(heading["tags"] as? [String] == ["work"])
160 #expect(heading["start"] as? Int == offset("* TODO"))
161 #expect(heading["end"] as? Int == offset("* Done"))
162 let titleStart = try #require(heading["titleStart"] as? Int), titleEnd = try #require(heading["titleEnd"] as? Int)
163 #expect((Self.text as NSString).substring(with: NSRange(titleStart..<titleEnd)) == "Plan the week")
164 #expect(heading["scheduled"] as? String == "<2026-11-30 Mon>")
165 #expect(heading["deadline"] as? String == "<2026-12-04 Fri>")
166 #expect(heading["closed"] is NSNull)
167 #expect(heading["properties"] as? [String: String] == ["EFFORT": "1:00"])
168 // Before the first heading, none; with an offset, the heading there.
169 #expect(UserCommandAPI.answer("heading", NSNull(), context: self.context(0), file: nil) is NSNull)
170 let sub = try #require(UserCommandAPI.answer("heading", offset("Sub") as NSNumber, context: context, file: nil) as? [String: Any])
171 #expect(sub["title"] as? String == "Sub é")
172 #expect(sub["level"] as? Int == 2)
173 #expect(sub["keyword"] is NSNull)
174 }
175
176 @Test func outlineSelectionTextFileAndSettings() throws {
177 let context = context(0, selection: [3..<5, 9..<9])
178 let outline = try #require(UserCommandAPI.answer("outline", NSNull(), context: context, file: nil) as? [[String: Any]])
179 #expect(outline.map { $0["title"] as? String } == ["Plan the week", "Sub é", "Done"])
180 #expect(outline.last?["end"] as? Int == (Self.text as NSString).length)
181 #expect(UserCommandAPI.answer("text", NSNull(), context: context, file: nil) as? String == Self.text)
182 #expect(UserCommandAPI.answer("selection", NSNull(), context: context, file: nil) as? [[String: Int]] == [["from": 3, "to": 5], ["from": 9, "to": 9]])
183 #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: "notes/a.org") as? String == "notes/a.org")
184 #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: nil) is NSNull)
185 let settings = try #require(UserCommandAPI.answer("settings", NSNull(), context: context, file: nil) as? [String: Any])
186 #expect(settings["todoKeywords"] as? [String] == ["TODO"])
187 #expect(settings["doneKeywords"] as? [String] == ["DONE"])
188 #expect(settings["fileTags"] as? [String] == ["home"])
189 #expect(settings["tags"] as? [String] == ["work", "home"])
190 #expect(settings["fillColumn"] as? Int == 70)
191 #expect(UserCommandAPI.answer("nope", NSNull(), context: context, file: nil) == nil)
192 }
193
194 func result(_ json: String) -> Result<EditResult, UserCommandAPI.Problem> {
195 UserCommandAPI.result(json, in: EditContext(revision: 4, text: "ab😀cd", tree: OrgParser.parse("ab😀cd"), selection: [0..<0]))
196 }
197
198 @Test func readsTheResult() {
199 #expect(result("null") == .success(EditResult(baseRevision: 4, edits: [])))
200 #expect(result(#"{"edits": [{"from": 5, "to": 6, "text": "D"}, {"from": 0, "to": 1}, {"from": 2, "text": "+"}], "selection": {"from": 1, "to": 2}, "message": "done", "copy": "x"}"#)
201 == .success(EditResult(baseRevision: 4, edits: [
202 TextEdit(range: 0..<1, replacement: ""), TextEdit(range: 2..<2, replacement: "+"), TextEdit(range: 5..<6, replacement: "D"),
203 ], selection: [1..<2], effects: [.message("done"), .copy("x")])))
204 #expect(result(#"{"selection": [3, {"from": 5, "to": 1}]}"#) == .success(EditResult(baseRevision: 4, edits: [], selection: [3..<3, 1..<5])))
205 }
206
207 @Test func refusesEditsThatCantApply() {
208 func problem(_ json: String) -> String? {
209 if case .failure(let problem) = result(json) { return problem.message }
210 return nil
211 }
212 #expect(problem(#"{"edits": [{"from": 0, "to": 2}, {"from": 1, "to": 4}]}"#) == "edits overlap")
213 #expect(problem(#"{"edits": [{"from": 1, "text": "a"}, {"from": 1, "text": "b"}]}"#) == "edits overlap")
214 #expect(problem(#"{"edits": [{"from": 5, "to": 9}]}"#) == "edit 1 is outside the text")
215 #expect(problem(#"{"edits": [{"from": 2, "to": 1}]}"#) == "edit 1 is outside the text")
216 #expect(problem(#"{"edits": [{"from": -1}]}"#) == "edit 1 is outside the text")
217 #expect(problem(#"{"edits": [{"from": 3}]}"#) == "edit 1 splits a character")
218 #expect(problem(#"{"edits": [{"from": 0.5}]}"#) == "edit 1 needs a from offset")
219 #expect(problem(#"{"edits": [{"from": 0, "text": 3}]}"#) == "edit 1 has a text that isn't a string")
220 #expect(problem(#"{"edits": {"from": 0}}"#) == "edits must be a list")
221 #expect(problem(#"{"edit": []}"#) == "returned an unknown key edit")
222 #expect(problem(#"{"selection": 7}"#) == "selection is outside the text")
223 #expect(problem(#"{"edits": [{"from": 0, "to": 6}], "selection": 2}"#) == "selection is outside the text")
224 #expect(problem(#"{"message": 3}"#) == "message must be a string")
225 #expect(problem(#""text""#) == "returned something other than an object")
226 }
227
228 @Test func prompts() {
229 let prompt = UserCommandAPI.prompt(["message": "Week: ", "initial": "W48", "choices": ["W48", "W49"], "requireMatch": true] as [String: Any])
230 #expect(prompt == Prompt(key: "user", message: "Week: ", initial: "W48", choices: ["W48", "W49"], requireMatch: true))
231 #expect(UserCommandAPI.prompt(["message": "Any: ", "requireMatch": true] as [String: Any]).requireMatch == false)
232 let date = UserCommandAPI.prompt(["message": "When? ", "date": true] as [String: Any])
233 #expect(date.date == Prompt.DateRead(defaultDate: nil))
234 var utc = Calendar(identifier: .gregorian)
235 utc.timeZone = TimeZone(identifier: "UTC")!
236 let now = Date(timeIntervalSince1970: 1_795_000_000) // 2026-11-18
237 #expect(UserCommandAPI.answer("+2d", to: date, now: now, calendar: utc) == "2026-11-20")
238 #expect(UserCommandAPI.answer("2026-12-01 9:30", to: date, now: now, calendar: utc) == "2026-12-01 09:30")
239 #expect(UserCommandAPI.answer("+2d", to: prompt, now: now, calendar: utc) == "+2d")
240 }
241}
Tests/OrgEditorAppKitTests/UserCommandEditorTests.swift added +75 · view
@@ -0,0 +1,75 @@
1import AppKit
2import Foundation
3import OrgCore
4import OrgDocument
5@testable import OrgApp
6import Testing
7@testable import OrgEditorAppKit
8
9/// A user command run through the command host on the session's editor.
10@MainActor
11struct UserCommandEditorTests {
12 @Test func editsApplyAsOneUndoStep() async throws {
13 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
14 defer { try? FileManager.default.removeItem(at: folder) }
15 let modules = folder.appendingPathComponent("config/commands")
16 try FileManager.default.createDirectory(at: modules, withIntermediateDirectories: true)
17 try Data("""
18 export async function swap(org) {
19 const [{ from }] = await org.selection();
20 const h = await org.heading();
21 return {
22 edits: [
23 { from: h.titleStart, to: h.titleStart, text: "[" },
24 { from: h.titleEnd, to: h.titleEnd, text: "]" },
25 { from: h.end, to: h.end, text: "added\\n" },
26 ],
27 selection: from + 1,
28 message: "Swapped",
29 };
30 }
31 """.utf8).write(to: modules.appendingPathComponent("swap.js"))
32 let file = folder.appendingPathComponent("a.org")
33 let text = "* One\nbody\n* Two\n"
34 try Data(text.utf8).write(to: file)
35 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
36 session.saveMode = .explicit
37 session.userCommands = UserCommands()
38 let command = UserCommand(name: "swap", title: "Swap", file: "swap.js", function: "swap")
39 session.userCommands.replace([command], folder: modules)
40 session.open(file.path)
41 let h = Harness(try #require(session.document))
42 h.editor.onChange = { [weak session] in session?.bufferChanged() }
43 session.attach(h.editor)
44 var messages: [String] = []
45 h.editor.onMessage = { messages.append($0) }
46 h.caret(at: 3)
47 var requested: UserCommandRequest?
48 h.editor.onExternal = { if case .userCommand(let request) = $0 { requested = request } }
49 h.editor.perform(command)
50 let request = try #require(requested)
51 #expect(await session.runUserCommand(request, context: h.editor.context(), file: "a.org", ask: { _, _ in }, report: { _ in }) == nil)
52 #expect(h.string == "* [One]\nbody\nadded\n* Two\n")
53 #expect(h.textView.selectedRange() == NSRange(location: 4, length: 0))
54 #expect(messages == ["Swapped"])
55 #expect(session.isDirty)
56 h.checkInSync()
57 h.textView.undoManager?.undo()
58 #expect(h.string == text)
59 #expect(h.textView.undoManager?.canUndo != true)
60 h.checkInSync()
61 }
62
63 @Test func registeredWhereCommandIDsAre() throws {
64 let store = UserCommands()
65 store.replace([UserCommand(name: "review", title: "Weekly Review", file: "r.js", function: "r", when: "heading")], folder: nil)
66 let commands = EditorCommands.userCommands(store)
67 #expect(commands.map(\.id) == ["user.review"])
68 #expect(commands[0].localizedTitle == "Weekly Review" && commands[0].inPalette)
69 var problems: [String] = []
70 let ids = Set(EditorCommands.builtIn.map(\.id) + commands.map(\.id))
71 let keymap = try Keymap(toml: "[[bind]]\nkeys = \"C-c w\"\ncommand = \"user.review\"\n[[bind]]\nkeys = \"C-c x\"\ncommand = \"user.other\"\n", problems: &problems, commands: ids)
72 #expect(keymap.bindings.map(\.command) == ["user.review"])
73 #expect(problems == ["line 4: unknown command user.other"])
74 }
75}
docs/manual/guide/03-keys.org +13 −1 · view
@@ -332,6 +332,18 @@ command = "macro.named.done-and-next"
332332
333333orgstar reloads =macros.toml= when you save it, and reads =keymap.toml= again so that bindings to new names apply.
334334
335* User commands
336
337Commands you write in JavaScript and declare in =commands.toml= have ids =user.=/name/ (see [[file:18-user-commands.org][User commands]]). They are in the palette under their titles, shown as written, and =keymap.toml= binds them like any other command, in every preset and Doom state:
338
339#+BEGIN_SRC toml
340[[bind]]
341keys = "C-c u"
342command = "user.upcase-title"
343#+END_SRC
344
345A command with =when= in =commands.toml= is left out of the palette where its context doesn't hold, and its keys fall through there as a binding's =when= makes them. orgstar reads =keymap.toml= again when =commands.toml= changes, so bindings to new commands apply. A binding to a =user.= id that =commands.toml= doesn't define is reported as an unknown command.
346
335347* Vim editing (Doom preset)
336348
337349The Doom preset edits modally, as Doom Emacs does with =evil=, =evil-org=, =evil-surround=, =evil-snipe= and =evil-nerd-commenter=. orgstar implements these itself; none of them are Emacs packages running inside it. The caret is a block in normal and visual states and a bar in insert state, and the modeline shows the state.
@@ -1202,7 +1214,7 @@ No preset binds these. Run them from the palette or a menu, or bind them in =key
12021214| Messages (=app.messages=) | Lists the last 100 messages of the echo area (=view-echo-area-messages=). View ▸ Messages. |
12031215| Show Agenda or Files in Sidebar (=app.sidebar-agenda=) | Switches the sidebar between the files and the agenda, as the button at the right of its bar does. |
12041216| Verbatim, Code, Strike-Through (=org.emphasize.verbatim=, =org.emphasize.code=, =org.emphasize.strike-through=) | =org-emphasize= with ===, =~= or =+=. |
1205| Cancel Running Task (=app.babel.cancel=) | Stops the src block that is running, or an export or table recalculation running in Emacs. Edit ▸ Cancel Running Task, =⌘.=. |
1217| Cancel Running Task (=app.babel.cancel=) | Stops the user command or src block that is running, or an export or table recalculation running in Emacs. Edit ▸ Cancel Running Task, =⌘.=. |
12061218| Edit Config File (=app.edit-config=) | Opens =config.toml= in the editor. =⌥⌘,=. |
12071219| Import from Emacs… (=app.import-emacs=) | Opens Import from Emacs…. |
12081220| Revert to File on Disk (=app.revert=) | Replaces the buffer with the file on disk; unsaved changes go to recovery (=revert-buffer=). |
docs/manual/guide/13-configuration.org +3 −2 · view
@@ -23,6 +23,7 @@ The folder holds these files:
2323| =views.toml= | Saved agenda views | No |
2424| =macros.toml= | Named keyboard macros | Yes, when you name a macro |
2525| =snippets.toml= | Snippets and templates for new files | Only by Import from Emacs |
26| =commands.toml= | Your own commands; their code is in =commands/= beside it (see [[file:18-user-commands.org][User commands]]) | No |
2627| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch |
2728
2829=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. The [[file:17-command-line.org][orgstar command]] reads the same folder, =ORGSTAR_CONFIG_DIR= included. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way.
@@ -45,7 +46,7 @@ If =config.toml= has a line orgstar can't use, the problem shows in the message
4546- =config.toml: org-agenda-start-day must look like "-3d" or "+0d"=
4647- =config.toml: theme.light.background must be a color such as "#1f2328"=
4748
48A file that isn't valid TOML is reported with its parse error, and none of it applies. =keymap.toml=, =capture.toml=, =views.toml=, =macros.toml= and =snippets.toml= report their problems the same way when they are read.
49A file that isn't valid TOML is reported with its parse error, and none of it applies. =keymap.toml=, =capture.toml=, =views.toml=, =macros.toml=, =snippets.toml= and =commands.toml= report their problems the same way when they are read.
4950
5051* The Settings window
5152
@@ -435,7 +436,7 @@ Keys are letters, digits, =_= and =-=. Emacs import adds entries here; remove on
435436
436437** [key-bar]
437438
438The buttons of the key bar above the on-screen keyboard on iPhone and iPad, in order: =iphone= where the editor is narrow (iPhone, and iPad in Slide Over or a narrow split), =ipad= where it is wide. Each is a list of ids: the key bar's own buttons, or any command id from the Commands list, =org.snippet:<trigger>= for a snippet and =macro.named.<name>= for a named keyboard macro. A list may run over several lines.
439The buttons of the key bar above the on-screen keyboard on iPhone and iPad, in order: =iphone= where the editor is narrow (iPhone, and iPad in Slide Over or a narrow split), =ipad= where it is wide. Each is a list of ids: the key bar's own buttons, or any command id from the Commands list, =org.snippet:<trigger>= for a snippet, =macro.named.<name>= for a named keyboard macro and =user.<name>= for a user command. A list may run over several lines.
439440
440441#+BEGIN_SRC toml
441442[key-bar]
docs/manual/guide/14-ios.org +1 −1 · view
@@ -160,7 +160,7 @@ Bold, Italic and Code are in the edit menu of a selection, under Format: each pu
160160
161161*** Choosing the buttons
162162
163Settings ▸ Key Bar lists the bar's buttons in order. Drag a row by its handle to move it, tap the red minus to remove it, and tap Add Button… to add one from the Commands list, grouped as Commands groups it, with the bar's own buttons (Overview, Open Link, Bold, Italic, Code and the rest) first. Any command can be a button, as can a snippet and a named keyboard macro. Reset to Default brings back the buttons above. The iPhone and iPad tabs at the top choose the list: the iPhone buttons show where the editor is narrow, which includes iPad in Slide Over or a narrow split, and the iPad buttons where it is wide.
163Settings ▸ Key Bar lists the bar's buttons in order. Drag a row by its handle to move it, tap the red minus to remove it, and tap Add Button… to add one from the Commands list, grouped as Commands groups it, with the bar's own buttons (Overview, Open Link, Bold, Italic, Code and the rest) first. Any command can be a button, as can a snippet, a named keyboard macro and a user command (see [[file:18-user-commands.org][User commands]]). Reset to Default brings back the buttons above. The iPhone and iPad tabs at the top choose the list: the iPhone buttons show where the editor is narrow, which includes iPad in Slide Over or a narrow split, and the iPad buttons where it is wide.
164164
165165The lists are =[key-bar]= in the configuration folder's =config.toml= (see [[file:13-configuration.org][Configuration]]), so edits there apply too, and other devices using the folder share them. Without a configuration folder, they are kept on the device. An id the app doesn't know is reported in red under the folder in Settings, and skipped.
166166
docs/manual/guide/18-user-commands.org added +238 · view
@@ -0,0 +1,238 @@
1#+TITLE: User commands
2#+DESCRIPTION: Your own editing commands in JavaScript: commands.toml, the commands folder, the org API, trust, limits, and porting commands from Emacs Lisp.
3#+LEDE: Write your own editing commands in JavaScript. They run on the Mac and on iPhone and iPad, from the palette, keys and the key bar.
4
5* Overview
6
7A user command is a JavaScript function that reads the buffer it runs in and returns the changes to make. You declare it in =commands.toml= in the configuration folder and put its code in the =commands= folder beside it:
8
9#+BEGIN_EXAMPLE
10~/.config/orgstar/
11 commands.toml
12 commands/
13 headings.js
14 review.js
15#+END_EXAMPLE
16
17Each command gets the id =user.=/name/ and appears wherever commands do: the command palette, =keymap.toml= bindings, the Commands list on iPhone and iPad, and =[key-bar]=. Its changes are one step of undo. User commands are included in every version of orgstar; they don't need orgstar+.
18
19The download version, the Mac App Store version and the iOS app run the same commands with the same API, so a command works unchanged on every device the configuration folder reaches. On iPhone and iPad the folder is the one chosen in Settings (see [[file:14-ios.org][iPhone and iPad]]).
20
21* commands.toml
22
23#+BEGIN_SRC toml
24api = 1
25
26[[command]]
27name = "upcase-title" # the command user.upcase-title
28title = "Upcase Heading Title" # shown in the palette; default: the name
29file = "headings.js" # in commands/
30function = "upcaseTitle" # an exported function
31when = "heading" # optional; default: everywhere
32timeout = 5 # optional, seconds; default 2, at most 30
33
34[[command]]
35name = "weekly-review"
36title = "Add Weekly Review"
37file = "review.js"
38function = "weeklyReview"
39#+END_SRC
40
41| Key | Required | What it sets |
42|------------+----------+-----------------------------------------------------------------------------------------------------------------------------------------|
43| =api= | Yes | The API version the commands are written for, at the top of the file. This version of orgstar runs =1=. |
44| =name= | Yes | Letters, digits, =-= and =_=. The command's id is =user.=/name/. |
45| =title= | No | The title in the palette, the Commands list and key hints, shown as written. |
46| =file= | Yes | A =.js= or =.mjs= file in =commands/=, which may be in a subfolder (=lib/dates.js=). |
47| =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| =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
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.
52
53Problems are reported like those of the other configuration files (see [[file:13-configuration.org::*Problems in the files][Problems in the files]]), and the command with the problem isn't registered:
54
55- =commands.toml: command weekly-review: no file commands/review.js=
56- =commands.toml: command slow: timeout must be 1 to 30 seconds=
57- =commands.toml: command review: unknown context headline=
58- =commands.toml: api 2 needs a newer orgstar= (no command is registered)
59- =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)
61
62* The commands folder
63
64Files in =commands/= are ES modules. They may import each other by relative path (=import { pad } from "./lib/text.js"=) and nothing else: imports from other folders or URLs fail. Each run starts fresh, so nothing a command keeps in a variable survives to its next run, and a changed file is read again.
65
66The function is called with one argument, =org=, the API below. Its return value says what to change.
67
68* The API, version 1
69
70Every call returns a promise; use =await=. Offsets are UTF-16 code units, as JavaScript strings count them, so =text.slice(from, to)= gives the text between two offsets.
71
72| Call | Gives |
73|----------------------------+-----------------------------------------------------------------------------------------------------------------------------|
74| =org.text()= | The buffer's text when the command started. |
75| =org.selection()= | The selections as =[{from, to}]=, the main caret first. With nothing selected, =from= and =to= are both the caret. |
76| =org.heading(at)= | The heading whose entry holds the offset =at= (default: the caret), as described below, or =null= before the first heading. |
77| =org.outline()= | Every heading in the file, in order, as =org.heading()= describes it. |
78| =org.file()= | The file's path relative to its folder (=notes/plan.org=), or =null= for a buffer without a file. |
79| =org.settings()= | =todoKeywords=, =doneKeywords=, =priorities= (={highest, lowest, default}=), =fileTags=, =tags= (the tags used in your folders), =fillColumn= and =tagsColumn=. |
80| =org.prompt(options)= | Asks in the echo area (the Mac) or a sheet (iPhone and iPad) and gives the answer as a string. Throws when you cancel. |
81| =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("…")=. |
83| =org.version= | =1=. |
84
85A heading is an object with:
86
87| Field | Value |
88|--------------------------+---------------------------------------------------------------------------------------------------------|
89| =level= | The number of stars. |
90| =keyword=, =done= | The TODO keyword or =null=, and whether it is a done keyword. |
91| =priority= | The cookie's value (="A"=) or =null=. |
92| =title= | The title as written, without keyword, priority or tags. |
93| =tags= | The heading's own tags, without inherited ones. |
94| =start=, =end= | Where the heading line starts and where its subtree ends (the start of the next heading at its level or above, or the end of the file). |
95| =titleStart=, =titleEnd= | Where the title is. |
96| =scheduled=, =deadline=, =closed= | The planning line's timestamps as written (="<2026-11-30 Mon>"=), or =null=. |
97| =properties= | The property drawer as an object (={EFFORT: "1:00"}=). |
98
99=org.prompt= takes =message=, =initial= (text the answer starts with), =choices= (answers to complete from), =requireMatch= (the answer must be one of =choices=; default false) and =date= (ask for a date as Org's date prompt does, and give =YYYY-MM-DD= or =YYYY-MM-DD HH:MM=). =org.prompt("Week: ")= is short for =org.prompt({message: "Week: "})=.
100
101** The return value
102
103The function returns an object with any of these, or nothing:
104
105| Field | Value |
106|-------------+---------------------------------------------------------------------------------------------------------------------------------------------|
107| =edits= | A list of ={from, to, text}= in the text the command was given. =to= defaults to =from= (an insertion) and =text= to =""= (a deletion). Edits may not overlap or start at the same offset. |
108| =selection= | Where the caret or selection goes, in the text after the edits: an offset, ={from, to}=, or a list of them. Without it, the selection moves with the edits. |
109| =message= | Text for the echo area. |
110| =copy= | Text for the clipboard (the kill ring). |
111
112orgstar checks the edits before it makes any of them. An edit outside the text, edits that overlap, an edit that splits an emoji or other character in two, or an unknown field fail the command with a message such as =Add Weekly Review: edits overlap=, and nothing changes.
113
114The edits are applied together as one step of undo, and only if the buffer is as it was when the command started. If you type, or the file changes on disk, while the command runs or waits for a prompt, its result is refused with "The file changed; try again."
115
116* Examples
117
118=commands/headings.js= upcases the current heading's title:
119
120#+BEGIN_SRC js
121export async function upcaseTitle(org) {
122 const heading = await org.heading()
123 if (!heading) return org.fail("Not in an entry")
124 const text = await org.text()
125 const title = text.slice(heading.titleStart, heading.titleEnd)
126 return {
127 edits: [{ from: heading.titleStart, to: heading.titleEnd, text: title.toUpperCase() }],
128 message: `Upcased ${title}`,
129 }
130}
131#+END_SRC
132
133=commands/review.js= asks for a week and adds a child heading at the end of the current entry's subtree, with the caret after its stars:
134
135#+BEGIN_SRC js
136export async function weeklyReview(org) {
137 const heading = await org.heading()
138 if (!heading) return org.fail("Not on a heading")
139 const week = await org.prompt({ message: "Week: ", initial: "W48" })
140 const stars = "*".repeat(heading.level + 1)
141 return {
142 edits: [{ from: heading.end, to: heading.end, text: `${stars} Review ${week}\n` }],
143 selection: heading.end + stars.length + 1,
144 }
145}
146#+END_SRC
147
148=commands/outline.js= copies the path of the current entry, using the outline:
149
150#+BEGIN_SRC js
151export async function copyPath(org) {
152 const here = await org.heading()
153 if (!here) return org.fail("Not in an entry")
154 const outline = await org.outline()
155 const path = outline.filter(h => h.start <= here.start && h.end >= here.end).map(h => h.title).join(" / ")
156 return { copy: path, message: `Copied ${path}` }
157}
158#+END_SRC
159
160Bind a command like any other in =keymap.toml=:
161
162#+BEGIN_SRC toml
163[[bind]]
164keys = "C-c u"
165command = "user.upcase-title"
166#+END_SRC
167
168* Running a command
169
170Run a command from the palette, a key bound in =keymap.toml=, the Commands list on iPhone and iPad, or a key bar button (=[key-bar]= in =config.toml= takes =user.= ids). The echo area shows "Running /title/… (⌘. to cancel)" while it runs.
171
172** Trust
173
174The first time you run a command from a file, orgstar asks:
175
176#+BEGIN_EXAMPLE
177Run commands from commands/review.js?
178#+END_EXAMPLE
179
180A command can read and change the file you run it in, and nothing else (see [[*Limits][Limits]]). The answers are Run Once, Always and Don't Run:
181
182- Run Once runs it this time and asks again next time.
183- Always runs it and doesn't ask again while the file and every module it imports stay as they are.
184- Don't Run, or cancelling, runs nothing.
185
186Any 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]]).
187
188** Cancelling
189
190Edit ▸ 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.
191
192* Limits
193
194- *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.
195- *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh.
196- *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.
197- *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."
198- *Keyboard macros* don't wait for a user command to finish.
199- *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.
200
201* Compared with Emacs Lisp
202
203User commands cover the small interactive commands people keep in =init.el=: insert a dated heading, set a property from a prompt, toggle a tag, clean up a list, convert the region. They are written in JavaScript rather than Emacs Lisp, and the API is orgstar's, not Emacs's. Import from Emacs lists bindings to functions your configuration defines with =defun= as not imported, with a note pointing here.
204
205What Emacs Lisp has that user commands don't:
206
207- Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read.
208- Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead.
209- The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=, calling Org's own commands (=org-todo=, =org-schedule=). Read headings with =org.heading()= and =org.outline()=, and write the text yourself.
210- Other buffers and files, =find-file=, =with-temp-buffer=, capture from a command.
211- Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables.
212- =interactive= codes other than the prompts above; =C-u= prefix arguments.
213- Timers, processes and shell commands.
214
215** Porting table
216
217| Emacs Lisp | User command |
218|----------------------------------------------------+--------------------------------------------------------------------|
219| =(buffer-string)= | =await org.text()= |
220| =(point)=, =(region-beginning)=, =(region-end)= | =(await org.selection())[0]= |
221| =(org-get-heading t t t t)= | =(await org.heading()).title= |
222| =(org-get-todo-state)= | =(await org.heading()).keyword= |
223| =(org-get-tags nil t)= | =(await org.heading()).tags= |
224| =(org-entry-get nil "EFFORT")= | =(await org.heading()).properties.EFFORT= |
225| =(org-entry-get nil "SCHEDULED")= | =(await org.heading()).scheduled= |
226| =(org-map-entries …)= in the current file | =(await org.outline()).forEach(…)= |
227| =(org-end-of-subtree)= | =(await org.heading()).end= |
228| =(buffer-file-name)= | =await org.file()= |
229| =org-todo-keywords=, =org-tag-alist= | =(await org.settings()).todoKeywords=, =.tags= |
230| =(read-string "Week: " "W48")= | =await org.prompt({message: "Week: ", initial: "W48"})= |
231| =(completing-read "Tag: " tags nil t)= | =await org.prompt({message: "Tag: ", choices: tags, requireMatch: true})= |
232| =(org-read-date)= | =await org.prompt({message: "Date: ", date: true})= |
233| =(insert …)=, =(delete-region …)=, =(replace-match …)= | An entry in =edits= |
234| =(goto-char …)=, =(set-mark …)= | =selection= |
235| =(message …)= | =org.message(…)= or =message= |
236| =(user-error …)= | =return org.fail(…)= |
237| =(kill-new …)= | =copy= |
238| =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= |
docs/manual/index.org +1 · view
@@ -38,6 +38,7 @@ reminders, export and tangling.
383815. [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]]
393916. [[file:guide/16-flashcards.org][Flashcards]]
404017. [[file:guide/17-command-line.org][The command line]]
4118. [[file:guide/18-user-commands.org][User commands]]
4142
4243* Principles
4344
l10n/Localizable.xcstrings +350 · view
@@ -465,6 +465,41 @@
465465 }
466466 }
467467 },
468 "%@ canceled.": {
469 "comment": "A user command canceled with Cancel Running Task",
470 "localizations": {
471 "de": {
472 "stringUnit": {
473 "state": "translated",
474 "value": "Befehl %@ abgebrochen."
475 }
476 },
477 "es": {
478 "stringUnit": {
479 "state": "translated",
480 "value": "Comando %@ cancelado."
481 }
482 },
483 "fr": {
484 "stringUnit": {
485 "state": "translated",
486 "value": "Commande %@ annulée."
487 }
488 },
489 "ja": {
490 "stringUnit": {
491 "state": "translated",
492 "value": "コマンド「%@」をキャンセルしました。"
493 }
494 },
495 "pt-BR": {
496 "stringUnit": {
497 "state": "translated",
498 "value": "Comando %@ cancelado."
499 }
500 }
501 }
502 },
468503 "%@ changed on disk while saving, and the changes conflict with yours; both are in the editor between conflict markers.": {
469504 "localizations": {
470505 "de": {
@@ -499,6 +534,41 @@
499534 }
500535 }
501536 },
537 "%@ didn't finish within %lld s and was stopped.": {
538 "comment": "A user command passed its time limit",
539 "localizations": {
540 "de": {
541 "stringUnit": {
542 "state": "translated",
543 "value": "Befehl %1$@ wurde nicht innerhalb von %2$lld s fertig und wurde gestoppt."
544 }
545 },
546 "es": {
547 "stringUnit": {
548 "state": "translated",
549 "value": "El comando %1$@ no terminó en %2$lld s y se detuvo."
550 }
551 },
552 "fr": {
553 "stringUnit": {
554 "state": "translated",
555 "value": "La commande %1$@ ne s’est pas terminée en %2$lld s et a été arrêtée."
556 }
557 },
558 "ja": {
559 "stringUnit": {
560 "state": "translated",
561 "value": "コマンド「%1$@」は%2$lld秒以内に終わらなかったため停止しました。"
562 }
563 },
564 "pt-BR": {
565 "stringUnit": {
566 "state": "translated",
567 "value": "O comando %1$@ não terminou em %2$lld s e foi interrompido."
568 }
569 }
570 }
571 },
502572 "%@ doesn't contain %@.": {
503573 "comment": "Alert when the folder chosen to grant access doesn't contain the one needed",
504574 "localizations": {
@@ -608,6 +678,41 @@
608678 }
609679 }
610680 },
681 "%@ has decrypted entries, so user commands don't run in it.": {
682 "comment": "A user command refused in a buffer holding decrypted text",
683 "localizations": {
684 "de": {
685 "stringUnit": {
686 "state": "translated",
687 "value": "%@ enthält entschlüsselte Einträge, daher laufen eigene Befehle darin nicht."
688 }
689 },
690 "es": {
691 "stringUnit": {
692 "state": "translated",
693 "value": "%@ tiene entradas descifradas, así que los comandos propios no se ejecutan en él."
694 }
695 },
696 "fr": {
697 "stringUnit": {
698 "state": "translated",
699 "value": "%@ contient des entrées déchiffrées, les commandes personnelles ne s’y exécutent donc pas."
700 }
701 },
702 "ja": {
703 "stringUnit": {
704 "state": "translated",
705 "value": "%@ には復号されたエントリがあるため、ユーザーコマンドは実行されません。"
706 }
707 },
708 "pt-BR": {
709 "stringUnit": {
710 "state": "translated",
711 "value": "%@ tem entradas descriptografadas, então comandos do usuário não são executados nele."
712 }
713 }
714 }
715 },
611716 "%@ in %lld of %lld files": {
612717 "comment": "Lint All Folders: the number of problems, files with problems, files checked",
613718 "localizations": {
@@ -1330,6 +1435,41 @@
13301435 }
13311436 }
13321437 },
1438 "%@ was stopped: its web view ended, as when a command runs out of memory.": {
1439 "comment": "A user command whose web view ended",
1440 "localizations": {
1441 "de": {
1442 "stringUnit": {
1443 "state": "translated",
1444 "value": "Befehl %@ wurde gestoppt: Seine Web-Ansicht wurde beendet, etwa weil der Befehl keinen Speicher mehr hatte."
1445 }
1446 },
1447 "es": {
1448 "stringUnit": {
1449 "state": "translated",
1450 "value": "El comando %@ se detuvo: su vista web terminó, como ocurre cuando un comando se queda sin memoria."
1451 }
1452 },
1453 "fr": {
1454 "stringUnit": {
1455 "state": "translated",
1456 "value": "La commande %@ a été arrêtée : sa vue web s’est fermée, comme lorsqu’une commande manque de mémoire."
1457 }
1458 },
1459 "ja": {
1460 "stringUnit": {
1461 "state": "translated",
1462 "value": "コマンド「%@」は停止しました。メモリ不足のときなどと同じく、Webビューが終了しました。"
1463 }
1464 },
1465 "pt-BR": {
1466 "stringUnit": {
1467 "state": "translated",
1468 "value": "O comando %@ foi interrompido: sua visualização web terminou, como quando um comando fica sem memória."
1469 }
1470 }
1471 }
1472 },
13331473 "%@ wasn't synced: %@": {
13341474 "comment": "Working Copy sync; Working Copy's error follows",
13351475 "localizations": {
@@ -6212,6 +6352,41 @@
62126352 }
62136353 }
62146354 },
6355 "Always": {
6356 "comment": "Answer to the question before a user command runs",
6357 "localizations": {
6358 "de": {
6359 "stringUnit": {
6360 "state": "translated",
6361 "value": "Immer"
6362 }
6363 },
6364 "es": {
6365 "stringUnit": {
6366 "state": "translated",
6367 "value": "Siempre"
6368 }
6369 },
6370 "fr": {
6371 "stringUnit": {
6372 "state": "translated",
6373 "value": "Toujours"
6374 }
6375 },
6376 "ja": {
6377 "stringUnit": {
6378 "state": "translated",
6379 "value": "常に実行"
6380 }
6381 },
6382 "pt-BR": {
6383 "stringUnit": {
6384 "state": "translated",
6385 "value": "Sempre"
6386 }
6387 }
6388 }
6389 },
62156390 "An app that doesn't give its name": {
62166391 "localizations": {
62176392 "de": {
@@ -15930,6 +16105,41 @@
1593016105 }
1593116106 }
1593216107 },
16108 "Don't Run": {
16109 "comment": "Answer to the question before a user command runs",
16110 "localizations": {
16111 "de": {
16112 "stringUnit": {
16113 "state": "translated",
16114 "value": "Nicht ausführen"
16115 }
16116 },
16117 "es": {
16118 "stringUnit": {
16119 "state": "translated",
16120 "value": "No ejecutar"
16121 }
16122 },
16123 "fr": {
16124 "stringUnit": {
16125 "state": "translated",
16126 "value": "Ne pas exécuter"
16127 }
16128 },
16129 "ja": {
16130 "stringUnit": {
16131 "state": "translated",
16132 "value": "実行しない"
16133 }
16134 },
16135 "pt-BR": {
16136 "stringUnit": {
16137 "state": "translated",
16138 "value": "Não executar"
16139 }
16140 }
16141 }
16142 },
1593316143 "Don't Save": {
1593416144 "localizations": {
1593516145 "de": {
@@ -41654,6 +41864,41 @@
4165441864 }
4165541865 }
4165641866 },
41867 "Run Once": {
41868 "comment": "Answer to the question before a user command runs",
41869 "localizations": {
41870 "de": {
41871 "stringUnit": {
41872 "state": "translated",
41873 "value": "Einmal ausführen"
41874 }
41875 },
41876 "es": {
41877 "stringUnit": {
41878 "state": "translated",
41879 "value": "Ejecutar una vez"
41880 }
41881 },
41882 "fr": {
41883 "stringUnit": {
41884 "state": "translated",
41885 "value": "Exécuter une fois"
41886 }
41887 },
41888 "ja": {
41889 "stringUnit": {
41890 "state": "translated",
41891 "value": "1回だけ実行"
41892 }
41893 },
41894 "pt-BR": {
41895 "stringUnit": {
41896 "state": "translated",
41897 "value": "Executar uma vez"
41898 }
41899 }
41900 }
41901 },
4165741902 "Run Source Block": {
4165841903 "comment": "Command title",
4165941904 "localizations": {
@@ -41723,6 +41968,41 @@
4172341968 }
4172441969 }
4172541970 },
41971 "Run commands from %@?": {
41972 "comment": "Asked before a user command from a file not yet trusted on this device runs",
41973 "localizations": {
41974 "de": {
41975 "stringUnit": {
41976 "state": "translated",
41977 "value": "Befehle aus %@ ausführen?"
41978 }
41979 },
41980 "es": {
41981 "stringUnit": {
41982 "state": "translated",
41983 "value": "¿Ejecutar comandos de %@?"
41984 }
41985 },
41986 "fr": {
41987 "stringUnit": {
41988 "state": "translated",
41989 "value": "Exécuter les commandes de %@ ?"
41990 }
41991 },
41992 "ja": {
41993 "stringUnit": {
41994 "state": "translated",
41995 "value": "%@ のコマンドを実行しますか?"
41996 }
41997 },
41998 "pt-BR": {
41999 "stringUnit": {
42000 "state": "translated",
42001 "value": "Executar comandos de %@?"
42002 }
42003 }
42004 }
42005 },
4172642006 "Run this %@ block? (%@)": {
4172742007 "comment": "Echo area prompt: the block's language, then the answers it accepts (yes, no, always), which stay in English",
4172842008 "localizations": {
@@ -41792,6 +42072,76 @@
4179242072 }
4179342073 }
4179442074 },
42075 "Running %@…": {
42076 "comment": "A user command started on iPhone and iPad",
42077 "localizations": {
42078 "de": {
42079 "stringUnit": {
42080 "state": "translated",
42081 "value": "%@ wird ausgeführt …"
42082 }
42083 },
42084 "es": {
42085 "stringUnit": {
42086 "state": "translated",
42087 "value": "Ejecutando %@…"
42088 }
42089 },
42090 "fr": {
42091 "stringUnit": {
42092 "state": "translated",
42093 "value": "Exécution de %@…"
42094 }
42095 },
42096 "ja": {
42097 "stringUnit": {
42098 "state": "translated",
42099 "value": "%@を実行中…"
42100 }
42101 },
42102 "pt-BR": {
42103 "stringUnit": {
42104 "state": "translated",
42105 "value": "Executando %@…"
42106 }
42107 }
42108 }
42109 },
42110 "Running %@… (⌘. to cancel)": {
42111 "comment": "A user command started",
42112 "localizations": {
42113 "de": {
42114 "stringUnit": {
42115 "state": "translated",
42116 "value": "%@ wird ausgeführt … (⌘. zum Abbrechen)"
42117 }
42118 },
42119 "es": {
42120 "stringUnit": {
42121 "state": "translated",
42122 "value": "Ejecutando %@… (⌘. para cancelar)"
42123 }
42124 },
42125 "fr": {
42126 "stringUnit": {
42127 "state": "translated",
42128 "value": "Exécution de %@… (⌘. pour annuler)"
42129 }
42130 },
42131 "ja": {
42132 "stringUnit": {
42133 "state": "translated",
42134 "value": "%@を実行中…(⌘.でキャンセル)"
42135 }
42136 },
42137 "pt-BR": {
42138 "stringUnit": {
42139 "state": "translated",
42140 "value": "Executando %@… (⌘. para cancelar)"
42141 }
42142 }
42143 }
42144 },
4179542145 "S: %@": {
4179642146 "localizations": {
4179742147 "de": {
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