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