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