Sources/OrgCore/Commands/UserCommandAPI.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgCore/Commands/UserCommandAPI.swift

323 lines · 17597 bytes

21 symbols in this file
  1import Foundation
  2
  3/// Version 1 of the API user commands call (`org.text()`, `org.heading()`, …) and of the value
  4/// they return. Answers are JSON values (`String`, `Int`, `Bool`, `NSNull`, arrays and
  5/// dictionaries of them) computed from the context the command started with; offsets are UTF-16,
  6/// as JavaScript strings count them.
  7public enum UserCommandAPI {
  8    /// The answer to a call that reads the buffer: `text`, `selection`, `heading`, `outline`,
  9    /// `file` or `settings`; nil for any other name. `file` is the file's path relative to its
 10    /// folder.
 11    public static func answer(_ name: String, _ value: Any, context: EditContext, file: String?) -> Any? {
 12        switch name {
 13        case "text": return context.text
 14        case "selection": return context.selection.map(range)
 15        case "heading":
 16            let at = (value as? NSNumber).flatMap { integer($0) } ?? context.caret
 17            let model = DocumentModel(tree: context.tree)
 18            return heading(at: at, model: model, context: context).map { describe($0, model: model, context: context) } ?? NSNull()
 19        case "outline":
 20            let model = DocumentModel(tree: context.tree)
 21            return model.headings.indices.map { describe($0, model: model, context: context) }
 22        case "file": return file ?? NSNull()
 23        case "settings": return settings(context)
 24        default: return nil
 25        }
 26    }
 27
 28    static func range(_ range: Range<Int>) -> [String: Any] {
 29        ["from": range.lowerBound, "to": range.upperBound]
 30    }
 31
 32    /// The innermost heading whose subtree holds `offset`.
 33    static func heading(at offset: Int, model: DocumentModel, context: EditContext) -> Int? {
 34        let length = context.text.utf16.count
 35        return model.headings.indices.last { index in
 36            let section = model.headings[index].sectionRange
 37            return section.contains(offset) || (offset == section.upperBound && offset == length)
 38        }
 39    }
 40
 41    static func describe(_ index: Int, model: DocumentModel, context: EditContext) -> [String: Any] {
 42        let info = model.headings[index]
 43        let text = context.text as NSString
 44        var lineEnd = info.headingRange.upperBound
 45        if lineEnd > info.headingRange.lowerBound, text.character(at: lineEnd - 1) == 0x0A { lineEnd -= 1 }
 46        var node = context.tree.root
 47        while node.kind != .heading, let child = node.child(containing: info.headingRange.lowerBound) { node = child }
 48        let title = node.kind == .heading ? node.firstChild(.title)?.range : nil
 49        var properties: [String: Any] = [:]
 50        for property in info.properties { properties[property.key] = property.value }
 51        var described: [String: Any] = [
 52            "level": info.level,
 53            "keyword": info.todo ?? NSNull(),
 54            "done": info.isDone,
 55            "priority": info.priority ?? NSNull(),
 56            "title": info.title,
 57            "tags": info.localTags,
 58            "start": info.sectionRange.lowerBound,
 59            "end": info.sectionRange.upperBound,
 60            "titleStart": title?.lowerBound ?? lineEnd,
 61            "titleEnd": title?.upperBound ?? lineEnd,
 62            "properties": properties,
 63        ]
 64        let planning = Self.planning(text.substring(with: NSRange(location: info.headingRange.upperBound, length: max(0, nextLineEnd(after: info.headingRange.upperBound, in: text) - info.headingRange.upperBound))))
 65        for kind in ["scheduled", "deadline", "closed"] { described[kind] = planning[kind] ?? NSNull() }
 66        return described
 67    }
 68
 69    static func nextLineEnd(after offset: Int, in text: NSString) -> Int {
 70        guard offset < text.length else { return offset }
 71        let line = text.lineRange(for: NSRange(location: offset, length: 0))
 72        return NSMaxRange(line)
 73    }
 74
 75    private static let planningPattern = try! NSRegularExpression(pattern: #"\b(SCHEDULED|DEADLINE|CLOSED):\s*([<\[][^>\]\n]*[>\]])"#)
 76
 77    /// The timestamps of a planning line, by lowercased keyword; empty for any other line.
 78    static func planning(_ line: String) -> [String: String] {
 79        guard line.trimmingCharacters(in: .whitespaces).range(of: #"^(SCHEDULED|DEADLINE|CLOSED):"#, options: .regularExpression) != nil else { return [:] }
 80        var result: [String: String] = [:]
 81        let ns = line as NSString
 82        for match in planningPattern.matches(in: line, range: NSRange(location: 0, length: ns.length)) {
 83            result[ns.substring(with: match.range(at: 1)).lowercased()] = ns.substring(with: match.range(at: 2))
 84        }
 85        return result
 86    }
 87
 88    static func settings(_ context: EditContext) -> [String: Any] {
 89        let settings = context.tree.settings
 90        return [
 91            "todoKeywords": settings.todoSequences.flatMap { $0.active.map(\.name) },
 92            "doneKeywords": settings.todoSequences.flatMap { $0.done.map(\.name) },
 93            "priorities": ["highest": settings.priorities.highest, "lowest": settings.priorities.lowest, "default": settings.priorities.default],
 94            "fileTags": DocumentModel(tree: context.tree).fileTags,
 95            "tags": context.knownTags(),
 96            "fillColumn": context.options.fillColumn,
 97            "tagsColumn": context.options.tagsColumn,
 98        ]
 99    }
100
101    // MARK: - Results
102
103    /// What a command returned, as JSON, read into a result for the context it ran in: `edits`
104    /// (`{from, to, text}` in the text it was given, non-overlapping), `selection` (`{from, to}`,
105    /// a list of them or an offset, in the text after the edits), `message` and `copy`. Null is
106    /// no change. A message saying what is wrong when the value can't be used.
107    public static func result(_ json: String, in context: EditContext) -> Result<EditResult, Problem> {
108        guard let value = try? JSONSerialization.jsonObject(with: Data(json.utf8), options: .fragmentsAllowed) else {
109            return .failure(Problem("returned something that isn't JSON"))
110        }
111        if value is NSNull { return .success(EditResult(baseRevision: context.revision, edits: [])) }
112        guard let object = value as? [String: Any] else { return .failure(Problem("returned something other than an object")) }
113        if let key = object.keys.sorted().first(where: { !["edits", "selection", "message", "copy"].contains($0) }) {
114            return .failure(Problem("returned an unknown key \(key)"))
115        }
116        let text = context.text as NSString
117        var edits: [TextEdit] = []
118        if let raw = object["edits"], !(raw is NSNull) {
119            guard let list = raw as? [Any] else { return .failure(Problem("edits must be a list")) }
120            for (number, item) in zip(1..., list) {
121                guard let edit = item as? [String: Any], let from = (edit["from"] as? NSNumber).flatMap(integer) else {
122                    return .failure(Problem("edit \(number) needs a from offset"))
123                }
124                let to = edit["to"].map { ($0 as? NSNumber).flatMap(integer) } ?? from
125                guard let to else { return .failure(Problem("edit \(number) has a to that isn't an offset")) }
126                let replacement = edit["text"] ?? ""
127                guard let replacement = replacement as? String else { return .failure(Problem("edit \(number) has a text that isn't a string")) }
128                guard 0 <= from, from <= to, to <= text.length else { return .failure(Problem("edit \(number) is outside the text")) }
129                guard !splits(from, text), !splits(to, text) else { return .failure(Problem("edit \(number) splits a character")) }
130                edits.append(TextEdit(range: from..<to, replacement: replacement))
131            }
132        }
133        let sorted = edits.enumerated().sorted { ($0.element.range.lowerBound, $0.offset) < ($1.element.range.lowerBound, $1.offset) }.map(\.element)
134        for (a, b) in zip(sorted, sorted.dropFirst()) where b.range.lowerBound < a.range.upperBound || b.range.lowerBound == a.range.lowerBound {
135            return .failure(Problem("edits overlap"))
136        }
137        let length = text.length + sorted.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
138        var selection: [Range<Int>]?
139        if let raw = object["selection"], !(raw is NSNull) {
140            let items: [Any] = (raw as? [Any]) ?? [raw]
141            var ranges: [Range<Int>] = []
142            for item in items {
143                let bounds: (Int, Int)?
144                if let offset = (item as? NSNumber).flatMap(integer) {
145                    bounds = (offset, offset)
146                } else if let range = item as? [String: Any], let from = (range["from"] as? NSNumber).flatMap(integer) {
147                    bounds = range["to"].map { ($0 as? NSNumber).flatMap(integer).map { (from, $0) } } ?? (from, from)
148                } else {
149                    bounds = nil
150                }
151                guard let (from, to) = bounds, 0 <= min(from, to), max(from, to) <= length else {
152                    return .failure(Problem("selection is outside the text"))
153                }
154                ranges.append(min(from, to)..<max(from, to))
155            }
156            if !ranges.isEmpty { selection = ranges }
157        }
158        var effects: [Effect] = []
159        for key in ["message", "copy"] {
160            guard let raw = object[key], !(raw is NSNull) else { continue }
161            guard let string = raw as? String else { return .failure(Problem("\(key) must be a string")) }
162            effects.append(key == "message" ? .message(string) : .copy(string))
163        }
164        return .success(EditResult(baseRevision: context.revision, edits: sorted, selection: selection, effects: effects))
165    }
166
167    public struct Problem: Error, Equatable {
168        public let message: String
169        init(_ message: String) { self.message = message }
170    }
171
172    /// Whether `offset` falls between the two halves of a surrogate pair.
173    static func splits(_ offset: Int, _ text: NSString) -> Bool {
174        offset > 0 && offset < text.length && (0xDC00...0xDFFF).contains(text.character(at: offset))
175    }
176
177    static func integer(_ number: NSNumber) -> Int? {
178        guard CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }
179        let double = number.doubleValue
180        guard double.rounded() == double, abs(double) < 1e15 else { return nil }
181        return Int(double)
182    }
183
184    // MARK: - Prompts
185
186    /// A prompt from the value of `org.prompt(...)`: `message`, `initial`, `choices`,
187    /// `requireMatch` (default false) and `date`.
188    public static func prompt(_ value: Any) -> Prompt {
189        let options = value as? [String: Any] ?? [:]
190        let message = (options["message"] as? String) ?? (value as? String) ?? ""
191        let choices = (options["choices"] as? [Any])?.compactMap { $0 as? String } ?? []
192        let date = (options["date"] as? Bool) == true
193        return Prompt(
194            key: "user", message: message, initial: options["initial"] as? String ?? "", choices: choices,
195            requireMatch: (options["requireMatch"] as? Bool) == true && !choices.isEmpty,
196            date: date ? .init(defaultDate: nil) : nil
197        )
198    }
199
200    /// The answer the command gets: the text typed, or for a date prompt the date read from it,
201    /// `YYYY-MM-DD` or `YYYY-MM-DD HH:MM`.
202    public static func answer(_ text: String, to prompt: Prompt, now: Date, calendar: Calendar) -> String {
203        guard prompt.date != nil else { return text }
204        let read = ReadDate.read(text, default: nil, now: now, calendar: calendar)
205        let day = String(format: "%04d-%02d-%02d", read.year, read.month, read.day)
206        return read.timeGiven ? day + String(format: " %02d:%02d", read.hour, read.minute) : day
207    }
208
209    // MARK: - org.run
210
211    /// The commands of the app `org.run` runs; it refuses the others. An entry may not need a
212    /// window, a sheet or another file, and may not change the text.
213    public static let safeAppCommands: Set<String> = [
214        // Writes the buffer to its own file, as the person's own save would, once the command's
215        // changes are applied; nothing is saved when the command fails.
216        "app.save",
217    ]
218
219    /// The built-in command `org.run(id)` runs, or why it doesn't run `id`. `safeAppCommands`
220    /// are the caller's to handle.
221    public static func builtIn(_ id: String) -> Result<any OrgCommand, Problem> {
222        if id.hasPrefix(UserCommands.commandPrefix) { return .failure(Problem("A user command can't run another: \(id)")) }
223        if id.hasPrefix("app.") { return .failure(Problem("\(id) is a command of the app, which user commands can't run")) }
224        guard let command = Commands.command(id) else { return .failure(Problem("No built-in command \(id)")) }
225        return .success(command)
226    }
227
228    /// Why `org.run(id)` refused a command that asked for work outside the text.
229    public static func external(_ id: String) -> Problem {
230        Problem("\(id) needs work outside the text here (code blocks, Emacs, links, tangling or a view), which org.run doesn't do")
231    }
232}
233
234/// The buffer as a running user command sees it: the text it started with, changed by the
235/// built-in commands it ran with `org.run`. Calls read the current text, the command's
236/// returned edits are in it, and the result is one change from the starting text.
237public struct UserCommandState: Sendable {
238    /// The context the command started with.
239    public let start: EditContext
240    /// The text and selection now.
241    public private(set) var context: EditContext
242    let defaults: OrgSettings
243    /// Effects of the commands run that the result keeps: those without offsets.
244    private var effects: [Effect] = []
245    /// Whether a built-in command ran.
246    private var ran = false
247
248    /// `defaults` are the settings the buffer's tree was parsed with.
249    public init(_ start: EditContext, defaults: OrgSettings) {
250        self.start = start
251        context = start
252        self.defaults = defaults
253    }
254
255    /// Runs `command` at the current text and selection. A commit becomes the current state.
256    public mutating func run(_ command: any OrgCommand, answers: [String: String]) -> CommandStep {
257        let current = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: context.selection,
258                                  now: context.now, calendar: context.calendar, answers: answers, options: context.options,
259                                  knownTags: context.knownTags)
260        let step = command.run(in: current)
261        guard case .commit(let result) = step else { return step }
262        var text = context.text
263        var tree = context.tree
264        for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
265            tree = OrgParser.reparse(tree, oldText: text, edit: edit, defaults: defaults)
266            text = edit.apply(to: text)
267        }
268        var options = context.options
269        for effect in result.effects {
270            switch effect {
271            case .fold, .sparseTree, .snippet: continue
272            case .timer(let timer): options.timer = timer
273            default: break
274            }
275            effects.append(effect)
276        }
277        context = EditContext(revision: context.revision, text: text, tree: tree,
278                              selection: result.selection ?? Self.map(context.selection, through: result.edits),
279                              now: context.now, calendar: context.calendar, options: options, knownTags: context.knownTags)
280        ran = true
281        return step
282    }
283
284    /// What `org.run` resolves with: the text and the selections.
285    public var reply: [String: Any] {
286        ["text": context.text, "selection": context.selection.map(UserCommandAPI.range)]
287    }
288
289    /// The command's returned JSON, in the current text, as one result at the starting revision.
290    public func result(_ json: String) -> Result<EditResult, UserCommandAPI.Problem> {
291        let own: EditResult
292        switch UserCommandAPI.result(json, in: context) {
293        case .failure(let problem): return .failure(problem)
294        case .success(let result): own = result
295        }
296        guard ran else { return .success(own) }
297        var text = context.text
298        for edit in own.edits.reversed() { text = edit.apply(to: text) }
299        return .success(EditResult(baseRevision: start.revision, edits: TextEdit.between(start.text, text),
300                                   selection: own.selection ?? Self.map(context.selection, through: own.edits),
301                                   effects: effects + own.effects))
302    }
303
304    /// Ranges moved by edits that don't overlap: an offset inside or at the end of a replaced
305    /// range, or at an insertion, moves past the replacement.
306    static func map(_ ranges: [Range<Int>], through edits: [TextEdit]) -> [Range<Int>] {
307        let sorted = edits.sorted { $0.range.lowerBound < $1.range.lowerBound }
308        func map(_ offset: Int) -> Int {
309            var shift = 0
310            for edit in sorted {
311                let lower = edit.range.lowerBound, upper = edit.range.upperBound
312                if offset < lower || (offset == lower && upper > lower) { return offset + shift }
313                if offset <= upper { return lower + shift + edit.replacement.utf16.count }
314                shift += edit.replacement.utf16.count - edit.range.count
315            }
316            return offset + shift
317        }
318        return ranges.map { range in
319            let lower = map(range.lowerBound)
320            return lower..<max(lower, map(range.upperBound))
321        }
322    }
323}
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