Sources/OrgCore/Commands/Command.swift

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

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