Sources/OrgCore/Commands/Command.swift
158 lines · 6609 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
17 public init(
18 tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true,
19 listAllowAlphabetical: Bool = false, logRepeat: Bool = true
20 ) {
21 self.tagsColumn = tagsColumn
22 self.insertHeadingRespectContent = insertHeadingRespectContent
23 self.metaReturnMaySplitLine = metaReturnMaySplitLine
24 self.listAllowAlphabetical = listAllowAlphabetical
25 self.logRepeat = logRepeat
26 }
27
28 /// Org's own defaults.
29 public static let org = EditingOptions()
30}
31
32/// Everything a command may read. Commands never read the clock or the file system, so the
33/// same context always gives the same result.
34public struct EditContext: Sendable {
35 /// The revision `text` and `tree` belong to; results are applied only at this revision.
36 public let revision: Int
37 public let text: String
38 public let tree: OrgTree
39 /// Selections in UTF-16 offsets. The first is the main caret.
40 public let selection: [Range<Int>]
41 public let now: Date
42 /// Includes the time zone.
43 public let calendar: Calendar
44 /// Replies to earlier prompts, by prompt key.
45 public let answers: [String: String]
46 /// Ranges the view hides (folded text); motion commands skip headings inside them.
47 public let hidden: [Range<Int>]
48 public let options: EditingOptions
49
50 public init(
51 revision: Int, text: String, tree: OrgTree, selection: [Range<Int>],
52 now: Date = Date(), calendar: Calendar = .current, answers: [String: String] = [:], hidden: [Range<Int>] = [],
53 options: EditingOptions = .org
54 ) {
55 self.revision = revision
56 self.text = text
57 self.tree = tree
58 self.selection = selection
59 self.now = now
60 self.calendar = calendar
61 self.answers = answers
62 self.hidden = hidden
63 self.options = options
64 }
65
66 public var caret: Int { selection.first?.lowerBound ?? 0 }
67}
68
69public struct Prompt: Sendable, Equatable {
70 /// The key the answer comes back under in `EditContext.answers`.
71 public let key: String
72 public let message: String
73 /// Text the answer field starts with.
74 public let initial: String
75 /// When set, the answer is one of these.
76 public let choices: [String]
77
78 public init(key: String, message: String, initial: String = "", choices: [String] = []) {
79 self.key = key
80 self.message = message
81 self.initial = initial
82 self.choices = choices
83 }
84}
85
86/// Edits computed elsewhere (refiling to another file, archiving), applied like any command's
87/// result. Fails if the document changed since they were computed.
88public struct PrecomputedEdit: OrgCommand {
89 public let result: EditResult
90 public init(_ result: EditResult) { self.result = result }
91 public var id: String { "internal.precomputed" }
92 public var title: String { "Apply Edit" }
93 public func applies(in context: EditContext) -> Bool { context.revision == result.baseRevision }
94 public func run(in context: EditContext) -> CommandStep {
95 context.revision == result.baseRevision ? .commit(result) : .failed("The file changed; try again.")
96 }
97}
98
99/// Things a command asks for besides text changes; the platform layer carries them out.
100public enum Effect: Sendable, Equatable {
101 case message(String)
102}
103
104public struct EditResult: Sendable, Equatable {
105 public let baseRevision: Int
106 /// Non-overlapping, in `baseRevision` coordinates.
107 public let edits: [TextEdit]
108 /// Selection after the edits, in new coordinates; nil maps the old selection through.
109 public let selection: [Range<Int>]?
110 public let effects: [Effect]
111
112 public init(baseRevision: Int, edits: [TextEdit], selection: [Range<Int>]? = nil, effects: [Effect] = []) {
113 self.baseRevision = baseRevision
114 self.edits = edits
115 self.selection = selection
116 self.effects = effects
117 }
118}
119
120public enum CommandStep: Sendable, Equatable {
121 case commit(EditResult)
122 /// Ask, then run again with the answer in `EditContext.answers`.
123 case prompt(Prompt)
124 /// The command can't run here; nothing changes. The message is for the user, as org's
125 /// `user-error`.
126 case failed(String)
127}
128
129/// A named operation. Keys, menus, the palette and touch controls all run commands.
130public protocol OrgCommand: Sendable {
131 /// Stable identifier, used by keymaps: `org.todo.cycle`.
132 var id: String { get }
133 /// Shown in the command palette.
134 var title: String { get }
135 /// Whether the command means something at the caret; context dispatch (one key, several
136 /// commands) runs the first that applies.
137 func applies(in context: EditContext) -> Bool
138 func run(in context: EditContext) -> CommandStep
139}
140
141public enum Commands {
142 public static let all: [any OrgCommand] = [
143 TodoCycle(), PriorityUp(), PriorityDown(), PromoteHeading(), DemoteHeading(),
144 InsertHeading(), InsertHeadingAfterSubtree(), InsertTodoHeading(),
145 MoveSubtreeUp(), MoveSubtreeDown(), PromoteSubtree(), DemoteSubtree(),
146 NextHeading(), PreviousHeading(), ForwardSameLevel(), BackwardSameLevel(), UpHeading(),
147 SetTags(),
148 InsertItem(), InsertCheckboxItem(), IndentItem(), OutdentItem(), IndentItemTree(), OutdentItemTree(),
149 MoveItemUp(), MoveItemDown(), ToggleCheckbox(),
150 InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true),
151 RemovePlanning(deadline: false), RemovePlanning(deadline: true),
152 ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false),
153 ]
154
155 public static func command(_ id: String) -> (any OrgCommand)? {
156 all.first { $0.id == id }
157 }
158}