Sources/OrgCore/Commands/Command.swift

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

214 lines · 9880 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    /// `org-log-done`: CLOSED when an entry becomes done, and a note with `.note`.
 17    public var logDone: LogHow?
 18    /// `org-log-into-drawer`: the drawer state notes go in, or nil for none.
 19    public var logIntoDrawer: String?
 20    /// `org-use-fast-todo-selection` `auto`: with keys in the keywords, C-c C-t asks for one.
 21    public var fastTodoSelection: Bool
 22    /// `fill-column` for M-q.
 23    public var fillColumn: Int
 24    /// `org-hide-emphasis-markers`: table alignment measures emphasis without its markers.
 25    public var hideEmphasisMarkers: Bool
 26    /// `org-pretty-entities`: table alignment measures `\alpha` as `α`.
 27    public var prettyEntities: Bool
 28    /// `org-use-sub-superscripts` `{}`: only `_{…}` and `^{…}` are sub- and superscripts.
 29    public var subSuperscriptsNeedBraces: Bool
 30
 31    public init(
 32        tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true,
 33        listAllowAlphabetical: Bool = false, logRepeat: Bool = true, fillColumn: Int = 70,
 34        hideEmphasisMarkers: Bool = false, prettyEntities: Bool = false, subSuperscriptsNeedBraces: Bool = false,
 35        logDone: LogHow? = nil, logIntoDrawer: String? = nil, fastTodoSelection: Bool = true
 36    ) {
 37        self.fastTodoSelection = fastTodoSelection
 38        self.logDone = logDone
 39        self.logIntoDrawer = logIntoDrawer
 40        self.tagsColumn = tagsColumn
 41        self.insertHeadingRespectContent = insertHeadingRespectContent
 42        self.metaReturnMaySplitLine = metaReturnMaySplitLine
 43        self.listAllowAlphabetical = listAllowAlphabetical
 44        self.logRepeat = logRepeat
 45        self.fillColumn = fillColumn
 46        self.hideEmphasisMarkers = hideEmphasisMarkers
 47        self.prettyEntities = prettyEntities
 48        self.subSuperscriptsNeedBraces = subSuperscriptsNeedBraces
 49    }
 50
 51    /// Org's own defaults.
 52    public static let org = EditingOptions()
 53}
 54
 55/// Everything a command may read. Commands never read the clock or the file system, so the
 56/// same context always gives the same result.
 57public struct EditContext: Sendable {
 58    /// The revision `text` and `tree` belong to; results are applied only at this revision.
 59    public let revision: Int
 60    public let text: String
 61    public let tree: OrgTree
 62    /// Selections in UTF-16 offsets. The first is the main caret.
 63    public let selection: [Range<Int>]
 64    public let now: Date
 65    /// Includes the time zone.
 66    public let calendar: Calendar
 67    /// Replies to earlier prompts, by prompt key.
 68    public let answers: [String: String]
 69    /// Ranges the view hides (folded text); motion commands skip headings inside them.
 70    public let hidden: [Range<Int>]
 71    public let options: EditingOptions
 72    /// Tags used across the workspace, for completion; read when a command needs them.
 73    public let knownTags: @Sendable () -> [String]
 74
 75    public init(
 76        revision: Int, text: String, tree: OrgTree, selection: [Range<Int>],
 77        now: Date = Date(), calendar: Calendar = .current, answers: [String: String] = [:], hidden: [Range<Int>] = [],
 78        options: EditingOptions = .org, knownTags: @escaping @Sendable () -> [String] = { [] }
 79    ) {
 80        self.knownTags = knownTags
 81        self.revision = revision
 82        self.text = text
 83        self.tree = tree
 84        self.selection = selection
 85        self.now = now
 86        self.calendar = calendar
 87        self.answers = answers
 88        self.hidden = hidden
 89        self.options = options
 90    }
 91
 92    public var caret: Int { selection.first?.lowerBound ?? 0 }
 93}
 94
 95public struct Prompt: Sendable, Equatable {
 96    /// The key the answer comes back under in `EditContext.answers`.
 97    public let key: String
 98    public let message: String
 99    /// Text the answer field starts with.
100    public let initial: String
101    /// When set, the answer is one of these, or with `requireMatch` false, these are offered.
102    public let choices: [String]
103    public let requireMatch: Bool
104    /// Choices complete the text after the last of these characters (`:` between tags).
105    public let completionSeparator: Character?
106    /// Single keys answer instead of text.
107    public let fast: FastSelection?
108
109    public init(
110        key: String, message: String, initial: String = "", choices: [String] = [], requireMatch: Bool = true,
111        completionSeparator: Character? = nil, fast: FastSelection? = nil
112    ) {
113        self.key = key
114        self.message = message
115        self.initial = initial
116        self.choices = choices
117        self.requireMatch = requireMatch
118        self.completionSeparator = completionSeparator
119        self.fast = fast
120    }
121}
122
123/// Edits computed elsewhere (refiling to another file, archiving), applied like any command's
124/// result. Fails if the document changed since they were computed.
125public struct PrecomputedEdit: OrgCommand {
126    public let result: EditResult
127    public init(_ result: EditResult) { self.result = result }
128    public var id: String { "internal.precomputed" }
129    public var title: String { "Apply Edit" }
130    public func applies(in context: EditContext) -> Bool { context.revision == result.baseRevision }
131    public func run(in context: EditContext) -> CommandStep {
132        context.revision == result.baseRevision ? .commit(result) : .failed("The file changed; try again.")
133    }
134}
135
136/// Things a command asks for besides text changes; the platform layer carries them out.
137public enum Effect: Sendable, Equatable {
138    case message(String)
139    /// An inserted link was a stored one; it leaves `org-stored-links`.
140    case storedLinkUsed(String)
141}
142
143public struct EditResult: Sendable, Equatable {
144    public let baseRevision: Int
145    /// Non-overlapping, in `baseRevision` coordinates.
146    public let edits: [TextEdit]
147    /// Selection after the edits, in new coordinates; nil maps the old selection through.
148    public let selection: [Range<Int>]?
149    public let effects: [Effect]
150
151    public init(baseRevision: Int, edits: [TextEdit], selection: [Range<Int>]? = nil, effects: [Effect] = []) {
152        self.baseRevision = baseRevision
153        self.edits = edits
154        self.selection = selection
155        self.effects = effects
156    }
157}
158
159public enum CommandStep: Sendable, Equatable {
160    case commit(EditResult)
161    /// Ask, then run again with the answer in `EditContext.answers`.
162    case prompt(Prompt)
163    /// The command can't run here; nothing changes. The message is for the user, as org's
164    /// `user-error`.
165    case failed(String)
166    /// Work the platform does outside the text (Emacs, an interpreter); its result comes back
167    /// as an edit.
168    case external(ExternalRequest)
169}
170
171public enum ExternalRequest: Sendable, Equatable {
172    /// Recalculate the table whose text is at `table` in Emacs, running `form` with point at
173    /// `point`, and put Emacs's table text in its place. `lisp` when its formulas run Lisp.
174    case emacsTable(table: Range<Int>, point: Int, form: String, reason: String, lisp: Bool)
175    /// Run a src block; `Babel.finish` turns its output into the result edit.
176    case babel(BabelJob)
177    /// Follow a link: the app opens URLs and files and searches headings.
178    case openLink(OrgLink)
179}
180
181/// A named operation. Keys, menus, the palette and touch controls all run commands.
182public protocol OrgCommand: Sendable {
183    /// Stable identifier, used by keymaps: `org.todo.cycle`.
184    var id: String { get }
185    /// Shown in the command palette.
186    var title: String { get }
187    /// Whether the command means something at the caret; context dispatch (one key, several
188    /// commands) runs the first that applies.
189    func applies(in context: EditContext) -> Bool
190    func run(in context: EditContext) -> CommandStep
191}
192
193public enum Commands {
194    public static let all: [any OrgCommand] = [
195        TodoCycle(), TodoShift(right: true), TodoShift(right: false), PriorityUp(), PriorityDown(), PromoteHeading(), DemoteHeading(),
196        InsertHeading(), InsertHeadingAfterSubtree(), InsertTodoHeading(),
197        MoveSubtreeUp(), MoveSubtreeDown(), PromoteSubtree(), DemoteSubtree(),
198        NextHeading(), PreviousHeading(), ForwardSameLevel(), BackwardSameLevel(), UpHeading(),
199        SetTags(),
200        InsertItem(), InsertCheckboxItem(), IndentItem(), OutdentItem(), IndentItemTree(), OutdentItemTree(),
201        MoveItemUp(), MoveItemDown(), ToggleCheckbox(),
202        InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true),
203        RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(), CreateTable(),
204        TableRecalculate(all: false), TableRecalculate(all: true), ExecuteSrcBlock(), OrgDwim(),
205        ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false),
206        OpenLinkAtPoint(), CreateID(),
207    ]
208
209    public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) }
210
211    public static func command(_ id: String) -> (any OrgCommand)? {
212        everything.first { $0.id == id }
213    }
214}