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