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