Sources/OrgCore/Commands/Command.swift

ea98aa303287e7bc94425330f51d3c2dfd1ef77e
orgstar/Sources/OrgCore/Commands/Command.swift

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