Sources/OrgCore/Commands/Command.swift

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

312 lines · 16179 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-enforce-todo-dependencies`: an entry can't become done before its TODO
 26    /// descendants, or under an `ORDERED` parent before its earlier TODO siblings.
 27    public var enforceTodoDependencies = false
 28    /// `org-enforce-todo-checkbox-dependencies`: an entry can't become done with unchecked boxes.
 29    public var enforceTodoCheckboxDependencies = false
 30    /// `org-tag-alist` in `#+TAGS` syntax, a line for each `:newline`: the tags C-c C-q offers in
 31    /// files without `#+TAGS`.
 32    public var tagAlist: String?
 33    /// `org-clock-rounding-minutes`: clocks start and end on multiples of this many minutes.
 34    public var clockRoundingMinutes = 0
 35    /// `org-clock-out-remove-zero-time-clocks`.
 36    public var clockOutRemoveZeroTimeClocks = false
 37    /// `org-clock-in-switch-to-state`: the keyword an entry takes when clocked in.
 38    public var clockInSwitchToState: String?
 39    /// `org-clock-into-drawer` as `config.toml` writes it: `nil`, `t`, a number of clock lines,
 40    /// or a drawer name; nil for Org's default, `t`.
 41    public var clockIntoDrawer: String?
 42    /// `org-structure-template-alist`, for C-c C-, and `<` completion; nil for Org's.
 43    public var structureTemplates: [StructureTemplate]?
 44    /// `org-archive-location`, for entries without an `ARCHIVE` property or `#+ARCHIVE:`; nil
 45    /// for Org's default, `%s_archive::`.
 46    public var archiveLocation: String?
 47    /// `org-track-ordered-property-with-tag`: the tag toggling `ORDERED` toggles too; nil for none.
 48    public var trackOrderedPropertyWithTag: String?
 49    /// `org-use-speed-commands`: single keys at the start of a heading line run commands.
 50    public var useSpeedCommands: Bool
 51    /// `org-startup-with-inline-images`.
 52    public var startupWithInlineImages: Bool
 53    /// `org-startup-indented`: org-indent's virtual indentation.
 54    public var startupIndented = true
 55    /// `org-hide-leading-stars`; org-indent hides them too.
 56    public var hideLeadingStars = false
 57    /// `org-startup-align-all-tables`.
 58    public var startupAlignAllTables = false
 59    /// `org-startup-truncated`: long lines run off the right edge instead of wrapping.
 60    public var startupTruncated = false
 61    /// Spell checking while typing, outside code and markup.
 62    public var spellCheck = false
 63    /// `electric-pair-mode`: brackets and quotes typed in pairs.
 64    public var electricPair = false
 65    /// `org-cycle-hide-drawer-startup`: drawers are folded when a file opens.
 66    public var hideDrawerStartup: Bool
 67    /// `org-cycle-hide-block-startup`: blocks are folded when a file opens.
 68    public var hideBlockStartup: Bool
 69    /// `fill-column` for M-q.
 70    public var fillColumn: Int
 71    /// `org-hide-emphasis-markers`: table alignment measures emphasis without its markers.
 72    public var hideEmphasisMarkers: Bool
 73    /// `org-pretty-entities`: table alignment measures `\alpha` as `α`.
 74    public var prettyEntities: Bool
 75    /// `org-use-sub-superscripts` `{}`: only `_{…}` and `^{…}` are sub- and superscripts.
 76    public var subSuperscriptsNeedBraces: Bool
 77
 78    public init(
 79        tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true,
 80        listAllowAlphabetical: Bool = false, logRepeat: Bool = true, fillColumn: Int = 70,
 81        hideEmphasisMarkers: Bool = false, prettyEntities: Bool = false, subSuperscriptsNeedBraces: Bool = false,
 82        logDone: LogHow? = nil, logIntoDrawer: String? = nil, fastTodoSelection: Bool = true,
 83        hideDrawerStartup: Bool = true, hideBlockStartup: Bool = false, logReschedule: LogHow? = nil, logRedeadline: LogHow? = nil,
 84        useSpeedCommands: Bool = false, startupWithInlineImages: Bool = false,
 85        startupIndented: Bool = true, hideLeadingStars: Bool = false, startupAlignAllTables: Bool = false,
 86        startupTruncated: Bool = false, spellCheck: Bool = false
 87    ) {
 88        self.startupTruncated = startupTruncated
 89        self.spellCheck = spellCheck
 90        self.startupIndented = startupIndented
 91        self.hideLeadingStars = hideLeadingStars
 92        self.startupAlignAllTables = startupAlignAllTables
 93        self.useSpeedCommands = useSpeedCommands
 94        self.startupWithInlineImages = startupWithInlineImages
 95        self.logReschedule = logReschedule
 96        self.logRedeadline = logRedeadline
 97        self.hideDrawerStartup = hideDrawerStartup
 98        self.hideBlockStartup = hideBlockStartup
 99        self.fastTodoSelection = fastTodoSelection
100        self.logDone = logDone
101        self.logIntoDrawer = logIntoDrawer
102        self.tagsColumn = tagsColumn
103        self.insertHeadingRespectContent = insertHeadingRespectContent
104        self.metaReturnMaySplitLine = metaReturnMaySplitLine
105        self.listAllowAlphabetical = listAllowAlphabetical
106        self.logRepeat = logRepeat
107        self.fillColumn = fillColumn
108        self.hideEmphasisMarkers = hideEmphasisMarkers
109        self.prettyEntities = prettyEntities
110        self.subSuperscriptsNeedBraces = subSuperscriptsNeedBraces
111    }
112
113    /// Org's own defaults.
114    public static let org = EditingOptions()
115}
116
117/// Everything a command may read. Commands never read the clock or the file system, so the
118/// same context always gives the same result.
119public struct EditContext: Sendable {
120    /// The revision `text` and `tree` belong to; results are applied only at this revision.
121    public let revision: Int
122    public let text: String
123    public let tree: OrgTree
124    /// Selections in UTF-16 offsets. The first is the main caret.
125    public let selection: [Range<Int>]
126    public let now: Date
127    /// Includes the time zone.
128    public let calendar: Calendar
129    /// Replies to earlier prompts, by prompt key.
130    public let answers: [String: String]
131    /// Ranges the view hides (folded text); motion commands skip headings inside them.
132    public let hidden: [Range<Int>]
133    public let options: EditingOptions
134    /// Tags used across the workspace, for completion; read when a command needs them.
135    public let knownTags: @Sendable () -> [String]
136    /// The command run just before, with nothing typed since (`last-command`).
137    public let lastCommand: String?
138
139    public init(
140        revision: Int, text: String, tree: OrgTree, selection: [Range<Int>],
141        now: Date = Date(), calendar: Calendar = .current, answers: [String: String] = [:], hidden: [Range<Int>] = [],
142        options: EditingOptions = .org, knownTags: @escaping @Sendable () -> [String] = { [] }, lastCommand: String? = nil
143    ) {
144        self.lastCommand = lastCommand
145        self.knownTags = knownTags
146        self.revision = revision
147        self.text = text
148        self.tree = tree
149        self.selection = selection
150        self.now = now
151        self.calendar = calendar
152        self.answers = answers
153        self.hidden = hidden
154        self.options = options
155    }
156
157    public var caret: Int { selection.first?.lowerBound ?? 0 }
158}
159
160public struct Prompt: Sendable, Equatable {
161    /// The key the answer comes back under in `EditContext.answers`.
162    public let key: String
163    public let message: String
164    /// Text the answer field starts with.
165    public let initial: String
166    /// When set, the answer is one of these, or with `requireMatch` false, these are offered.
167    public let choices: [String]
168    public let requireMatch: Bool
169    /// Choices complete the text after the last of these characters (`:` between tags).
170    public let completionSeparator: Character?
171    /// Single keys answer instead of text.
172    public let fast: FastSelection?
173    /// A date prompt, read by `org-read-date` against this default (nil: today).
174    public let date: DateRead?
175
176    public struct DateRead: Sendable, Equatable {
177        public let defaultDate: Date?
178        /// Whether the answer becomes an inactive timestamp, shown in brackets.
179        public let inactive: Bool
180        public init(defaultDate: Date?, inactive: Bool = false) {
181            self.defaultDate = defaultDate
182            self.inactive = inactive
183        }
184    }
185
186    public init(
187        key: String, message: String, initial: String = "", choices: [String] = [], requireMatch: Bool = true,
188        completionSeparator: Character? = nil, fast: FastSelection? = nil, date: DateRead? = nil
189    ) {
190        self.key = key
191        self.message = message
192        self.initial = initial
193        self.choices = choices
194        self.requireMatch = requireMatch
195        self.completionSeparator = completionSeparator
196        self.fast = fast
197        self.date = date
198    }
199}
200
201/// Edits computed elsewhere (refiling to another file, archiving), applied like any command's
202/// result. Fails if the document changed since they were computed.
203public struct PrecomputedEdit: OrgCommand {
204    public let result: EditResult
205    public init(_ result: EditResult) { self.result = result }
206    public var id: String { "internal.precomputed" }
207    public var title: String { "Apply Edit" }
208    public func applies(in context: EditContext) -> Bool { context.revision == result.baseRevision }
209    public func run(in context: EditContext) -> CommandStep {
210        context.revision == result.baseRevision ? .commit(result) : .failed("The file changed; try again.")
211    }
212}
213
214/// Things a command asks for besides text changes; the platform layer carries them out.
215public enum Effect: Sendable, Equatable {
216    case message(String)
217    /// An inserted link was a stored one; it leaves `org-stored-links`.
218    case storedLinkUsed(String)
219    /// Text for the clipboard (the kill ring).
220    case copy(String)
221    /// Show a sparse tree: the context of each point, the rest folded, and highlights until
222    /// the next edit or C-c C-c.
223    case sparseTree(show: [Int], highlights: [Range<Int>])
224    /// Fold the subtree of the heading starting here (in the new text).
225    case fold(Int)
226    /// Read the file's `#+SETUPFILE`s again (`org-mode-restart`).
227    case refreshSetup
228}
229
230public struct EditResult: Sendable, Equatable {
231    public let baseRevision: Int
232    /// Non-overlapping, in `baseRevision` coordinates.
233    public let edits: [TextEdit]
234    /// Selection after the edits, in new coordinates; nil maps the old selection through.
235    public let selection: [Range<Int>]?
236    public let effects: [Effect]
237
238    public init(baseRevision: Int, edits: [TextEdit], selection: [Range<Int>]? = nil, effects: [Effect] = []) {
239        self.baseRevision = baseRevision
240        self.edits = edits
241        self.selection = selection
242        self.effects = effects
243    }
244}
245
246public enum CommandStep: Sendable, Equatable {
247    case commit(EditResult)
248    /// Ask, then run again with the answer in `EditContext.answers`.
249    case prompt(Prompt)
250    /// The command can't run here; nothing changes. The message is for the user, as org's
251    /// `user-error`.
252    case failed(String)
253    /// Work the platform does outside the text (Emacs, an interpreter); its result comes back
254    /// as an edit.
255    case external(ExternalRequest)
256}
257
258public enum ExternalRequest: Sendable, Equatable {
259    /// Recalculate the table whose text is at `table` in Emacs, running `form` with point at
260    /// `point`, and put Emacs's table text in its place. `lisp` when its formulas run Lisp.
261    case emacsTable(table: Range<Int>, point: Int, form: String, reason: String, lisp: Bool)
262    /// Run a src block; `Babel.finish` turns its output into the result edit.
263    case babel(BabelJob)
264    /// Follow a link: the app opens URLs and files and searches headings.
265    case openLink(OrgLink)
266    /// Edit a block's text apart (`org-edit-special`); `ReplaceBlockLines` puts it back.
267    case editBlock(BlockEdit)
268    /// Show a column view.
269    case columnView(ColumnView.View)
270    /// Show the agenda for `days` days from `start` (a `Days` number), as
271    /// `org-follow-timestamp-link` does.
272    case agenda(start: Int, days: Int)
273    /// Write source blocks to their files (`org-babel-tangle`); the app knows the file's path.
274    case tangle(Tangle.Scope)
275}
276
277/// A named operation. Keys, menus, the palette and touch controls all run commands.
278public protocol OrgCommand: Sendable {
279    /// Stable identifier, used by keymaps: `org.todo.cycle`.
280    var id: String { get }
281    /// Shown in the command palette.
282    var title: String { get }
283    /// Whether the command means something at the caret; context dispatch (one key, several
284    /// commands) runs the first that applies.
285    func applies(in context: EditContext) -> Bool
286    func run(in context: EditContext) -> CommandStep
287}
288
289public enum Commands {
290    public static let all: [any OrgCommand] = [
291        TodoCycle(), TodoShift(right: true), TodoShift(right: false), PriorityUp(), PriorityDown(), PromoteHeading(), DemoteHeading(),
292        InsertHeading(), InsertHeadingAfterSubtree(), InsertTodoHeading(),
293        MoveSubtreeUp(), MoveSubtreeDown(), PromoteSubtree(), DemoteSubtree(),
294        NextHeading(), PreviousHeading(), ForwardSameLevel(), BackwardSameLevel(), UpHeading(),
295        SetTags(),
296        InsertItem(), InsertCheckboxItem(), IndentItem(), OutdentItem(), IndentItemTree(), OutdentItemTree(),
297        MoveItemUp(), MoveItemDown(), ToggleCheckbox(),
298        InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true),
299        RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(), CreateTable(),
300        TableRecalculate(all: false), TableRecalculate(all: true), ExecuteSrcBlock(), OrgDwim(),
301        ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false),
302        OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(),
303        CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target),
304        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(), ToggleOrderedProperty(),
305    ]
306
307    public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) }
308
309    public static func command(_ id: String) -> (any OrgCommand)? {
310        everything.first { $0.id == id }
311    }
312}