Sources/OrgCore/Commands/Command.swift

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

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