User commands: org.run and keyboard macros !528
17 files changed, +730 −72
Changed files (17)
- Sources/OrgApp/CommandHost.swift +1
- Sources/OrgApp/DocumentSession.swift +49 −14
- Sources/OrgCore/Commands/UserCommandAPI.swift +115
- Sources/OrgCore/Keymap/KeyboardMacros.swift +32
- Sources/OrgEditorAppKit/OrgEditor+Macros.swift +76 −17
- Sources/OrgEditorAppKit/OrgEditor.swift +10
- Sources/Orgstar/ContentView.swift +17 −7
- Sources/Orgstar/OrgstarApp.swift +2
- Sources/Orgstar/PaneView.swift +1
- Sources/OrgstarMobile/EditorScreen.swift +17 −9
- Sources/OrgstarMobile/MobileEditor+Macros.swift +75 −16
- Sources/OrgstarMobile/MobileEditor.swift +8 −3
- Tests/OrgAppTests/UserCommandRunTests.swift +170
- Tests/OrgCoreTests/UserCommandTests.swift +36
- Tests/OrgEditorAppKitTests/MacroTests.swift +81
- docs/manual/guide/03-keys.org +2
- docs/manual/guide/18-user-commands.org +38 −6
Sources/OrgApp/CommandHost.swift +1 · view
| @@ -423,6 +423,7 @@ public final class CommandHost { | |||
| 423 | settings: () => call("settings", null), | 423 | settings: () => call("settings", null), |
| 424 | prompt: options => call("prompt", typeof options === "string" ? { message: options } : options ?? {}), | 424 | prompt: options => call("prompt", typeof options === "string" ? { message: options } : options ?? {}), |
| 425 | message: text => call("message", String(text)), | 425 | message: text => call("message", String(text)), |
| 426 | run: id => call("run", String(id)), | ||
| 426 | fail, | 427 | fail, |
| 427 | }); | 428 | }); |
| 428 | } | 429 | } |
Sources/OrgApp/DocumentSession.swift +49 −14 · view
| @@ -1491,10 +1491,12 @@ public final class DocumentSession { | |||
| 1491 | 1491 | ||
| 1492 | /// Runs a user command on the focused buffer in the background, with `context` the editor's | 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 | 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`. | 1494 | /// the file's path relative to its folder, for `org.file()`. Prompts go to `ask`. `finished` |
| 1495 | /// gets the message once the command has ended, nil when its result was applied. | ||
| 1495 | public func startUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?, | 1496 | public func startUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?, |
| 1496 | ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void, | 1497 | ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void, |
| 1497 | report: @escaping @MainActor (String) -> Void) { | 1498 | report: @escaping @MainActor (String) -> Void, |
| 1499 | finished: @escaping @MainActor (String?) -> Void = { _ in }) { | ||
| 1498 | userCommandTask?.cancel() | 1500 | userCommandTask?.cancel() |
| 1499 | isRunningUserCommand = true | 1501 | isRunningUserCommand = true |
| 1500 | let task = Task { await runUserCommand(request, context: context, file: file, ask: ask, report: report) } | 1502 | let task = Task { await runUserCommand(request, context: context, file: file, ask: ask, report: report) } |
| @@ -1506,6 +1508,7 @@ public final class DocumentSession { | |||
| 1506 | isRunningUserCommand = false | 1508 | isRunningUserCommand = false |
| 1507 | } | 1509 | } |
| 1508 | if let message { report(message) } | 1510 | if let message { report(message) } |
| 1511 | finished(message) | ||
| 1509 | } | 1512 | } |
| 1510 | } | 1513 | } |
| 1511 | 1514 | ||
| @@ -1536,22 +1539,52 @@ public final class DocumentSession { | |||
| 1536 | final class State { | 1539 | final class State { |
| 1537 | var failure: String? | 1540 | var failure: String? |
| 1538 | var quit = false | 1541 | var quit = false |
| 1542 | /// `org.run("app.save")` ran. | ||
| 1543 | var save = false | ||
| 1544 | var buffer: UserCommandState | ||
| 1545 | init(_ buffer: UserCommandState) { self.buffer = buffer } | ||
| 1546 | } | ||
| 1547 | let state = State(UserCommandState( | ||
| 1548 | EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection, | ||
| 1549 | now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags), | ||
| 1550 | defaults: entry.buffer.document.defaults)) | ||
| 1551 | /// The answer to `prompt`; a canceled prompt throws. | ||
| 1552 | func reply(to prompt: Prompt) async throws -> String { | ||
| 1553 | try await withCheckedThrowingContinuation { continuation in | ||
| 1554 | ask(prompt) { answer in | ||
| 1555 | guard let answer else { | ||
| 1556 | state.quit = true | ||
| 1557 | return continuation.resume(throwing: CommandHost.Failure.script("Quit")) | ||
| 1558 | } | ||
| 1559 | continuation.resume(returning: answer) | ||
| 1560 | } | ||
| 1561 | } | ||
| 1539 | } | 1562 | } |
| 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 | 1563 | host.calls = { name, value in |
| 1544 | if let answer = UserCommandAPI.answer(name, value, context: context, file: file) { return answer } | 1564 | if let answer = UserCommandAPI.answer(name, value, context: state.buffer.context, file: file) { return answer } |
| 1545 | switch name { | 1565 | switch name { |
| 1546 | case "prompt": | 1566 | case "prompt": |
| 1547 | let prompt = UserCommandAPI.prompt(value) | 1567 | let prompt = UserCommandAPI.prompt(value) |
| 1548 | return try await withCheckedThrowingContinuation { continuation in | 1568 | return UserCommandAPI.answer(try await reply(to: prompt), to: prompt, now: Date(), calendar: state.buffer.context.calendar) |
| 1549 | ask(prompt) { answer in | 1569 | case "run": |
| 1550 | guard let answer else { | 1570 | let id = value as? String ?? "" |
| 1551 | state.quit = true | 1571 | if UserCommandAPI.safeAppCommands.contains(id) { |
| 1552 | return continuation.resume(throwing: CommandHost.Failure.script("Quit")) | 1572 | state.save = true |
| 1553 | } | 1573 | return state.buffer.reply |
| 1554 | continuation.resume(returning: UserCommandAPI.answer(answer, to: prompt, now: Date(), calendar: context.calendar)) | 1574 | } |
| 1575 | let command: any OrgCommand | ||
| 1576 | switch UserCommandAPI.builtIn(id) { | ||
| 1577 | case .success(let found): command = found | ||
| 1578 | case .failure(let problem): throw CommandHost.Failure.script(problem.message) | ||
| 1579 | } | ||
| 1580 | // A built-in command's prompts go through the same prompt as the command's own. | ||
| 1581 | var answers: [String: String] = [:] | ||
| 1582 | while true { | ||
| 1583 | switch state.buffer.run(command, answers: answers) { | ||
| 1584 | case .commit: return state.buffer.reply | ||
| 1585 | case .failed(let message): throw CommandHost.Failure.script(message) | ||
| 1586 | case .external: throw CommandHost.Failure.script(UserCommandAPI.external(id).message) | ||
| 1587 | case .prompt(let prompt): answers[prompt.key] = try await reply(to: prompt) | ||
| 1555 | } | 1588 | } |
| 1556 | } | 1589 | } |
| 1557 | case "message": | 1590 | case "message": |
| @@ -1581,13 +1614,15 @@ public final class DocumentSession { | |||
| 1581 | } | 1614 | } |
| 1582 | if let failure = state.failure { return failure } | 1615 | 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") } | 1616 | guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") } |
| 1584 | switch UserCommandAPI.result(json, in: context) { | 1617 | switch state.buffer.result(json) { |
| 1585 | case .failure(let problem): | 1618 | case .failure(let problem): |
| 1586 | return "\(command.title): \(problem.message)" | 1619 | return "\(command.title): \(problem.message)" |
| 1587 | case .success(let result): | 1620 | case .success(let result): |
| 1588 | guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the command finished." } | 1621 | 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 } | 1622 | if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message } |
| 1590 | if !result.edits.isEmpty { changed(entry) } | 1623 | if !result.edits.isEmpty { changed(entry) } |
| 1624 | // A save that fails shows why, as Save does. | ||
| 1625 | if state.save { save(entry) } | ||
| 1591 | return nil | 1626 | return nil |
| 1592 | } | 1627 | } |
| 1593 | #else | 1628 | #else |
Sources/OrgCore/Commands/UserCommandAPI.swift +115 · view
| @@ -205,4 +205,119 @@ public enum UserCommandAPI { | |||
| 205 | let day = String(format: "%04d-%02d-%02d", read.year, read.month, read.day) | 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 | 206 | return read.timeGiven ? day + String(format: " %02d:%02d", read.hour, read.minute) : day |
| 207 | } | 207 | } |
| 208 | |||
| 209 | // MARK: - org.run | ||
| 210 | |||
| 211 | /// The commands of the app `org.run` runs; it refuses the others. An entry may not need a | ||
| 212 | /// window, a sheet or another file, and may not change the text. | ||
| 213 | public static let safeAppCommands: Set<String> = [ | ||
| 214 | // Writes the buffer to its own file, as the person's own save would, once the command's | ||
| 215 | // changes are applied; nothing is saved when the command fails. | ||
| 216 | "app.save", | ||
| 217 | ] | ||
| 218 | |||
| 219 | /// The built-in command `org.run(id)` runs, or why it doesn't run `id`. `safeAppCommands` | ||
| 220 | /// are the caller's to handle. | ||
| 221 | public static func builtIn(_ id: String) -> Result<any OrgCommand, Problem> { | ||
| 222 | if id.hasPrefix(UserCommands.commandPrefix) { return .failure(Problem("A user command can't run another: \(id)")) } | ||
| 223 | if id.hasPrefix("app.") { return .failure(Problem("\(id) is a command of the app, which user commands can't run")) } | ||
| 224 | guard let command = Commands.command(id) else { return .failure(Problem("No built-in command \(id)")) } | ||
| 225 | return .success(command) | ||
| 226 | } | ||
| 227 | |||
| 228 | /// Why `org.run(id)` refused a command that asked for work outside the text. | ||
| 229 | public static func external(_ id: String) -> Problem { | ||
| 230 | Problem("\(id) needs work outside the text here (code blocks, Emacs, links, tangling or a view), which org.run doesn't do") | ||
| 231 | } | ||
| 232 | } | ||
| 233 | |||
| 234 | /// The buffer as a running user command sees it: the text it started with, changed by the | ||
| 235 | /// built-in commands it ran with `org.run`. Calls read the current text, the command's | ||
| 236 | /// returned edits are in it, and the result is one change from the starting text. | ||
| 237 | public struct UserCommandState: Sendable { | ||
| 238 | /// The context the command started with. | ||
| 239 | public let start: EditContext | ||
| 240 | /// The text and selection now. | ||
| 241 | public private(set) var context: EditContext | ||
| 242 | let defaults: OrgSettings | ||
| 243 | /// Effects of the commands run that the result keeps: those without offsets. | ||
| 244 | private var effects: [Effect] = [] | ||
| 245 | /// Whether a built-in command ran. | ||
| 246 | private var ran = false | ||
| 247 | |||
| 248 | /// `defaults` are the settings the buffer's tree was parsed with. | ||
| 249 | public init(_ start: EditContext, defaults: OrgSettings) { | ||
| 250 | self.start = start | ||
| 251 | context = start | ||
| 252 | self.defaults = defaults | ||
| 253 | } | ||
| 254 | |||
| 255 | /// Runs `command` at the current text and selection. A commit becomes the current state. | ||
| 256 | public mutating func run(_ command: any OrgCommand, answers: [String: String]) -> CommandStep { | ||
| 257 | let current = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: context.selection, | ||
| 258 | now: context.now, calendar: context.calendar, answers: answers, options: context.options, | ||
| 259 | knownTags: context.knownTags) | ||
| 260 | let step = command.run(in: current) | ||
| 261 | guard case .commit(let result) = step else { return step } | ||
| 262 | var text = context.text | ||
| 263 | var tree = context.tree | ||
| 264 | for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { | ||
| 265 | tree = OrgParser.reparse(tree, oldText: text, edit: edit, defaults: defaults) | ||
| 266 | text = edit.apply(to: text) | ||
| 267 | } | ||
| 268 | var options = context.options | ||
| 269 | for effect in result.effects { | ||
| 270 | switch effect { | ||
| 271 | case .fold, .sparseTree, .snippet: continue | ||
| 272 | case .timer(let timer): options.timer = timer | ||
| 273 | default: break | ||
| 274 | } | ||
| 275 | effects.append(effect) | ||
| 276 | } | ||
| 277 | context = EditContext(revision: context.revision, text: text, tree: tree, | ||
| 278 | selection: result.selection ?? Self.map(context.selection, through: result.edits), | ||
| 279 | now: context.now, calendar: context.calendar, options: options, knownTags: context.knownTags) | ||
| 280 | ran = true | ||
| 281 | return step | ||
| 282 | } | ||
| 283 | |||
| 284 | /// What `org.run` resolves with: the text and the selections. | ||
| 285 | public var reply: [String: Any] { | ||
| 286 | ["text": context.text, "selection": context.selection.map(UserCommandAPI.range)] | ||
| 287 | } | ||
| 288 | |||
| 289 | /// The command's returned JSON, in the current text, as one result at the starting revision. | ||
| 290 | public func result(_ json: String) -> Result<EditResult, UserCommandAPI.Problem> { | ||
| 291 | let own: EditResult | ||
| 292 | switch UserCommandAPI.result(json, in: context) { | ||
| 293 | case .failure(let problem): return .failure(problem) | ||
| 294 | case .success(let result): own = result | ||
| 295 | } | ||
| 296 | guard ran else { return .success(own) } | ||
| 297 | var text = context.text | ||
| 298 | for edit in own.edits.reversed() { text = edit.apply(to: text) } | ||
| 299 | return .success(EditResult(baseRevision: start.revision, edits: TextEdit.between(start.text, text), | ||
| 300 | selection: own.selection ?? Self.map(context.selection, through: own.edits), | ||
| 301 | effects: effects + own.effects)) | ||
| 302 | } | ||
| 303 | |||
| 304 | /// Ranges moved by edits that don't overlap: an offset inside or at the end of a replaced | ||
| 305 | /// range, or at an insertion, moves past the replacement. | ||
| 306 | static func map(_ ranges: [Range<Int>], through edits: [TextEdit]) -> [Range<Int>] { | ||
| 307 | let sorted = edits.sorted { $0.range.lowerBound < $1.range.lowerBound } | ||
| 308 | func map(_ offset: Int) -> Int { | ||
| 309 | var shift = 0 | ||
| 310 | for edit in sorted { | ||
| 311 | let lower = edit.range.lowerBound, upper = edit.range.upperBound | ||
| 312 | if offset < lower || (offset == lower && upper > lower) { return offset + shift } | ||
| 313 | if offset <= upper { return lower + shift + edit.replacement.utf16.count } | ||
| 314 | shift += edit.replacement.utf16.count - edit.range.count | ||
| 315 | } | ||
| 316 | return offset + shift | ||
| 317 | } | ||
| 318 | return ranges.map { range in | ||
| 319 | let lower = map(range.lowerBound) | ||
| 320 | return lower..<max(lower, map(range.upperBound)) | ||
| 321 | } | ||
| 322 | } | ||
| 208 | } | 323 | } |
Sources/OrgCore/Keymap/KeyboardMacros.swift +32 · view
| @@ -106,6 +106,38 @@ public struct MacroRecorder: Sendable { | |||
| 106 | } | 106 | } |
| 107 | } | 107 | } |
| 108 | 108 | ||
| 109 | /// Work a replayed key started that the replay waits for before its next key, as a user | ||
| 110 | /// command running. It ends once, with the message it failed with or nil. | ||
| 111 | @MainActor | ||
| 112 | public final class MacroWait { | ||
| 113 | private var outcome: String?? | ||
| 114 | private var waiting: [CheckedContinuation<String?, Never>] = [] | ||
| 115 | |||
| 116 | public init() {} | ||
| 117 | |||
| 118 | public func finish(_ failure: String?) { | ||
| 119 | guard outcome == nil else { return } | ||
| 120 | outcome = .some(failure) | ||
| 121 | for continuation in waiting { continuation.resume(returning: failure) } | ||
| 122 | waiting = [] | ||
| 123 | } | ||
| 124 | |||
| 125 | /// The failure, once the work has ended. | ||
| 126 | public var value: String? { | ||
| 127 | get async { | ||
| 128 | if let outcome { return outcome } | ||
| 129 | return await withCheckedContinuation { waiting.append($0) } | ||
| 130 | } | ||
| 131 | } | ||
| 132 | } | ||
| 133 | |||
| 134 | /// Where a macro replay stopped: at its end, with the error that ended it or nil, or at work | ||
| 135 | /// it waits for. | ||
| 136 | public enum MacroStep { | ||
| 137 | case ended(String?) | ||
| 138 | case waiting(MacroWait) | ||
| 139 | } | ||
| 140 | |||
| 109 | /// Macros named with `kmacro-name-last-macro`, kept in `macros.toml` in the configuration | 141 | /// Macros named with `kmacro-name-last-macro`, kept in `macros.toml` in the configuration |
| 110 | /// folder. Each runs as the command `macro.named.<name>`, which `keymap.toml` can bind. | 142 | /// folder. Each runs as the command `macro.named.<name>`, which `keymap.toml` can bind. |
| 111 | public final class NamedMacros: @unchecked Sendable { | 143 | public final class NamedMacros: @unchecked Sendable { |
Sources/OrgEditorAppKit/OrgEditor+Macros.swift +76 −17 · view
| @@ -18,7 +18,7 @@ extension OrgEditor { | |||
| 18 | 18 | ||
| 19 | /// Asks through `onPrompt`, recording the answer while a macro records. While one replays, | 19 | /// Asks through `onPrompt`, recording the answer while a macro records. While one replays, |
| 20 | /// the answer comes from its keys. | 20 | /// the answer comes from its keys. |
| 21 | func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) { | 21 | public func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) { |
| 22 | if kmacroDepth > 0 { | 22 | if kmacroDepth > 0 { |
| 23 | guard let (answer, used) = MacroRecorder.reply(from: macroKeys) else { | 23 | guard let (answer, used) = MacroRecorder.reply(from: macroKeys) else { |
| 24 | // The rest of the macro doesn't answer it: it is the person's to answer. | 24 | // The rest of the macro doesn't answer it: it is the person's to answer. |
| @@ -112,36 +112,95 @@ extension OrgEditor { | |||
| 112 | 112 | ||
| 113 | /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a | 113 | /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a |
| 114 | /// round changes nothing. False when a command failed. | 114 | /// round changes nothing. False when a command failed. |
| 115 | /// A key that starts a user command leaves the replay waiting until the command has | ||
| 116 | /// finished; it goes on from there. | ||
| 115 | @discardableResult | 117 | @discardableResult |
| 116 | func playMacro(_ keys: [KeyChord], count: Int) -> Bool { | 118 | func playMacro(_ keys: [KeyChord], count: Int) -> Bool { |
| 117 | guard kmacroDepth < 20 else { | 119 | guard kmacroDepth < 20 else { |
| 118 | fail("Keyboard macros nest too deeply") | 120 | fail("Keyboard macros nest too deeply") |
| 119 | return false | 121 | return false |
| 120 | } | 122 | } |
| 121 | let outer = macroKeys | 123 | let replay = MacroReplay(keys: keys, count: count, outer: macroKeys) |
| 124 | let outermost = kmacroDepth == 0 | ||
| 122 | kmacroDepth += 1 | 125 | kmacroDepth += 1 |
| 123 | defer { | 126 | switch replayMacro(replay) { |
| 124 | kmacroDepth -= 1 | 127 | case .ended(let error): |
| 125 | macroKeys = outer | 128 | return error == nil |
| 126 | if kmacroDepth == 0 { macroError = nil } | 129 | case .waiting(let wait): |
| 130 | // A replay this one runs in waits for the rest of it. | ||
| 131 | let rest = resumeMacro(replay, after: wait) | ||
| 132 | if !outermost { macroWait = rest } | ||
| 133 | return true | ||
| 127 | } | 134 | } |
| 135 | } | ||
| 136 | |||
| 137 | /// Goes on with `replay` each time the work it waits for has finished. | ||
| 138 | private func resumeMacro(_ replay: MacroReplay, after wait: MacroWait) -> MacroWait { | ||
| 139 | let rest = MacroWait() | ||
| 140 | Task { [weak self] in | ||
| 141 | var wait = wait | ||
| 142 | while true { | ||
| 143 | let failure = await wait.value | ||
| 144 | guard let self else { return rest.finish("") } | ||
| 145 | if let failure, self.macroError == nil { self.macroError = failure } | ||
| 146 | switch self.replayMacro(replay) { | ||
| 147 | case .ended(let error): return rest.finish(error) | ||
| 148 | case .waiting(let next): wait = next | ||
| 149 | } | ||
| 150 | } | ||
| 151 | } | ||
| 152 | return rest | ||
| 153 | } | ||
| 154 | |||
| 155 | /// A macro being replayed: the rounds run, and the state the current round started from, | ||
| 156 | /// nil between rounds. | ||
| 157 | final class MacroReplay { | ||
| 158 | let keys: [KeyChord] | ||
| 159 | let count: Int | ||
| 160 | /// The keys left in the replay this one runs in. | ||
| 161 | let outer: [KeyChord] | ||
| 128 | var rounds = 0 | 162 | var rounds = 0 |
| 129 | var failed = false | 163 | var before: (Int, NSRange)? |
| 130 | while count == 0 ? rounds < 100_000 : rounds < count { | 164 | |
| 131 | rounds += 1 | 165 | init(keys: [KeyChord], count: Int, outer: [KeyChord]) { |
| 132 | let before = (document.revision, textView.selectedRange()) | 166 | self.keys = keys |
| 133 | macroKeys = keys | 167 | self.count = count |
| 168 | self.outer = outer | ||
| 169 | } | ||
| 170 | } | ||
| 171 | |||
| 172 | /// Feeds `replay`'s keys through `handleChord` until it ends with the error that stopped it, | ||
| 173 | /// nil when it ran through, or until a key leaves `macroWait` set: the replay waits for | ||
| 174 | /// that work and goes on with the next key. | ||
| 175 | private func replayMacro(_ replay: MacroReplay) -> MacroStep { | ||
| 176 | while true { | ||
| 177 | if replay.before == nil { | ||
| 178 | guard replay.count == 0 ? replay.rounds < 100_000 : replay.rounds < replay.count else { return endReplay(replay) } | ||
| 179 | replay.rounds += 1 | ||
| 180 | replay.before = (document.revision, textView.selectedRange()) | ||
| 181 | macroKeys = replay.keys | ||
| 182 | } | ||
| 134 | while !macroKeys.isEmpty, macroError == nil { | 183 | while !macroKeys.isEmpty, macroError == nil { |
| 135 | let key = macroKeys.removeFirst() | 184 | let key = macroKeys.removeFirst() |
| 185 | macroWait = nil | ||
| 136 | if !handleChord(key) { typeUnhandled(key) } | 186 | if !handleChord(key) { typeUnhandled(key) } |
| 187 | if let wait = macroWait { | ||
| 188 | macroWait = nil | ||
| 189 | return .waiting(wait) | ||
| 190 | } | ||
| 137 | } | 191 | } |
| 138 | if macroError != nil { | 192 | if macroError != nil { return endReplay(replay) } |
| 139 | failed = true | 193 | if replay.count == 0, let before = replay.before, before == (document.revision, textView.selectedRange()) { return endReplay(replay) } |
| 140 | break | 194 | replay.before = nil |
| 141 | } | ||
| 142 | if count == 0, before == (document.revision, textView.selectedRange()) { break } | ||
| 143 | } | 195 | } |
| 144 | return !failed | 196 | } |
| 197 | |||
| 198 | private func endReplay(_ replay: MacroReplay) -> MacroStep { | ||
| 199 | let error = macroError | ||
| 200 | kmacroDepth -= 1 | ||
| 201 | macroKeys = replay.outer | ||
| 202 | if kmacroDepth == 0 { macroError = nil } | ||
| 203 | return .ended(error) | ||
| 145 | } | 204 | } |
| 146 | 205 | ||
| 147 | /// A replayed key that `handleChord` left to the text system, which gets it as an event. | 206 | /// A replayed key that `handleChord` left to the text system, which gets it as an event. |
Sources/OrgEditorAppKit/OrgEditor.swift +10 · view
| @@ -401,6 +401,10 @@ public final class OrgEditor: NSObject { | |||
| 401 | public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)? | 401 | public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)? |
| 402 | /// Runs work outside the text, such as a table recalculation in Emacs. | 402 | /// Runs work outside the text, such as a table recalculation in Emacs. |
| 403 | public var onExternal: ((ExternalRequest) -> Void)? | 403 | public var onExternal: ((ExternalRequest) -> Void)? |
| 404 | /// Runs a user command, calling `finished` with its message once it has ended, nil when its | ||
| 405 | /// result was applied; a keyboard macro replaying waits for that. Without it, user commands | ||
| 406 | /// go to `onExternal`. | ||
| 407 | public var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)? | ||
| 404 | /// Tags used across the workspace, for tag completion. | 408 | /// Tags used across the workspace, for tag completion. |
| 405 | public var knownTags: @Sendable () -> [String] = { [] } | 409 | public var knownTags: @Sendable () -> [String] = { [] } |
| 406 | /// Answers completion's questions to the index; run off the main actor. | 410 | /// Answers completion's questions to the index; run off the main actor. |
| @@ -495,6 +499,8 @@ public final class OrgEditor: NSObject { | |||
| 495 | var macroKeys: [KeyChord] = [] | 499 | var macroKeys: [KeyChord] = [] |
| 496 | var kmacroDepth = 0 | 500 | var kmacroDepth = 0 |
| 497 | var macroError: String? | 501 | var macroError: String? |
| 502 | /// Work the last replayed key started, which the replay waits for. | ||
| 503 | var macroWait: MacroWait? | ||
| 498 | var macroRepeatKey: KeyChord? | 504 | var macroRepeatKey: KeyChord? |
| 499 | var commandKeys: [KeyChord]? | 505 | var commandKeys: [KeyChord]? |
| 500 | /// Named macros (`macros.toml`). | 506 | /// Named macros (`macros.toml`). |
| @@ -753,6 +759,10 @@ public final class OrgEditor: NSObject { | |||
| 753 | } | 759 | } |
| 754 | case .failed(let message): | 760 | case .failed(let message): |
| 755 | fail(message) | 761 | fail(message) |
| 762 | case .external(.userCommand(let request)) where onUserCommand != nil: | ||
| 763 | let wait = kmacroDepth > 0 ? MacroWait() : nil | ||
| 764 | macroWait = wait | ||
| 765 | onUserCommand?(request) { wait?.finish($0) } | ||
| 756 | case .external(let request): | 766 | case .external(let request): |
| 757 | if let onExternal { onExternal(request) } else { onMessage?(EmacsFallback.wording("This needs Emacs, which isn't available here.", "This isn't available here.")) } | 767 | if let onExternal { onExternal(request) } else { onMessage?(EmacsFallback.wording("This needs Emacs, which isn't available here.", "This isn't available here.")) } |
| 758 | case .prompt(let prompt): | 768 | case .prompt(let prompt): |
Sources/Orgstar/ContentView.swift +17 −7 · view
| @@ -364,6 +364,7 @@ struct ContentView: View { | |||
| 364 | .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings } | 364 | .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings } |
| 365 | .onAppear { | 365 | .onAppear { |
| 366 | commands.externalHandler = runExternal | 366 | commands.externalHandler = runExternal |
| 367 | commands.userCommandHandler = runUserCommand | ||
| 367 | commands.filesHandler = { attachActions.drop($0) } | 368 | commands.filesHandler = { attachActions.drop($0) } |
| 368 | commands.imageHandler = { attachActions.yankImage($0, ext: $1) } | 369 | commands.imageHandler = { attachActions.yankImage($0, ext: $1) } |
| 369 | #if APPSTORE | 370 | #if APPSTORE |
| @@ -1295,10 +1296,15 @@ struct ContentView: View { | |||
| 1295 | } | 1296 | } |
| 1296 | } | 1297 | } |
| 1297 | 1298 | ||
| 1298 | /// Runs a user command once its file is trusted on this device. | 1299 | /// Runs a user command once its file is trusted on this device; `finished` gets its message |
| 1299 | private func runUserCommand(_ request: UserCommandRequest) { | 1300 | /// once it has ended, nil when its result was applied. The command's prompts go through the |
| 1300 | guard let path = session.path, let modules = session.userCommands.folder else { return } | 1301 | /// editor, so keyboard macros record and replay their answers. |
| 1301 | if let refusal = session.refusesUserCommand(path) { return commands.show(refusal) } | 1302 | private func runUserCommand(_ request: UserCommandRequest, finished: @escaping @MainActor (String?) -> Void = { _ in }) { |
| 1303 | guard let path = session.path, let modules = session.userCommands.folder else { return finished("") } | ||
| 1304 | if let refusal = session.refusesUserCommand(path) { | ||
| 1305 | commands.show(refusal) | ||
| 1306 | return finished(refusal) | ||
| 1307 | } | ||
| 1302 | let ask: @MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void = { question, reply in | 1308 | let ask: @MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void = { question, reply in |
| 1303 | let answers = UserCommandTrust.Answer.allCases | 1309 | let answers = UserCommandTrust.Answer.allCases |
| 1304 | // The echo area's line can cut the path short, so the detail above it repeats it whole. | 1310 | // The echo area's line can cut the path short, so the detail above it repeats it whole. |
| @@ -1308,10 +1314,14 @@ struct ContentView: View { | |||
| 1308 | } | 1314 | } |
| 1309 | } | 1315 | } |
| 1310 | UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: { | 1316 | UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: { |
| 1311 | guard let context = commands.editor?.context() else { return } | 1317 | guard let editor = commands.editor else { return finished("") } |
| 1312 | commands.show(String(localized: "Running \(request.command.title)… (⌘. to cancel)", comment: "A user command started")) | 1318 | commands.show(String(localized: "Running \(request.command.title)… (⌘. to cancel)", comment: "A user command started")) |
| 1313 | session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: commands.ask) { commands.show($0) } | 1319 | session.startUserCommand(request, context: editor.context(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), |
| 1314 | }, refuse: { commands.show($0) }) | 1320 | ask: editor.ask, report: { commands.show($0) }, finished: finished) |
| 1321 | }, refuse: { | ||
| 1322 | commands.show($0) | ||
| 1323 | finished($0) | ||
| 1324 | }) | ||
| 1315 | } | 1325 | } |
| 1316 | 1326 | ||
| 1317 | /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does. | 1327 | /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does. |
Sources/Orgstar/OrgstarApp.swift +2 · view
| @@ -47,6 +47,8 @@ final class AppCommands { | |||
| 47 | var editorSettings = EditorSettings() | 47 | var editorSettings = EditorSettings() |
| 48 | /// Runs work outside the text (a table recalculation in Emacs); the main window sets it. | 48 | /// Runs work outside the text (a table recalculation in Emacs); the main window sets it. |
| 49 | var externalHandler: ((ExternalRequest) -> Void)? | 49 | var externalHandler: ((ExternalRequest) -> Void)? |
| 50 | /// Runs a user command and says when it has finished; the main window sets it. | ||
| 51 | var userCommandHandler: ((UserCommandRequest, @escaping @MainActor (String?) -> Void) -> Void)? | ||
| 50 | /// Files and images pasted or dropped on an editor; the main window sets them. | 52 | /// Files and images pasted or dropped on an editor; the main window sets them. |
| 51 | var filesHandler: (([URL]) -> Void)? | 53 | var filesHandler: (([URL]) -> Void)? |
| 52 | var imageHandler: ((Data, String) -> Void)? | 54 | var imageHandler: ((Data, String) -> Void)? |
Sources/Orgstar/PaneView.swift +1 · view
| @@ -128,6 +128,7 @@ struct PaneView: NSViewRepresentable { | |||
| 128 | session.reveal(offset) | 128 | session.reveal(offset) |
| 129 | } | 129 | } |
| 130 | editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) } | 130 | editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) } |
| 131 | editor.onUserCommand = { [weak commands] request, finished in commands?.userCommandHandler?(request, finished) } | ||
| 131 | editor.onFiles = { [weak commands] in commands?.filesHandler?($0) } | 132 | editor.onFiles = { [weak commands] in commands?.filesHandler?($0) } |
| 132 | editor.onImage = { [weak commands] in commands?.imageHandler?($0, $1) } | 133 | editor.onImage = { [weak commands] in commands?.imageHandler?($0, $1) } |
| 133 | editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } } | 134 | editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } } |
Sources/OrgstarMobile/EditorScreen.swift +17 −9 · view
| @@ -443,16 +443,24 @@ struct EditorScreen: View { | |||
| 443 | } | 443 | } |
| 444 | } | 444 | } |
| 445 | 445 | ||
| 446 | /// Runs a user command once its file is trusted on this device. | 446 | /// Runs a user command once its file is trusted on this device; `finished` gets its message |
| 447 | private func runUserCommand(_ request: UserCommandRequest) { | 447 | /// once it has ended, nil when its result was applied. The command's prompts go through the |
| 448 | guard let modules = session.userCommands.folder else { return } | 448 | /// editor, so keyboard macros record and replay their answers. |
| 449 | if let refusal = session.refusesUserCommand(path) { return message = refusal } | 449 | private func runUserCommand(_ request: UserCommandRequest, finished: @escaping @MainActor (String?) -> Void) { |
| 450 | let ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { prompt = PromptRequest(prompt: $0, reply: $1) } | 450 | guard let modules = session.userCommands.folder else { return finished("") } |
| 451 | if let refusal = session.refusesUserCommand(path) { | ||
| 452 | message = refusal | ||
| 453 | return finished(refusal) | ||
| 454 | } | ||
| 451 | UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: { trustRequest = TrustRequest(question: $0, reply: $1) }, run: { | 455 | UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: { trustRequest = TrustRequest(question: $0, reply: $1) }, run: { |
| 452 | guard let context = editor?.editContext() else { return } | 456 | guard let editor else { return finished("") } |
| 453 | message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad") | 457 | message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad") |
| 454 | session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: ask) { message = $0 } | 458 | session.startUserCommand(request, context: editor.editContext(), file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), |
| 455 | }, refuse: { message = $0 }) | 459 | ask: editor.ask, report: { message = $0 }, finished: finished) |
| 460 | }, refuse: { | ||
| 461 | message = $0 | ||
| 462 | finished($0) | ||
| 463 | }) | ||
| 456 | } | 464 | } |
| 457 | 465 | ||
| 458 | private func start() { | 466 | private func start() { |
| @@ -537,7 +545,7 @@ struct EditorScreen: View { | |||
| 537 | editor.onColumnView = { view in sheet = .columns(view) } | 545 | editor.onColumnView = { view in sheet = .columns(view) } |
| 538 | editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } } | 546 | editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } } |
| 539 | editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } } | 547 | editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } } |
| 540 | editor.onUserCommand = { request in runUserCommand(request) } | 548 | editor.onUserCommand = { request, finished in runUserCommand(request, finished: finished) } |
| 541 | editor.onRefreshSetup = { session.refreshSetup() } | 549 | editor.onRefreshSetup = { session.refreshSetup() } |
| 542 | editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) } | 550 | editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) } |
| 543 | editor.keymap = model.keymap | 551 | editor.keymap = model.keymap |
Sources/OrgstarMobile/MobileEditor+Macros.swift +75 −16 · view
| @@ -104,36 +104,95 @@ extension MobileEditor { | |||
| 104 | 104 | ||
| 105 | /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a | 105 | /// Feeds `keys` through `handleChord` `count` times, or with 0 until a command fails or a |
| 106 | /// round changes nothing. False when a command failed. | 106 | /// round changes nothing. False when a command failed. |
| 107 | /// A key that starts a user command leaves the replay waiting until the command has | ||
| 108 | /// finished; it goes on from there. | ||
| 107 | @discardableResult | 109 | @discardableResult |
| 108 | func playMacro(_ keys: [KeyChord], count: Int) -> Bool { | 110 | func playMacro(_ keys: [KeyChord], count: Int) -> Bool { |
| 109 | guard kmacroDepth < 20 else { | 111 | guard kmacroDepth < 20 else { |
| 110 | fail("Keyboard macros nest too deeply") | 112 | fail("Keyboard macros nest too deeply") |
| 111 | return false | 113 | return false |
| 112 | } | 114 | } |
| 113 | let outer = macroKeys | 115 | let replay = MacroReplay(keys: keys, count: count, outer: macroKeys) |
| 116 | let outermost = kmacroDepth == 0 | ||
| 114 | kmacroDepth += 1 | 117 | kmacroDepth += 1 |
| 115 | defer { | 118 | switch replayMacro(replay) { |
| 116 | kmacroDepth -= 1 | 119 | case .ended(let error): |
| 117 | macroKeys = outer | 120 | return error == nil |
| 118 | if kmacroDepth == 0 { macroError = nil } | 121 | case .waiting(let wait): |
| 122 | // A replay this one runs in waits for the rest of it. | ||
| 123 | let rest = resumeMacro(replay, after: wait) | ||
| 124 | if !outermost { macroWait = rest } | ||
| 125 | return true | ||
| 119 | } | 126 | } |
| 127 | } | ||
| 128 | |||
| 129 | /// Goes on with `replay` each time the work it waits for has finished. | ||
| 130 | private func resumeMacro(_ replay: MacroReplay, after wait: MacroWait) -> MacroWait { | ||
| 131 | let rest = MacroWait() | ||
| 132 | Task { [weak self] in | ||
| 133 | var wait = wait | ||
| 134 | while true { | ||
| 135 | let failure = await wait.value | ||
| 136 | guard let self else { return rest.finish("") } | ||
| 137 | if let failure, self.macroError == nil { self.macroError = failure } | ||
| 138 | switch self.replayMacro(replay) { | ||
| 139 | case .ended(let error): return rest.finish(error) | ||
| 140 | case .waiting(let next): wait = next | ||
| 141 | } | ||
| 142 | } | ||
| 143 | } | ||
| 144 | return rest | ||
| 145 | } | ||
| 146 | |||
| 147 | /// A macro being replayed: the rounds run, and the state the current round started from, | ||
| 148 | /// nil between rounds. | ||
| 149 | final class MacroReplay { | ||
| 150 | let keys: [KeyChord] | ||
| 151 | let count: Int | ||
| 152 | /// The keys left in the replay this one runs in. | ||
| 153 | let outer: [KeyChord] | ||
| 120 | var rounds = 0 | 154 | var rounds = 0 |
| 121 | var failed = false | 155 | var before: (Int, NSRange)? |
| 122 | while count == 0 ? rounds < 100_000 : rounds < count { | 156 | |
| 123 | rounds += 1 | 157 | init(keys: [KeyChord], count: Int, outer: [KeyChord]) { |
| 124 | let before = (document.revision, textView.selectedRange) | 158 | self.keys = keys |
| 125 | macroKeys = keys | 159 | self.count = count |
| 160 | self.outer = outer | ||
| 161 | } | ||
| 162 | } | ||
| 163 | |||
| 164 | /// Feeds `replay`'s keys through `handleChord` until it ends with the error that stopped it, | ||
| 165 | /// nil when it ran through, or until a key leaves `macroWait` set: the replay waits for | ||
| 166 | /// that work and goes on with the next key. | ||
| 167 | private func replayMacro(_ replay: MacroReplay) -> MacroStep { | ||
| 168 | while true { | ||
| 169 | if replay.before == nil { | ||
| 170 | guard replay.count == 0 ? replay.rounds < 100_000 : replay.rounds < replay.count else { return endReplay(replay) } | ||
| 171 | replay.rounds += 1 | ||
| 172 | replay.before = (document.revision, textView.selectedRange) | ||
| 173 | macroKeys = replay.keys | ||
| 174 | } | ||
| 126 | while !macroKeys.isEmpty, macroError == nil { | 175 | while !macroKeys.isEmpty, macroError == nil { |
| 127 | let key = macroKeys.removeFirst() | 176 | let key = macroKeys.removeFirst() |
| 177 | macroWait = nil | ||
| 128 | if !handleChord(key) { typeUnhandled(key) } | 178 | if !handleChord(key) { typeUnhandled(key) } |
| 179 | if let wait = macroWait { | ||
| 180 | macroWait = nil | ||
| 181 | return .waiting(wait) | ||
| 182 | } | ||
| 129 | } | 183 | } |
| 130 | if macroError != nil { | 184 | if macroError != nil { return endReplay(replay) } |
| 131 | failed = true | 185 | if replay.count == 0, let before = replay.before, before == (document.revision, textView.selectedRange) { return endReplay(replay) } |
| 132 | break | 186 | replay.before = nil |
| 133 | } | ||
| 134 | if count == 0, before == (document.revision, textView.selectedRange) { break } | ||
| 135 | } | 187 | } |
| 136 | return !failed | 188 | } |
| 189 | |||
| 190 | private func endReplay(_ replay: MacroReplay) -> MacroStep { | ||
| 191 | let error = macroError | ||
| 192 | kmacroDepth -= 1 | ||
| 193 | macroKeys = replay.outer | ||
| 194 | if kmacroDepth == 0 { macroError = nil } | ||
| 195 | return .ended(error) | ||
| 137 | } | 196 | } |
| 138 | 197 | ||
| 139 | /// A replayed key that `handleChord` left to the text system: typed here. | 198 | /// A replayed key that `handleChord` left to the text system: typed here. |
Sources/OrgstarMobile/MobileEditor.swift +8 −3 · view
| @@ -77,6 +77,8 @@ final class MobileEditor: NSObject, DocumentBuffer { | |||
| 77 | var macroKeys: [KeyChord] = [] | 77 | var macroKeys: [KeyChord] = [] |
| 78 | var kmacroDepth = 0 | 78 | var kmacroDepth = 0 |
| 79 | var macroError: String? | 79 | var macroError: String? |
| 80 | /// Work the last replayed key started, which the replay waits for. | ||
| 81 | var macroWait: MacroWait? | ||
| 80 | var macroRepeatKey: KeyChord? | 82 | var macroRepeatKey: KeyChord? |
| 81 | var commandKeys: [KeyChord]? | 83 | var commandKeys: [KeyChord]? |
| 82 | /// Named macros (`macros.toml`). | 84 | /// Named macros (`macros.toml`). |
| @@ -124,8 +126,9 @@ final class MobileEditor: NSObject, DocumentBuffer { | |||
| 124 | var onTangle: ((Tangle.Scope) -> Void)? | 126 | var onTangle: ((Tangle.Scope) -> Void)? |
| 125 | /// A source block to run (C-c C-c). | 127 | /// A source block to run (C-c C-c). |
| 126 | var onBabel: ((BabelJob) -> Void)? | 128 | var onBabel: ((BabelJob) -> Void)? |
| 127 | /// A user command to run. | 129 | /// A user command to run; `finished` gets its message once it has ended, nil when its result |
| 128 | var onUserCommand: ((UserCommandRequest) -> Void)? | 130 | /// was applied, and a keyboard macro replaying waits for that. |
| 131 | var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)? | ||
| 129 | /// The file's setup files to read again (C-c C-c on a keyword line). | 132 | /// The file's setup files to read again (C-c C-c on a keyword line). |
| 130 | var onRefreshSetup: (() -> Void)? | 133 | var onRefreshSetup: (() -> Void)? |
| 131 | /// A block, a table's formulas or a field to edit apart (C-c ', C-c `). | 134 | /// A block, a table's formulas or a field to edit apart (C-c ', C-c `). |
| @@ -411,7 +414,9 @@ final class MobileEditor: NSObject, DocumentBuffer { | |||
| 411 | case .external(.babel(let job)) where onBabel != nil: | 414 | case .external(.babel(let job)) where onBabel != nil: |
| 412 | onBabel?(job) | 415 | onBabel?(job) |
| 413 | case .external(.userCommand(let request)) where onUserCommand != nil: | 416 | case .external(.userCommand(let request)) where onUserCommand != nil: |
| 414 | onUserCommand?(request) | 417 | let wait = kmacroDepth > 0 ? MacroWait() : nil |
| 418 | macroWait = wait | ||
| 419 | onUserCommand?(request) { wait?.finish($0) } | ||
| 415 | case .external(.tangle(let scope)) where onTangle != nil: | 420 | case .external(.tangle(let scope)) where onTangle != nil: |
| 416 | onTangle?(scope) | 421 | onTangle?(scope) |
| 417 | case .external(.agenda(let start, let count)) where onAgenda != nil: | 422 | case .external(.agenda(let start, let count)) where onAgenda != nil: |
Tests/OrgAppTests/UserCommandRunTests.swift +170 · view
| @@ -44,6 +44,37 @@ struct UserCommandRunTests { | |||
| 44 | name = "copy" | 44 | name = "copy" |
| 45 | file = "bad.js" | 45 | file = "bad.js" |
| 46 | function = "copy" | 46 | function = "copy" |
| 47 | |||
| 48 | [[command]] | ||
| 49 | name = "compose" | ||
| 50 | file = "run.js" | ||
| 51 | function = "compose" | ||
| 52 | |||
| 53 | [[command]] | ||
| 54 | name = "schedule" | ||
| 55 | file = "run.js" | ||
| 56 | function = "schedule" | ||
| 57 | |||
| 58 | [[command]] | ||
| 59 | name = "promote" | ||
| 60 | title = "Promote" | ||
| 61 | file = "run.js" | ||
| 62 | function = "promote" | ||
| 63 | |||
| 64 | [[command]] | ||
| 65 | name = "refused" | ||
| 66 | file = "run.js" | ||
| 67 | function = "refused" | ||
| 68 | |||
| 69 | [[command]] | ||
| 70 | name = "save" | ||
| 71 | file = "run.js" | ||
| 72 | function = "save" | ||
| 73 | |||
| 74 | [[command]] | ||
| 75 | name = "edit-while-running" | ||
| 76 | file = "run.js" | ||
| 77 | function = "editWhileRunning" | ||
| 47 | """ | 78 | """ |
| 48 | static let headings = """ | 79 | static let headings = """ |
| 49 | import { upper } from "./lib/text.js"; | 80 | import { upper } from "./lib/text.js"; |
| @@ -76,6 +107,48 @@ struct UserCommandRunTests { | |||
| 76 | export async function refuse(org) { await org.fail("Not today"); } | 107 | 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" }; } | 108 | export async function copy(org) { org.message("Copying"); return { copy: (await org.file()) ?? "none" }; } |
| 78 | """ | 109 | """ |
| 110 | static let builtIns = """ | ||
| 111 | export async function compose(org) { | ||
| 112 | await org.run("org.todo.cycle"); | ||
| 113 | await org.run("org.todo.cycle"); | ||
| 114 | const { text, selection: [{ from }] } = await org.run("org.heading.insert"); | ||
| 115 | if (text !== await org.text()) return org.fail("org.text() isn't the text org.run gave"); | ||
| 116 | return { edits: [{ from, text: "New" }] }; | ||
| 117 | } | ||
| 118 | export async function schedule(org) { | ||
| 119 | await org.run("org.schedule"); | ||
| 120 | await org.message((await org.heading()).scheduled); | ||
| 121 | } | ||
| 122 | export async function promote(org) { | ||
| 123 | try { | ||
| 124 | await org.run("org.heading.promote"); | ||
| 125 | } catch (error) { | ||
| 126 | org.message("caught " + error.message); | ||
| 127 | } | ||
| 128 | await org.run("org.heading.promote"); | ||
| 129 | } | ||
| 130 | export async function refused(org) { | ||
| 131 | const messages = []; | ||
| 132 | for (const id of ["app.export.html", "user.compose", "org.cycle", "org.babel.execute"]) { | ||
| 133 | try { | ||
| 134 | await org.run(id); | ||
| 135 | messages.push("ran " + id); | ||
| 136 | } catch (error) { | ||
| 137 | messages.push(error.message); | ||
| 138 | } | ||
| 139 | } | ||
| 140 | await org.message(messages.join(" | ")); | ||
| 141 | } | ||
| 142 | export async function save(org) { | ||
| 143 | await org.run("org.todo.cycle"); | ||
| 144 | const { text } = await org.run("app.save"); | ||
| 145 | await org.message(text.slice(0, 6)); | ||
| 146 | } | ||
| 147 | export async function editWhileRunning(org) { | ||
| 148 | await org.run("org.todo.cycle"); | ||
| 149 | await org.prompt("Go on? "); | ||
| 150 | } | ||
| 151 | """ | ||
| 79 | static let file = "* Plan the week :work:\nbody\n* Next\n" | 152 | static let file = "* Plan the week :work:\nbody\n* Next\n" |
| 80 | 153 | ||
| 81 | let config: Folder | 154 | let config: Folder |
| @@ -92,6 +165,7 @@ struct UserCommandRunTests { | |||
| 92 | try config.write("commands/lib/text.js", "export const upper = s => s.toUpperCase();\n") | 165 | try config.write("commands/lib/text.js", "export const upper = s => s.toUpperCase();\n") |
| 93 | try config.write("commands/review.js", Self.review) | 166 | try config.write("commands/review.js", Self.review) |
| 94 | try config.write("commands/bad.js", Self.bad) | 167 | try config.write("commands/bad.js", Self.bad) |
| 168 | try config.write("commands/run.js", Self.builtIns) | ||
| 95 | path = try notes.write("a.org", Self.file).path | 169 | path = try notes.write("a.org", Self.file).path |
| 96 | session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))) | 170 | session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))) |
| 97 | session.saveMode = .explicit | 171 | session.saveMode = .explicit |
| @@ -156,6 +230,102 @@ struct UserCommandRunTests { | |||
| 156 | #expect(reported == ["Copying"]) | 230 | #expect(reported == ["Copying"]) |
| 157 | } | 231 | } |
| 158 | 232 | ||
| 233 | // MARK: - org.run | ||
| 234 | |||
| 235 | /// The commands a script runs and its own edits after them are one undo step, with the text | ||
| 236 | /// and selection that running the same commands directly gives. | ||
| 237 | @Test func runningBuiltInsIsOneUndoStep() async throws { | ||
| 238 | let direct = StateBuffer(DocumentState(bytes: Array(Self.file.utf8))) | ||
| 239 | direct.selection = [4..<4] | ||
| 240 | for id in ["org.todo.cycle", "org.todo.cycle", "org.heading.insert"] { | ||
| 241 | guard case .commit = direct.perform(try #require(Commands.command(id)), now: Date(), answers: [:]) else { | ||
| 242 | Issue.record("\(id) didn't commit") | ||
| 243 | return | ||
| 244 | } | ||
| 245 | } | ||
| 246 | let caret = direct.selection[0].lowerBound | ||
| 247 | #expect(try await run("compose") == nil) | ||
| 248 | #expect(buffer.document.text == (direct.document.text as NSString).replacingCharacters(in: NSRange(location: caret, length: 0), with: "New")) | ||
| 249 | #expect(buffer.document.text.hasPrefix("* DONE Pl")) | ||
| 250 | #expect(buffer.selection == [caret + 3..<caret + 3]) | ||
| 251 | #expect(buffer.update { $0.undo() } != nil) | ||
| 252 | #expect(buffer.document.text == Self.file) | ||
| 253 | #expect(!buffer.document.canUndo) | ||
| 254 | } | ||
| 255 | |||
| 256 | /// A built-in command's prompt goes through the prompt the command's own prompts use. | ||
| 257 | @Test func aBuiltInsPromptGoesThroughThePrompt() async throws { | ||
| 258 | var asked: [Prompt] = [] | ||
| 259 | var reported: [String] = [] | ||
| 260 | let message = try await run("schedule", ask: { prompt, reply in | ||
| 261 | asked.append(prompt) | ||
| 262 | reply("2026-12-01") | ||
| 263 | }, report: { reported.append($0) }) | ||
| 264 | #expect(message == nil) | ||
| 265 | #expect(asked.count == 1 && asked.first?.key == "date" && asked.first?.date != nil) | ||
| 266 | let scheduled = "* Plan the week :work:\nSCHEDULED: <2026-12-01 Tue>\nbody\n* Next\n" | ||
| 267 | #expect(buffer.document.text == scheduled) | ||
| 268 | #expect(reported == ["<2026-12-01 Tue>"]) | ||
| 269 | // Canceling it ends the command with nothing changed. | ||
| 270 | #expect(try await run("schedule") == "Quit") | ||
| 271 | #expect(buffer.document.text == scheduled) | ||
| 272 | } | ||
| 273 | |||
| 274 | /// A failing built-in rejects with its message, which the script can catch. | ||
| 275 | @Test func aFailingBuiltInRejectsWithItsMessage() async throws { | ||
| 276 | let document = buffer.document | ||
| 277 | let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [4..<4]) | ||
| 278 | guard case .failed(let failure) = PromoteHeading().run(in: context) else { | ||
| 279 | Issue.record("promoting a level 1 heading didn't fail") | ||
| 280 | return | ||
| 281 | } | ||
| 282 | var reported: [String] = [] | ||
| 283 | #expect(try await run("promote", report: { reported.append($0) }) == "Promote: \(failure)") | ||
| 284 | #expect(reported == ["caught \(failure)"]) | ||
| 285 | #expect(buffer.document.text == Self.file) | ||
| 286 | } | ||
| 287 | |||
| 288 | /// Commands of the app other than the safe ones, user commands, the editor's own commands | ||
| 289 | /// and work outside the text are refused. | ||
| 290 | @Test func refusesWhatIsntABuiltInCommand() async throws { | ||
| 291 | let block = "#+begin_src sh\necho hi\n#+end_src\n" | ||
| 292 | _ = buffer.perform(ReplaceText(old: buffer.document.text, new: block), now: Date(), answers: [:]) | ||
| 293 | let document = buffer.document | ||
| 294 | let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [2..<2]) | ||
| 295 | guard case .external(.babel) = ExecuteSrcBlock().run(in: context) else { | ||
| 296 | Issue.record("the block doesn't run through Babel") | ||
| 297 | return | ||
| 298 | } | ||
| 299 | var reported: [String] = [] | ||
| 300 | #expect(try await run("refused", at: 2, report: { reported.append($0) }) == nil) | ||
| 301 | #expect(reported == [[ | ||
| 302 | "app.export.html is a command of the app, which user commands can't run", | ||
| 303 | "A user command can't run another: user.compose", | ||
| 304 | "No built-in command org.cycle", | ||
| 305 | UserCommandAPI.external("org.babel.execute").message, | ||
| 306 | ].joined(separator: " | ")]) | ||
| 307 | #expect(buffer.document.text == block) | ||
| 308 | } | ||
| 309 | |||
| 310 | /// `app.save` saves the file once the command's changes are applied. | ||
| 311 | @Test func saveRunsAfterTheChanges() async throws { | ||
| 312 | var reported: [String] = [] | ||
| 313 | #expect(try await run("save", report: { reported.append($0) }) == nil) | ||
| 314 | #expect(reported == ["* TODO"]) | ||
| 315 | #expect(buffer.document.text.hasPrefix("* TODO Plan")) | ||
| 316 | #expect(!buffer.document.isDirty) | ||
| 317 | #expect(try String(contentsOfFile: path, encoding: .utf8) == buffer.document.text) | ||
| 318 | } | ||
| 319 | |||
| 320 | @Test func anEditWhileRunningRefusesWhatItsCommandsDid() async throws { | ||
| 321 | let message = try await run("edit-while-running", ask: { [buffer] _, reply in | ||
| 322 | _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:]) | ||
| 323 | reply("yes") | ||
| 324 | }) | ||
| 325 | #expect(message == "The file changed; try again.") | ||
| 326 | #expect(buffer.document.text == Self.file + "typed\n") | ||
| 327 | } | ||
| 328 | |||
| 159 | @Test func cancelStopsTheCommand() async throws { | 329 | @Test func cancelStopsTheCommand() async throws { |
| 160 | let document = buffer.document | 330 | let document = buffer.document |
| 161 | let command = try #require(session.userCommands.command("user.loop")) | 331 | let command = try #require(session.userCommands.command("user.loop")) |
Tests/OrgCoreTests/UserCommandTests.swift +36 · view
| @@ -239,3 +239,39 @@ struct UserCommandAPITests { | |||
| 239 | #expect(UserCommandAPI.answer("+2d", to: prompt, now: now, calendar: utc) == "+2d") | 239 | #expect(UserCommandAPI.answer("+2d", to: prompt, now: now, calendar: utc) == "+2d") |
| 240 | } | 240 | } |
| 241 | } | 241 | } |
| 242 | |||
| 243 | struct UserCommandStateTests { | ||
| 244 | func context(_ text: String, caret: Int) -> EditContext { | ||
| 245 | EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) | ||
| 246 | } | ||
| 247 | |||
| 248 | /// Commands run one after another on the text the last one left; the command's own edits | ||
| 249 | /// are in that text, and the result is one change from the text it started with. | ||
| 250 | @Test func composesIntoOneResult() throws { | ||
| 251 | var state = UserCommandState(context("* a\n* b\n", caret: 2), defaults: .default) | ||
| 252 | guard case .commit = state.run(TodoCycle(), answers: [:]) else { Issue.record("no commit"); return } | ||
| 253 | #expect(state.context.text == "* TODO a\n* b\n") | ||
| 254 | #expect(state.context.selection == [7..<7]) | ||
| 255 | #expect(state.reply["text"] as? String == "* TODO a\n* b\n") | ||
| 256 | guard case .commit = state.run(NextHeading(), answers: [:]) else { Issue.record("no commit"); return } | ||
| 257 | let result = try state.result(#"{"edits": [{"from": 11, "text": "!"}]}"#).get() | ||
| 258 | #expect(result.baseRevision == 3) | ||
| 259 | #expect(result.edits.count == 1) | ||
| 260 | var text = state.start.text | ||
| 261 | for edit in result.edits.reversed() { text = edit.apply(to: text) } | ||
| 262 | #expect(text == "* TODO a\n* !b\n") | ||
| 263 | #expect(result.selection == [9..<9]) | ||
| 264 | } | ||
| 265 | |||
| 266 | @Test func refusesWhatIsntBuiltIn() { | ||
| 267 | func refusal(_ id: String) -> String? { | ||
| 268 | if case .failure(let problem) = UserCommandAPI.builtIn(id) { return problem.message } | ||
| 269 | return nil | ||
| 270 | } | ||
| 271 | #expect(refusal("org.todo.cycle") == nil) | ||
| 272 | #expect(refusal("app.export.html") == "app.export.html is a command of the app, which user commands can't run") | ||
| 273 | #expect(refusal("user.other") == "A user command can't run another: user.other") | ||
| 274 | #expect(refusal("org.cycle") == "No built-in command org.cycle") | ||
| 275 | #expect(UserCommandAPI.safeAppCommands == ["app.save"]) | ||
| 276 | } | ||
| 277 | } | ||
Tests/OrgEditorAppKitTests/MacroTests.swift +81 · view
| @@ -1,6 +1,7 @@ | |||
| 1 | import AppKit | 1 | import AppKit |
| 2 | import Foundation | 2 | import Foundation |
| 3 | import OrgCore | 3 | import OrgCore |
| 4 | import OrgDocument | ||
| 4 | import Testing | 5 | import Testing |
| 5 | @testable import OrgApp | 6 | @testable import OrgApp |
| 6 | @testable import OrgEditorAppKit | 7 | @testable import OrgEditorAppKit |
| @@ -237,6 +238,86 @@ struct MacroTests { | |||
| 237 | #expect(MacroRecorder.reply(from: KeySequence.parse("a")!) == nil) | 238 | #expect(MacroRecorder.reply(from: KeySequence.parse("a")!) == nil) |
| 238 | } | 239 | } |
| 239 | 240 | ||
| 241 | /// A keyboard macro records a user command's key and its prompt's answer; replaying waits | ||
| 242 | /// for the command to finish before the next key, and answers its prompt from the macro. | ||
| 243 | @Test func macrosWaitForUserCommands() async throws { | ||
| 244 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)") | ||
| 245 | defer { try? FileManager.default.removeItem(at: folder) } | ||
| 246 | let modules = folder.appendingPathComponent("config/commands") | ||
| 247 | try FileManager.default.createDirectory(at: modules, withIntermediateDirectories: true) | ||
| 248 | try Data(""" | ||
| 249 | export async function stamp(org) { | ||
| 250 | const word = await org.prompt("Word: "); | ||
| 251 | await new Promise(resolve => setTimeout(resolve, 100)); | ||
| 252 | const { selection: [{ from }] } = await org.run("org.todo.cycle"); | ||
| 253 | const heading = await org.heading(); | ||
| 254 | return { edits: [{ from: heading.titleEnd, text: " " + word }], selection: from }; | ||
| 255 | } | ||
| 256 | """.utf8).write(to: modules.appendingPathComponent("stamp.js")) | ||
| 257 | let file = folder.appendingPathComponent("a.org") | ||
| 258 | try Data("* one\n* two\n* three\n".utf8).write(to: file) | ||
| 259 | let shared = (UserCommands.shared.all, UserCommands.shared.folder) | ||
| 260 | defer { UserCommands.shared.replace(shared.0, folder: shared.1) } | ||
| 261 | UserCommands.shared.replace([UserCommand(name: "stamp", title: "Stamp", file: "stamp.js", function: "stamp")], folder: modules) | ||
| 262 | OrgEditor.kmacro = MacroRecorder() | ||
| 263 | defer { OrgEditor.kmacro = MacroRecorder() } | ||
| 264 | |||
| 265 | let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r"))) | ||
| 266 | session.saveMode = .explicit | ||
| 267 | session.userCommands = UserCommands.shared | ||
| 268 | session.open(file.path) | ||
| 269 | let h = Harness(try #require(session.document)) | ||
| 270 | h.editor.onChange = { [weak session] in session?.bufferChanged() } | ||
| 271 | session.attach(h.editor) | ||
| 272 | var problems: [String] = [] | ||
| 273 | let toml = "[[bind]]\nkeys = \"C-c u\"\ncommand = \"user.stamp\"\n[[bind]]\nkeys = \"C-c m\"\ncommand = \"macro.named.stamp\"\n" | ||
| 274 | let user = try Keymap(toml: toml, problems: &problems, commands: Set(EditorCommands.all.map(\.id) + ["macro.named.stamp"])) | ||
| 275 | h.editor.keymap = .layered([KeymapPreset.emacs.keymap, user]) | ||
| 276 | var asked = 0 | ||
| 277 | h.editor.onPrompt = { _, reply in | ||
| 278 | asked += 1 | ||
| 279 | reply("ok") | ||
| 280 | } | ||
| 281 | var messages: [String] = [] | ||
| 282 | h.editor.onMessage = { messages.append($0) } | ||
| 283 | h.editor.onUserCommand = { [weak session, weak h] request, finished in | ||
| 284 | guard let session, let h else { return } | ||
| 285 | session.startUserCommand(request, context: h.editor.context(), file: "a.org", ask: h.editor.ask, report: { messages.append($0) }, finished: finished) | ||
| 286 | } | ||
| 287 | func settled() async throws { | ||
| 288 | for _ in 0..<250 where session.isRunningUserCommand || h.editor.kmacroDepth > 0 { try await Task.sleep(for: .milliseconds(20)) } | ||
| 289 | #expect(!session.isRunningUserCommand && h.editor.kmacroDepth == 0) | ||
| 290 | } | ||
| 291 | h.caret(at: 2) | ||
| 292 | type(h, "C-x ( C-c u") | ||
| 293 | try await settled() | ||
| 294 | type(h, "C-n C-x )") | ||
| 295 | #expect(h.string == "* TODO one ok\n* two\n* three\n") | ||
| 296 | #expect(OrgEditor.kmacro.last == KeySequence.parse("C-c u o k RET C-n")) | ||
| 297 | #expect(asked == 1) | ||
| 298 | |||
| 299 | type(h, "C-u 2 C-x e") | ||
| 300 | try await settled() | ||
| 301 | #expect(h.string == "* TODO one ok\n* TODO two ok\n* TODO three ok\n") | ||
| 302 | #expect(asked == 1) | ||
| 303 | #expect(!messages.contains { $0.contains("undefined") }) | ||
| 304 | h.checkInSync() | ||
| 305 | // Each run is one undo step. | ||
| 306 | h.textView.undoManager?.undo() | ||
| 307 | #expect(h.string == "* TODO one ok\n* TODO two ok\n* three\n") | ||
| 308 | |||
| 309 | // A macro waits for a named macro it runs that waits for a user command. | ||
| 310 | let store = NamedMacros() | ||
| 311 | store.replace(["stamp": try OrgEditor.kmacro.lastMacro()]) | ||
| 312 | h.editor.namedMacros = store | ||
| 313 | OrgEditor.kmacro.last = KeySequence.parse("C-c m C-e !") | ||
| 314 | h.caret(at: 30) | ||
| 315 | type(h, "C-x e") | ||
| 316 | try await settled() | ||
| 317 | #expect(h.string == "* TODO one ok\n* TODO two ok\n* TODO three ok\n!") | ||
| 318 | #expect(asked == 1) | ||
| 319 | } | ||
| 320 | |||
| 240 | // MARK: - Emacs | 321 | // MARK: - Emacs |
| 241 | 322 | ||
| 242 | struct OracleCase { | 323 | struct OracleCase { |
docs/manual/guide/03-keys.org +2 · view
| @@ -317,6 +317,8 @@ In the Doom preset the Emacs keys above that start with =C-x= work in every stat | |||
| 317 | 317 | ||
| 318 | *What is recorded.* Keys typed in the editor, including =⌘= keys, which replay through the menus; the answers to the editor's questions; and keys typed during incremental search. Commands chosen with the mouse from a menu, the palette or the toolbar are not recorded, nor is what is typed into the palette, Quick Open or the app's own windows and sheets (refile targets, capture, export). Starting or stopping a recording from Edit ▸ Macros keeps every key typed in between. | 318 | *What is recorded.* Keys typed in the editor, including =⌘= keys, which replay through the menus; the answers to the editor's questions; and keys typed during incremental search. Commands chosen with the mouse from a menu, the palette or the toolbar are not recorded, nor is what is typed into the palette, Quick Open or the app's own windows and sheets (refile targets, capture, export). Starting or stopping a recording from Edit ▸ Macros keeps every key typed in between. |
| 319 | 319 | ||
| 320 | *User commands.* A key bound to a user command is recorded like any other, with the answers to the command's prompts, including those of the Org commands it runs. When the macro plays, it waits for the command to finish before the next key, and a command that fails stops it (see [[file:18-user-commands.org][User commands]]). The question before a command from a file not yet trusted on this device isn't recorded; it is asked whenever it comes up. | ||
| 321 | |||
| 320 | The last macro and the recording are shared by every buffer, as in Emacs. The last macro is gone when orgstar quits; name it to keep it. | 322 | The last macro and the recording are shared by every buffer, as in Emacs. The last macro is gone when orgstar quits; name it to keep it. |
| 321 | 323 | ||
| 322 | ** Named macros | 324 | ** Named macros |
docs/manual/guide/18-user-commands.org +38 −6 · view
| @@ -71,8 +71,8 @@ Every call returns a promise; use =await=. Offsets are UTF-16 code units, as Jav | |||
| 71 | 71 | ||
| 72 | | Call | Gives | | 72 | | Call | Gives | |
| 73 | |----------------------------+-----------------------------------------------------------------------------------------------------------------------------| | 73 | |----------------------------+-----------------------------------------------------------------------------------------------------------------------------| |
| 74 | | =org.text()= | The buffer's text when the command started. | | 74 | | =org.text()= | The buffer's text: as the command started, or as the last =org.run= left it. | |
| 75 | | =org.selection()= | The selections as =[{from, to}]=, the main caret first. With nothing selected, =from= and =to= are both the caret. | | 75 | | =org.selection()= | The selections as =[{from, to}]=, the main caret first. With nothing selected, =from= and =to= are both the caret. After =org.run=, where that command left them. | |
| 76 | | =org.heading(at)= | The heading whose entry holds the offset =at= (default: the caret), as described below, or =null= before the first heading. | | 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. | | 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. | | 78 | | =org.file()= | The file's path relative to its folder (=notes/plan.org=), or =null= for a buffer without a file. | |
| @@ -80,6 +80,7 @@ Every call returns a promise; use =await=. Offsets are UTF-16 code units, as Jav | |||
| 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. | | 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. | | 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("…")=. | | 82 | | =org.fail(text)= | Ends the command: nothing changes and =text= is shown. Use it as =return org.fail("…")=. | |
| 83 | | =org.run(id)= | Runs one of Org's commands by id (=org.todo.cycle=) and gives the text and selection after it as ={text, selection}=. See [[*Running Org's commands][Running Org's commands]]. | | ||
| 83 | | =org.version= | =1=. | | 84 | | =org.version= | =1=. | |
| 84 | 85 | ||
| 85 | A heading is an object with: | 86 | A heading is an object with: |
| @@ -104,14 +105,37 @@ The function returns an object with any of these, or nothing: | |||
| 104 | 105 | ||
| 105 | | Field | Value | | 106 | | Field | Value | |
| 106 | |-------------+---------------------------------------------------------------------------------------------------------------------------------------------| | 107 | |-------------+---------------------------------------------------------------------------------------------------------------------------------------------| |
| 107 | | =edits= | A list of ={from, to, text}= in the text the command was given. =to= defaults to =from= (an insertion) and =text= to =""= (a deletion). Edits may not overlap or start at the same offset. | | 108 | | =edits= | A list of ={from, to, text}= in the text the command was given, or after =org.run=, in the text the last =org.run= gave. =to= defaults to =from= (an insertion) and =text= to =""= (a deletion). Edits may not overlap or start at the same offset. | |
| 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 | | =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 | | =message= | Text for the echo area. | |
| 110 | | =copy= | Text for the clipboard (the kill ring). | | 111 | | =copy= | Text for the clipboard (the kill ring). | |
| 111 | 112 | ||
| 112 | orgstar 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 | orgstar 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 | 114 | ||
| 114 | The 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 | The edits are applied together as one step of undo, with the changes of the commands run with =org.run=, and only if the buffer is as it was when the command started. If you type, or the file changes on disk, while the command runs or waits for a prompt, its result is refused with "The file changed; try again." |
| 116 | |||
| 117 | ** Running Org's commands | ||
| 118 | |||
| 119 | =org.run(id)= runs a built-in command on the text as it is at that point in the command, with the caret where the command has left it, and resolves with ={text, selection}= after it: =text= is the new text and =selection= the selections as =org.selection()= gives them. The ids are those of the palette and =keymap.toml= (see [[file:03-keys.org][Keys]]): =org.todo.cycle=, =org.schedule=, =org.heading.insert= and the rest. Later calls read the new text, and later =org.run= calls work on it. | ||
| 120 | |||
| 121 | #+BEGIN_SRC js | ||
| 122 | export async function startTask(org) { | ||
| 123 | await org.run("org.todo.cycle") // TODO | ||
| 124 | await org.run("org.schedule") // asks for the date | ||
| 125 | const { selection } = await org.run("org.heading.insert-todo") | ||
| 126 | return { edits: [{ from: selection[0].from, text: "Follow up" }] } | ||
| 127 | } | ||
| 128 | #+END_SRC | ||
| 129 | |||
| 130 | - *One step of undo.* Nothing reaches the buffer until the command returns. Then the changes of every =org.run=, and the command's own =edits= after them, apply together as one step of undo. If the command fails or is cancelled, none of them apply. | ||
| 131 | - *Prompts.* A command that asks (=org.schedule= for a date, =org.tags.set= for tags) asks through the same prompt as =org.prompt=. Cancelling it makes =org.run= throw =Quit=. | ||
| 132 | - *Failures.* A command that can't run at the caret makes =org.run= throw an error with the command's own message (=error.message=), as =user-error= does in Emacs. Catch it to go on; uncaught, the command ends with that message and nothing changes. | ||
| 133 | - *Messages and the clipboard.* Messages and text for the clipboard from the commands run are shown and copied when the command's changes apply. Folding, sparse trees and snippet fields from them are not. | ||
| 134 | - *What it refuses.* =org.run= throws for: | ||
| 135 | - commands of the app (=app.*=: export, refile, capture, the clock, windows), except =app.save=, which saves the file after the command's changes apply. They need windows, other files or the network, which a command doesn't reach; | ||
| 136 | - other user commands (=user.*=); | ||
| 137 | - the editor's own commands, which aren't Org's: folding (=org.cycle=), movement and editing keys (=edit.*=), snippets and keyboard macros; | ||
| 138 | - work Org does outside the text: running a code block (=org.babel.execute=, or =C-c C-c= on one), table formulas that need Emacs, following a link, tangling, editing a block apart, column view and the agenda. =org.run= throws with "/id/ needs work outside the text here …" instead of starting it, since its result would come back after the command had ended. | ||
| 115 | 139 | ||
| 116 | * Examples | 140 | * Examples |
| 117 | 141 | ||
| @@ -197,7 +221,7 @@ Edit ▸ Cancel Running Task (=⌘.=, =app.babel.cancel=) stops a running comman | |||
| 197 | - *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh. | 221 | - *Memory.* A command that uses up its memory is stopped without affecting the app, and the next run starts fresh. |
| 198 | - *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. | 222 | - *The buffer only.* A command reads and changes the buffer it runs in, nothing else: no files, no network (=fetch=, =XMLHttpRequest=, =WebSocket=, =importScripts= and the rest are removed), no other buffers, no clipboard reads, no notifications, Calendar or other system services. |
| 199 | - *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." | 223 | - *Encrypted text.* Commands don't run in an encrypted file or in a buffer with entries decrypted that are encrypted on disk: "/file/ has decrypted entries, so user commands don't run in it." |
| 200 | - *Keyboard macros* don't wait for a user command to finish. | 224 | - *Keyboard macros* record a key bound to a user command with the answers to its prompts, and wait for the command to finish when they play (see [[file:03-keys.org::*Keyboard macros][Keyboard macros]]). |
| 201 | - *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. | 225 | - *Startup.* When you have commands, the engine that runs them starts when an editor opens, so the first run doesn't wait for it. It stops after five minutes without a run. |
| 202 | 226 | ||
| 203 | * Compared with Emacs Lisp | 227 | * Compared with Emacs Lisp |
| @@ -208,7 +232,7 @@ What Emacs Lisp has that user commands don't: | |||
| 208 | 232 | ||
| 209 | - Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read. | 233 | - Emacs Lisp functions and packages (=dash=, =s=, =org-ql=); =.el= files aren't read. |
| 210 | - Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead. | 234 | - Buffer primitives: =point=, =goto-char=, =insert=, =re-search-forward= on the buffer, =save-excursion=, markers. A command gets the text and returns edits instead. |
| 211 | - The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=, calling Org's own commands (=org-todo=, =org-schedule=). Read headings with =org.heading()= and =org.outline()=, and write the text yourself. | 235 | - The Org API: =org-element-*=, =org-map-entries= over several files, =org-entry-put=. Read headings with =org.heading()= and =org.outline()=, and write the text yourself or run Org's commands with =org.run=. |
| 212 | - Other buffers and files, =find-file=, =with-temp-buffer=, capture from a command. | 236 | - Other buffers and files, =find-file=, =with-temp-buffer=, capture from a command. |
| 213 | - Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables. | 237 | - Hooks (=org-after-todo-state-change-hook=, =post-command-hook=), advice, minor modes and buffer-local variables. |
| 214 | - =interactive= codes other than the prompts above; =C-u= prefix arguments. | 238 | - =interactive= codes other than the prompts above; =C-u= prefix arguments. |
| @@ -237,4 +261,12 @@ What Emacs Lisp has that user commands don't: | |||
| 237 | | =(message …)= | =org.message(…)= or =message= | | 261 | | =(message …)= | =org.message(…)= or =message= | |
| 238 | | =(user-error …)= | =return org.fail(…)= | | 262 | | =(user-error …)= | =return org.fail(…)= | |
| 239 | | =(kill-new …)= | =copy= | | 263 | | =(kill-new …)= | =copy= | |
| 264 | | =(org-todo)= | =await org.run("org.todo.cycle")= | | ||
| 265 | | =(org-schedule nil)=, =(org-deadline nil)= | =await org.run("org.schedule")=, =org.run("org.deadline")= | | ||
| 266 | | =(org-insert-heading)=, =(org-insert-todo-heading nil)= | =await org.run("org.heading.insert")=, =org.run("org.heading.insert-todo")= | | ||
| 267 | | =(org-set-tags-command)= | =await org.run("org.tags.set")= | | ||
| 268 | | =(org-set-effort)=, =(org-set-property …)= | =await org.run("org.effort.set")=, =org.run("org.property.read-and-set")= | | ||
| 269 | | =(org-promote-subtree)=, =(org-demote-subtree)= | =await org.run("org.subtree.promote")=, =org.run("org.subtree.demote")= | | ||
| 270 | | =(org-toggle-checkbox)= | =await org.run("org.checkbox.toggle")= | | ||
| 271 | | =(save-buffer)= | =await org.run("app.save")= | | ||
| 240 | | =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= | | 272 | | =(global-set-key (kbd "C-c u") #'my/command)= | =[[bind]]= in =keymap.toml= with =command = "user.…"= | |