Sources/OrgCore/Commands/Command.swift

6ecbf692e07af991cfe740d095dce71f29a670ae
orgstar/Sources/OrgCore/Commands/Command.swift history · blame · raw

123 lines · 4838 bytes

  1import Foundation
  2
  3/// Everything a command may read. Commands never read the clock or the file system, so the
  4/// same context always gives the same result.
  5public struct EditContext: Sendable {
  6    /// The revision `text` and `tree` belong to; results are applied only at this revision.
  7    public let revision: Int
  8    public let text: String
  9    public let tree: OrgTree
 10    /// Selections in UTF-16 offsets. The first is the main caret.
 11    public let selection: [Range<Int>]
 12    public let now: Date
 13    /// Includes the time zone.
 14    public let calendar: Calendar
 15    /// Replies to earlier prompts, by prompt key.
 16    public let answers: [String: String]
 17    /// Ranges the view hides (folded text); motion commands skip headings inside them.
 18    public let hidden: [Range<Int>]
 19
 20    public init(
 21        revision: Int, text: String, tree: OrgTree, selection: [Range<Int>],
 22        now: Date = Date(), calendar: Calendar = .current, answers: [String: String] = [:], hidden: [Range<Int>] = []
 23    ) {
 24        self.revision = revision
 25        self.text = text
 26        self.tree = tree
 27        self.selection = selection
 28        self.now = now
 29        self.calendar = calendar
 30        self.answers = answers
 31        self.hidden = hidden
 32    }
 33
 34    public var caret: Int { selection.first?.lowerBound ?? 0 }
 35}
 36
 37public struct Prompt: Sendable, Equatable {
 38    /// The key the answer comes back under in `EditContext.answers`.
 39    public let key: String
 40    public let message: String
 41    /// Text the answer field starts with.
 42    public let initial: String
 43    /// When set, the answer is one of these.
 44    public let choices: [String]
 45
 46    public init(key: String, message: String, initial: String = "", choices: [String] = []) {
 47        self.key = key
 48        self.message = message
 49        self.initial = initial
 50        self.choices = choices
 51    }
 52}
 53
 54/// Edits computed elsewhere (refiling to another file, archiving), applied like any command's
 55/// result. Fails if the document changed since they were computed.
 56public struct PrecomputedEdit: OrgCommand {
 57    public let result: EditResult
 58    public init(_ result: EditResult) { self.result = result }
 59    public var id: String { "internal.precomputed" }
 60    public var title: String { "Apply Edit" }
 61    public func applies(in context: EditContext) -> Bool { context.revision == result.baseRevision }
 62    public func run(in context: EditContext) -> CommandStep {
 63        context.revision == result.baseRevision ? .commit(result) : .failed("The file changed; try again.")
 64    }
 65}
 66
 67/// Things a command asks for besides text changes; the platform layer carries them out.
 68public enum Effect: Sendable, Equatable {
 69    case message(String)
 70}
 71
 72public struct EditResult: Sendable, Equatable {
 73    public let baseRevision: Int
 74    /// Non-overlapping, in `baseRevision` coordinates.
 75    public let edits: [TextEdit]
 76    /// Selection after the edits, in new coordinates; nil maps the old selection through.
 77    public let selection: [Range<Int>]?
 78    public let effects: [Effect]
 79
 80    public init(baseRevision: Int, edits: [TextEdit], selection: [Range<Int>]? = nil, effects: [Effect] = []) {
 81        self.baseRevision = baseRevision
 82        self.edits = edits
 83        self.selection = selection
 84        self.effects = effects
 85    }
 86}
 87
 88public enum CommandStep: Sendable, Equatable {
 89    case commit(EditResult)
 90    /// Ask, then run again with the answer in `EditContext.answers`.
 91    case prompt(Prompt)
 92    /// The command can't run here; nothing changes. The message is for the user, as org's
 93    /// `user-error`.
 94    case failed(String)
 95}
 96
 97/// A named operation. Keys, menus, the palette and touch controls all run commands.
 98public protocol OrgCommand: Sendable {
 99    /// Stable identifier, used by keymaps: `org.todo.cycle`.
100    var id: String { get }
101    /// Shown in the command palette.
102    var title: String { get }
103    /// Whether the command means something at the caret; context dispatch (one key, several
104    /// commands) runs the first that applies.
105    func applies(in context: EditContext) -> Bool
106    func run(in context: EditContext) -> CommandStep
107}
108
109public enum Commands {
110    public static let all: [any OrgCommand] = [
111        TodoCycle(), PriorityUp(), PriorityDown(), PromoteHeading(), DemoteHeading(),
112        InsertHeading(), InsertHeadingAfterSubtree(), InsertTodoHeading(),
113        MoveSubtreeUp(), MoveSubtreeDown(), PromoteSubtree(), DemoteSubtree(),
114        NextHeading(), PreviousHeading(), ForwardSameLevel(), BackwardSameLevel(), UpHeading(),
115        SetTags(),
116        InsertItem(), InsertCheckboxItem(), IndentItem(), OutdentItem(), IndentItemTree(), OutdentItemTree(),
117        MoveItemUp(), MoveItemDown(), ToggleCheckbox(),
118    ]
119
120    public static func command(_ id: String) -> (any OrgCommand)? {
121        all.first { $0.id == id }
122    }
123}