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