Sources/OrgCore/Commands/Command.swift

33ad34b336e89f4757cb2613ed86e9fe0b674e52
orgstar/Sources/OrgCore/Commands/Command.swift

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