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