Sources/OrgCore/Compute/TableFormulaCommands.swift
400 lines · 22172 bytes
1import Foundation
2
3/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the
4/// native evaluator can't do become a request to recalculate them in Emacs.
5public struct TableRecalculate: OrgCommand {
6 public let all: Bool
7 public init(all: Bool) { self.all = all }
8 public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" }
9 public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" }
10
11 public static var emacsMessage: String { EmacsFallback.wording("needs Emacs: ", "can't be calculated here: ") }
12
13 public func applies(in context: EditContext) -> Bool {
14 KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil
15 }
16
17 static func tblfmLine(in context: EditContext) -> String? {
18 let buffer = EmacsBuffer(context.text, point: context.caret)
19 let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
20 guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
21 return line
22 }
23
24 public func run(in context: EditContext) -> CommandStep {
25 let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
26 return Self.recalculating(context, form: form) { buffer in
27 if let line = Self.tblfmLine(in: context) {
28 // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
29 // point at the end of the table, then back where it was, even after an error.
30 let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
31 let saved = buffer.marker(buffer.point)
32 defer {
33 buffer.point = saved.position
34 buffer.release(saved)
35 }
36 guard let tableEnd = buffer.saveExcursion({ () -> Int? in
37 while buffer.forwardLine(-1) == 0 {
38 if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
39 }
40 return nil
41 }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
42 buffer.point = tableEnd
43 try buffer.tableRecalculate(all: true, tblfm: formulas)
44 } else {
45 try buffer.tableRecalculate(all: all)
46 }
47 }
48 }
49
50 /// `commitBuffer` for a recalculation. On an error the fields written before it stay, as
51 /// in Emacs, with the error as the message. A formula the native evaluator can't do makes
52 /// a request to run `form` in Emacs, which carries those fields for builds without Emacs.
53 static func recalculating(_ context: EditContext, form: String, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
54 var failure: String?
55 var unsupported: Calc.Unsupported?
56 let step = commitBuffer(context) { buffer in
57 do {
58 try body(buffer)
59 } catch let error as EmacsBuffer.UserError {
60 failure = error.message
61 } catch let error as Calc.Unsupported {
62 unsupported = error
63 }
64 }
65 guard case .commit(let result) = step else { return step }
66 if let unsupported {
67 let wrote = !result.edits.isEmpty
68 return request(form: form, reason: unsupported.reason, formula: wrote ? unsupported.formula : nil, partial: wrote ? result : nil, in: context)
69 }
70 guard let failure else { return step }
71 guard !result.edits.isEmpty else { return .failed(failure) }
72 return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(failure)]))
73 }
74
75 /// A step that failed with `emacsMessage` as a request to run `form` on the table in
76 /// Emacs, whose text then replaces the table here; other steps unchanged.
77 static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep {
78 guard case .failed(let message) = step, message.hasPrefix(emacsMessage) else { return step }
79 return request(form: form, reason: String(message.dropFirst(emacsMessage.count)), formula: nil, partial: nil, in: context)
80 }
81
82 static func request(form: String, reason: String, formula: String?, partial: EditResult?, in context: EditContext) -> CommandStep {
83 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
84 let onTblfm = tblfmLine(in: context) != nil
85 if onTblfm {
86 while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {}
87 }
88 let table = buffer.tableBegin()..<buffer.tableEnd()
89 let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
90 return .external(.emacsTable(
91 table: table, point: context.caret, form: form,
92 reason: reason, lisp: tblfm.contains("'("), formula: formula, partial: partial
93 ))
94 }
95}
96
97/// C-u C-u C-c *: `org-table-iterate`, the whole table recalculated until it stops changing,
98/// at most ten times.
99public struct TableIterate: OrgCommand {
100 public init() {}
101 public var id: String { "org.table.iterate" }
102 public var title: String { "Iterate Table Formulas" }
103 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
104
105 public func run(in context: EditContext) -> CommandStep {
106 var message = ""
107 let step = TableRecalculate.recalculating(context, form: "(org-table-iterate)") { buffer in
108 guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
109 func table() -> String { buffer.substring(buffer.tableBegin(), buffer.tableEnd()) }
110 var last = table()
111 for iteration in 1...10 {
112 try buffer.tableRecalculate(all: true)
113 let this = table()
114 if this == last {
115 message = iteration > 1 ? "Convergence after \(iteration) iterations" : "Table was already stable"
116 return
117 }
118 last = this
119 }
120 // The recalculations stay, as Emacs leaves them before its error.
121 message = "No convergence after 10 iterations"
122 }
123 guard case .commit(let result) = step, !message.isEmpty else { return step }
124 return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(message)]))
125 }
126}
127
128// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
129extension EmacsBuffer {
130 /// `org-table-maybe-recalculate-line`: a row whose first field is `#` recalculated, as
131 /// TAB, S-TAB and RET in a table do first.
132 func tableMaybeRecalculateLine() throws {
133 guard lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else { return }
134 try tableRecalculate(all: false)
135 }
136
137 /// `org-table-formula-make-cmp-string`.
138 static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
139 var a = lhs
140 if let arrow = a.firstMatch(of: /^\$([<>])/) {
141 a = (try? handleFirstLast(a, analysis: analysis)) ?? a
142 a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))"
143 }
144 guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil }
145 var key = ""
146 if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) }
147 if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) }
148 if let name = m.5 { key += "@@" + name }
149 return key
150 }
151
152 /// `sort` with `org-table-formula-less-p`.
153 static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] {
154 var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = []
155 // Stable insertion, as `sort` with a partial predicate.
156 for formula in formulas {
157 let key = formulaSortKey(formula.lhs, analysis: analysis)
158 var index = sorted.count
159 while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 }
160 sorted.insert((formula, key), at: index)
161 }
162 return sorted.map(\.formula)
163 }
164
165 /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`.
166 func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) {
167 let sorted = Self.sortFormulas(formulas, analysis: analysis)
168 saveExcursion {
169 point = tableEnd()
170 if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) {
171 deleteRegion(match[3]!.lowerBound, match[0]!.upperBound)
172 point = match[3]!.lowerBound
173 } else {
174 insert("#+TBLFM:")
175 }
176 insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n")
177 }
178 }
179
180 /// `org-table-get-formula`: stores EQUATION for the current column, or with `named` the
181 /// current field, and returns it; nil when a blank EQUATION removed the formula. `read`
182 /// when EQUATION is the prompt's answer, which the stored formula never replaces.
183 func tableGetFormula(_ equation: String, named: Bool, read: Bool = false, analysis: TableAnalysis) throws -> String? {
184 var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "")
185 let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())"
186 let scol = named ? ref : "$\(tableCurrentColumn())"
187 let old = stored.first { $0.lhs == scol }?.rhs
188 var eq = !read && old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation
189 guard eq.contains(where: { !$0.isWhitespace }) else {
190 stored.removeAll { $0.lhs == scol }
191 tableStoreFormulas(stored, analysis: analysis)
192 // Org's user error, which keeps the stored formulas and stops the command.
193 message = "Formula removed"
194 return nil
195 }
196 eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression)
197 eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression)
198 var mustSave = false
199 if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) {
200 stored.remove(at: index)
201 mustSave = true
202 }
203 if let index = stored.firstIndex(where: { $0.lhs == scol }) {
204 stored[index].rhs = eq
205 } else {
206 stored.insert((scol, eq), at: 0)
207 }
208 if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) }
209 return eq
210 }
211
212 /// `org-table-eval-formula` for the current field with EQUATION, which is stored first.
213 /// A formula only Emacs can evaluate stays stored, the field unchanged.
214 func tableEvalFormula(equation: String, named: Bool, read: Bool = false) throws {
215 try checkInsideDataField()
216 let analysis = try tableAnalyze()
217 guard let formula = try tableGetFormula(equation, named: named, read: read, analysis: analysis) else { return }
218 do {
219 try tableEvalFormula(formula, analysis: analysis, substituted: false)
220 } catch let error as Calc.Unsupported {
221 message = EmacsFallback.wording("The formula was stored; recalculating it needs Emacs: ", "The formula was stored; it can't be calculated here: ") + error.reason
222 }
223 tableAlign()
224 }
225
226 /// `org-table-maybe-eval-formula`.
227 func tableMaybeEvalFormula() throws {
228 skipBackwardNot([124, 10])
229 guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return }
230 let start = point
231 var end = point
232 while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 }
233 point = min(lineEnd(point), start + 1)
234 let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
235 guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return }
236 try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":"))
237 }
238}
239
240/// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's
241/// formula, the stored one offered.
242public struct TableEvalFormula: OrgCommand {
243 let named: Bool
244 public init(named: Bool) { self.named = named }
245 public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" }
246 public var title: String { named ? "Set Field Formula" : "Set Column Formula" }
247 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
248 public func run(in context: EditContext) -> CommandStep {
249 guard let answer = context.answers["formula"] else {
250 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
251 guard buffer.atTable else { return .failed("Not at a table") }
252 let column = buffer.tableCurrentColumn()
253 let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)"
254 let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs
255 return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? ""))
256 }
257 return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named, read: true) }
258 }
259}
260
261// The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor.
262extension BlockEdit {
263 static let formulasKind = "formulas"
264
265 /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as
266 /// org's editor lists them. The range runs from the table (or that line) to the formulas.
267 public static func formulas(at offset: Int, text: String) -> BlockEdit? {
268 let buffer = EmacsBuffer(text, point: offset)
269 let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset))
270 let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil
271 guard atTblfm || buffer.atTable else { return nil }
272 let start: Int
273 let end: Int
274 let formulas: [(lhs: String, rhs: String)]
275 if atTblfm {
276 start = buffer.lineStart(offset)
277 end = min(buffer.length, buffer.lineEnd(offset) + 1)
278 let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " "))
279 formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? []
280 guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil }
281 } else {
282 start = buffer.tableBegin()
283 let tableEnd = buffer.tableEnd()
284 end = buffer.saveExcursion {
285 buffer.point = tableEnd
286 return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd
287 }
288 formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? []
289 }
290 guard let analysis = try? buffer.tableAnalyze() else { return nil }
291 var content = ""
292 var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")]
293 for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) {
294 let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named"
295 if let index = titles.firstIndex(where: { $0.type == type }) {
296 if !content.isEmpty { content += "\n" }
297 content += titles[index].title
298 titles.remove(at: index)
299 }
300 content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n"
301 }
302 let ns = text as NSString
303 return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind)
304 }
305
306 /// `org-table-fedit-finish`'s reading of the editor's text.
307 static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] {
308 let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines)
309 let ns = content as NSString
310 var result: [(lhs: String, rhs: String)] = []
311 for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) {
312 let lhs = ns.substring(with: m.range(at: 1))
313 var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
314 guard !rhs.isEmpty else { continue }
315 rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
316 if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") }
317 result.insert((lhs, rhs), at: 0)
318 }
319 return result
320 }
321
322 /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument.
323 func installFormulas(_ content: String, in context: EditContext) -> CommandStep {
324 let step = commitBuffer(context) { buffer in
325 let formulas = try Self.parseFormulas(content)
326 buffer.point = range.lowerBound
327 let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in
328 if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) }
329 return try buffer.tableAnalyze()
330 }
331 buffer.tableStoreFormulas(formulas, analysis: analysis)
332 }
333 guard case .commit(let result) = step else { return step }
334 return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection,
335 effects: result.effects + [.message("New formulas installed - Recalculate Table (C-c C-c on the #+TBLFM line) applies them.")]))
336 }
337}
338
339// `org-table-edit-field` (C-c `): a field's text edited apart, then put back.
340extension BlockEdit {
341 static let fieldKind = "field"
342
343 /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged.
344 public static func field(at offset: Int, text: String) -> BlockEdit? {
345 let buffer = EmacsBuffer(text, point: offset)
346 guard buffer.insideDataField else { return nil }
347 let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())"
348 let field = buffer.saveExcursion { () -> String in
349 buffer.skipBackwardNot([124, 10])
350 return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound)
351 }
352 let start = buffer.lineStart(offset)
353 let end = buffer.lineEnd(offset)
354 return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines),
355 language: nil, kind: fieldKind, point: offset, coordinate: coordinate)
356 }
357
358 /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the
359 /// table is aligned.
360 func installField(_ content: String, in context: EditContext) -> CommandStep {
361 var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression)
362 text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression)
363 text = text.trimmingCharacters(in: .whitespacesAndNewlines)
364 return commitBuffer(context) { buffer in
365 buffer.point = point ?? range.lowerBound
366 guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") }
367 buffer.skipBackwardNot([124, 10])
368 let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound
369 buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text)
370 buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1)
371 buffer.tableAlign()
372 }
373 }
374}
375
376extension EmacsBuffer {
377 /// `org-table-check-inside-data-field` with NOERROR.
378 var insideDataField: Bool {
379 atTable && !atTableHline
380 && !saveExcursion { () -> Bool in
381 while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 }
382 return bolp
383 }
384 && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil
385 }
386}
387
388/// C-c `: `org-table-edit-field`, in the block editor.
389public struct TableEditField: OrgCommand {
390 public init() {}
391 public var id: String { "org.table.edit-field" }
392 public var title: String { "Edit Table Field" }
393 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
394 public func run(in context: EditContext) -> CommandStep {
395 guard let edit = BlockEdit.field(at: context.caret, text: context.text) else {
396 return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table")
397 }
398 return .external(.editBlock(edit))
399 }
400}