Sources/OrgCore/Commands/Command.swift
221 lines · 10285 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}
149
150public struct EditResult: Sendable, Equatable {
151 public let baseRevision: Int
152 /// Non-overlapping, in `baseRevision` coordinates.
153 public let edits: [TextEdit]
154 /// Selection after the edits, in new coordinates; nil maps the old selection through.
155 public let selection: [Range<Int>]?
156 public let effects: [Effect]
157
158 public init(baseRevision: Int, edits: [TextEdit], selection: [Range<Int>]? = nil, effects: [Effect] = []) {
159 self.baseRevision = baseRevision
160 self.edits = edits
161 self.selection = selection
162 self.effects = effects
163 }
164}
165
166public enum CommandStep: Sendable, Equatable {
167 case commit(EditResult)
168 /// Ask, then run again with the answer in `EditContext.answers`.
169 case prompt(Prompt)
170 /// The command can't run here; nothing changes. The message is for the user, as org's
171 /// `user-error`.
172 case failed(String)
173 /// Work the platform does outside the text (Emacs, an interpreter); its result comes back
174 /// as an edit.
175 case external(ExternalRequest)
176}
177
178public enum ExternalRequest: Sendable, Equatable {
179 /// Recalculate the table whose text is at `table` in Emacs, running `form` with point at
180 /// `point`, and put Emacs's table text in its place. `lisp` when its formulas run Lisp.
181 case emacsTable(table: Range<Int>, point: Int, form: String, reason: String, lisp: Bool)
182 /// Run a src block; `Babel.finish` turns its output into the result edit.
183 case babel(BabelJob)
184 /// Follow a link: the app opens URLs and files and searches headings.
185 case openLink(OrgLink)
186}
187
188/// A named operation. Keys, menus, the palette and touch controls all run commands.
189public protocol OrgCommand: Sendable {
190 /// Stable identifier, used by keymaps: `org.todo.cycle`.
191 var id: String { get }
192 /// Shown in the command palette.
193 var title: String { get }
194 /// Whether the command means something at the caret; context dispatch (one key, several
195 /// commands) runs the first that applies.
196 func applies(in context: EditContext) -> Bool
197 func run(in context: EditContext) -> CommandStep
198}
199
200public enum Commands {
201 public static let all: [any OrgCommand] = [
202 TodoCycle(), TodoShift(right: true), TodoShift(right: false), PriorityUp(), PriorityDown(), PromoteHeading(), DemoteHeading(),
203 InsertHeading(), InsertHeadingAfterSubtree(), InsertTodoHeading(),
204 MoveSubtreeUp(), MoveSubtreeDown(), PromoteSubtree(), DemoteSubtree(),
205 NextHeading(), PreviousHeading(), ForwardSameLevel(), BackwardSameLevel(), UpHeading(),
206 SetTags(),
207 InsertItem(), InsertCheckboxItem(), IndentItem(), OutdentItem(), IndentItemTree(), OutdentItemTree(),
208 MoveItemUp(), MoveItemDown(), ToggleCheckbox(),
209 InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true),
210 RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(), CreateTable(),
211 TableRecalculate(all: false), TableRecalculate(all: true), ExecuteSrcBlock(), OrgDwim(),
212 ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false),
213 OpenLinkAtPoint(), CreateID(),
214 ]
215
216 public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) }
217
218 public static func command(_ id: String) -> (any OrgCommand)? {
219 everything.first { $0.id == id }
220 }
221}