Sources/OrgCore/Commands/Command.swift

24e367f9f225ca0b6d36e6830e4269493de0ffe3
orgstar/Sources/OrgCore/Commands/Command.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form