Sources/OrgCore/Commands/UserCommandAPI.swift
208 lines · 11725 bytes
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}