Sources/OrgCore/Commands/Command.swift

7708760851bb006641ba731d1966cf18dc873e22
orgstar/Sources/OrgCore/Commands/Command.swift history · blame · raw

161 lines · 6747 bytes

  1import Foundation
  2
  3/// Org options that change what commands write, as the user's Emacs has them.
  4public struct EditingOptions: Sendable, Equatable, Codable {
  5    /// `org-tags-column`: negative aligns tags to end at that column, 0 puts them one space
  6    /// after the title.
  7    public var tagsColumn: Int
  8    /// `org-insert-heading-respect-content`: M-RET adds the heading after the subtree.
  9    public var insertHeadingRespectContent: Bool
 10    /// `org-M-RET-may-split-line`: M-RET in the middle of a line splits it.
 11    public var metaReturnMaySplitLine: Bool
 12    /// `org-list-allow-alphabetical`: `a.` and `A)` are list bullets.
 13    public var listAllowAlphabetical: Bool
 14    /// `org-log-repeat` `time`: completing a repeating entry records LAST_REPEAT and a state note.
 15    public var logRepeat: Bool
 16    /// `fill-column` for M-q.
 17    public var fillColumn: Int
 18
 19    public init(
 20        tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true,
 21        listAllowAlphabetical: Bool = false, logRepeat: Bool = true, fillColumn: Int = 70
 22    ) {
 23        self.tagsColumn = tagsColumn
 24        self.insertHeadingRespectContent = insertHeadingRespectContent
 25        self.metaReturnMaySplitLine = metaReturnMaySplitLine
 26        self.listAllowAlphabetical = listAllowAlphabetical
 27        self.logRepeat = logRepeat
 28        self.fillColumn = fillColumn
 29    }
 30
 31    /// Org's own defaults.
 32    public static let org = EditingOptions()
 33}
 34
 35/// Everything a command may read. Commands never read the clock or the file system, so the
 36/// same context always gives the same result.
 37public struct EditContext: Sendable {
 38    /// The revision `text` and `tree` belong to; results are applied only at this revision.
 39    public let revision: Int
 40    public let text: String
 41    public let tree: OrgTree
 42    /// Selections in UTF-16 offsets. The first is the main caret.
 43    public let selection: [Range<Int>]
 44    public let now: Date
 45    /// Includes the time zone.
 46    public let calendar: Calendar
 47    /// Replies to earlier prompts, by prompt key.
 48    public let answers: [String: String]
 49    /// Ranges the view hides (folded text); motion commands skip headings inside them.
 50    public let hidden: [Range<Int>]
 51    public let options: EditingOptions
 52
 53    public init(
 54        revision: Int, text: String, tree: OrgTree, selection: [Range<Int>],
 55        now: Date = Date(), calendar: Calendar = .current, answers: [String: String] = [:], hidden: [Range<Int>] = [],
 56        options: EditingOptions = .org
 57    ) {
 58        self.revision = revision
 59        self.text = text
 60        self.tree = tree
 61        self.selection = selection
 62        self.now = now
 63        self.calendar = calendar
 64        self.answers = answers
 65        self.hidden = hidden
 66        self.options = options
 67    }
 68
 69    public var caret: Int { selection.first?.lowerBound ?? 0 }
 70}
 71
 72public struct Prompt: Sendable, Equatable {
 73    /// The key the answer comes back under in `EditContext.answers`.
 74    public let key: String
 75    public let message: String
 76    /// Text the answer field starts with.
 77    public let initial: String
 78    /// When set, the answer is one of these.
 79    public let choices: [String]
 80
 81    public init(key: String, message: String, initial: String = "", choices: [String] = []) {
 82        self.key = key
 83        self.message = message
 84        self.initial = initial
 85        self.choices = choices
 86    }
 87}
 88
 89/// Edits computed elsewhere (refiling to another file, archiving), applied like any command's
 90/// result. Fails if the document changed since they were computed.
 91public struct PrecomputedEdit: OrgCommand {
 92    public let result: EditResult
 93    public init(_ result: EditResult) { self.result = result }
 94    public var id: String { "internal.precomputed" }
 95    public var title: String { "Apply Edit" }
 96    public func applies(in context: EditContext) -> Bool { context.revision == result.baseRevision }
 97    public func run(in context: EditContext) -> CommandStep {
 98        context.revision == result.baseRevision ? .commit(result) : .failed("The file changed; try again.")
 99    }
100}
101
102/// Things a command asks for besides text changes; the platform layer carries them out.
103public enum Effect: Sendable, Equatable {
104    case message(String)
105}
106
107public struct EditResult: Sendable, Equatable {
108    public let baseRevision: Int
109    /// Non-overlapping, in `baseRevision` coordinates.
110    public let edits: [TextEdit]
111    /// Selection after the edits, in new coordinates; nil maps the old selection through.
112    public let selection: [Range<Int>]?
113    public let effects: [Effect]
114
115    public init(baseRevision: Int, edits: [TextEdit], selection: [Range<Int>]? = nil, effects: [Effect] = []) {
116        self.baseRevision = baseRevision
117        self.edits = edits
118        self.selection = selection
119        self.effects = effects
120    }
121}
122
123public enum CommandStep: Sendable, Equatable {
124    case commit(EditResult)
125    /// Ask, then run again with the answer in `EditContext.answers`.
126    case prompt(Prompt)
127    /// The command can't run here; nothing changes. The message is for the user, as org's
128    /// `user-error`.
129    case failed(String)
130}
131
132/// A named operation. Keys, menus, the palette and touch controls all run commands.
133public protocol OrgCommand: Sendable {
134    /// Stable identifier, used by keymaps: `org.todo.cycle`.
135    var id: String { get }
136    /// Shown in the command palette.
137    var title: String { get }
138    /// Whether the command means something at the caret; context dispatch (one key, several
139    /// commands) runs the first that applies.
140    func applies(in context: EditContext) -> Bool
141    func run(in context: EditContext) -> CommandStep
142}
143
144public enum Commands {
145    public static let all: [any OrgCommand] = [
146        TodoCycle(), PriorityUp(), PriorityDown(), PromoteHeading(), DemoteHeading(),
147        InsertHeading(), InsertHeadingAfterSubtree(), InsertTodoHeading(),
148        MoveSubtreeUp(), MoveSubtreeDown(), PromoteSubtree(), DemoteSubtree(),
149        NextHeading(), PreviousHeading(), ForwardSameLevel(), BackwardSameLevel(), UpHeading(),
150        SetTags(),
151        InsertItem(), InsertCheckboxItem(), IndentItem(), OutdentItem(), IndentItemTree(), OutdentItemTree(),
152        MoveItemUp(), MoveItemDown(), ToggleCheckbox(),
153        InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true),
154        RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(),
155        ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false),
156    ]
157
158    public static func command(_ id: String) -> (any OrgCommand)? {
159        all.first { $0.id == id }
160    }
161}