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