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