Sources/OrgCore/Commands/Command.swift

53dc6c6bfdccaa724b05a834545373663c5cdee0
orgstar/Sources/OrgCore/Commands/Command.swift

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