Sources/OrgCore/Commands/Command.swift

e4d9b52b0ed18dbbe6402e33315f0e989b737988
orgstar/Sources/OrgCore/Commands/Command.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form