Sources/OrgCore/Commands/Command.swift

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

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