Sources/OrgCore/Commands/Command.swift

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

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