Sources/OrgCore/Compute/TableFormulas.swift
1229 lines · 65639 bytes
1import Foundation
2
3// Table formulas (org-table.el, Org 9.8.7): `org-table-recalculate` and
4// `org-table-eval-formula` with Calc and Lisp evaluated natively. Symbolic results, Calc
5// features beyond `Calc`, Lisp beyond `Elisp`, remote tables found by ID and relative field
6// targets throw `Calc.Unsupported`; the caller then recalculates the table in Emacs.
7
8/// Where `remote()` finds tables by ID in other files.
9public enum RemoteTables {
10 /// The text of the file holding the entry with an ID; the app sets it, from its index.
11 nonisolated(unsafe) public static var fileWithID: ((String) -> String?)?
12}
13
14extension EmacsBuffer {
15 struct TableAnalysis {
16 /// Table-relative line index of each data line, from 1 (index 0 unused).
17 var dlines: [Int]
18 /// Hline flag per line, with an extra hline after the last.
19 var types: [Bool]
20 var ncol: Int
21 var begin: Int
22 /// `org-table-column-names`: from the first `!` row.
23 var columnNames: [(name: String, column: Int)] = []
24 /// `org-table-local-parameters`, in the order org pushes them; the last match wins.
25 var parameters: [(name: String, value: String)] = []
26 /// `org-table-named-field-locations`: the table-relative line and the column.
27 var namedFields: [(name: String, line: Int, column: Int)] = []
28 /// A row marked for calculation (`org-table-calculate-mark-regexp`).
29 var marked = false
30 }
31
32 static let tblfmPattern = "^[ \\t]*#\\+TBLFM: *(.*)"
33 static let rangePattern = "@([-+]?I*[-+]?[0-9]*)(\\$[-+]?[0-9]+)?(\\.\\.@?([-+]?I*[-+]?[0-9]*)(\\$[-+]?[0-9]+)?)?"
34
35 /// `org-table-analyze`.
36 func tableAnalyze() throws -> TableAnalysis {
37 let begin = tableBegin()
38 let end = tableEnd()
39 return try saveExcursion {
40 point = begin
41 var dlines = [0]
42 var types: [Bool] = []
43 var lines: [String] = []
44 var line = 0
45 while point < end || (point == end && false) {
46 let content = substring(lineStart(point), lineEnd(point))
47 guard content.range(of: "^[ \\t]*\\|", options: .regularExpression) != nil else { break }
48 lines.append(content)
49 let isHline = content.range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil
50 types.append(isHline)
51 if !isHline { dlines.append(line) }
52 line += 1
53 if forwardLine(1) != 0 || point >= end { break }
54 }
55 types.append(true)
56 guard dlines.count > 1 else { throw UserError(message: "No data lines in table") }
57 point = begin
58 forwardLine(dlines[1])
59 let first = substring(lineStart(point), lineEnd(point))
60 let ncol = Self.splitFields(first, separator: "[ \\t]*\\|[ \\t]*").count
61 var analysis = TableAnalysis(dlines: dlines, types: types, ncol: ncol, begin: begin)
62 Self.names(lines, into: &analysis)
63 return analysis
64 }
65 }
66
67 /// The names part of `org-table-analyze`.
68 static func names(_ lines: [String], into analysis: inout TableAnalysis) {
69 let identifier = "^[a-zA-Z][_a-zA-Z0-9]*$"
70 func rest(_ line: String, _ pattern: String) -> String? {
71 guard let m = try! NSRegularExpression(pattern: pattern).firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) else { return nil }
72 return (line as NSString).substring(with: m.range(at: m.numberOfRanges - 1))
73 }
74 if let names = lines.lazy.compactMap({ rest($0, "^[ \\t]*\\| *! *(\\|.*)") }).first {
75 for (i, name) in splitFields(names, separator: " *\\| *").enumerated() where name.range(of: identifier, options: .regularExpression) != nil {
76 analysis.columnNames.append((name, i + 2))
77 }
78 }
79 for line in lines {
80 guard let fields = rest(line, "^[ \\t]*\\| *\\$ *(\\|.*)") else { continue }
81 for field in splitFields(fields, separator: " *\\| *") {
82 if let m = field.firstMatch(of: /^([a-zA-Z][_a-zA-Z0-9]*|%) *= *(.*)/) { analysis.parameters.append((String(m.1), String(m.2))) }
83 }
84 }
85 for (k, line) in lines.enumerated() {
86 guard let m = line.firstMatch(of: /^[ \t]*\| *([_^]) *(\|.*)/) else { continue }
87 let target = m.1 == "_" ? k + 1 : k - 1
88 guard lines.indices.contains(target), let values = rest(lines[target], "^[ \\t]*\\|[^|]*(\\|.*)") else { continue }
89 for (i, (name, value)) in zip(splitFields(String(m.2), separator: " *\\| *"), splitFields(values, separator: " *\\| *")).enumerated()
90 where name.range(of: identifier, options: .regularExpression) != nil {
91 analysis.parameters.append((name, value))
92 analysis.namedFields.append((name, target, i + 2))
93 }
94 }
95 analysis.marked = lines.contains { $0.range(of: "^[ \\t]*\\| *[!$^_#*] *(\\||$)", options: .regularExpression) != nil }
96 }
97
98 /// `org-split-string`: leading and trailing separators produce no empty strings.
99 static func splitFields(_ s: String, separator: String) -> [String] {
100 let ns = s as NSString
101 let regex = try! NSRegularExpression(pattern: separator)
102 let matches = regex.matches(in: s, range: NSRange(location: 0, length: ns.length))
103 guard !matches.isEmpty else { return [s] }
104 var results: [String] = []
105 var i = 0
106 for (k, m) in matches.enumerated() {
107 if k == 0, m.range.location == 0 {
108 i = NSMaxRange(m.range)
109 continue
110 }
111 results.append(ns.substring(with: NSRange(location: i, length: m.range.location - i)))
112 i = NSMaxRange(m.range)
113 }
114 if i != ns.length { results.append(ns.substring(from: i)) }
115 return results
116 }
117
118 /// `org-table-get-stored-formulas` from the `#+TBLFM` text `line`.
119 static func storedFormulas(_ line: String) throws -> [(lhs: String, rhs: String)] {
120 var result: [(String, String)] = []
121 var seen: Set<String> = []
122 let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|\\$([_a-zA-Z0-9]+|[<>]+)) *= *(.*[^ \\t])")
123 for part in splitFields(line, separator: " *:: *") {
124 let ns = part as NSString
125 guard let m = regex.firstMatch(in: part, range: NSRange(location: 0, length: ns.length)) else { continue }
126 let whole = ns.substring(with: m.range(at: 1))
127 var lhs = whole
128 if m.range(at: 2).location != NSNotFound,
129 whole.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) == nil {
130 lhs = ns.substring(with: m.range(at: 2))
131 }
132 guard seen.insert(lhs).inserted else { throw UserError(message: "Double definition `\(lhs)=' in TBLFM line, please fix by hand") }
133 result.append((lhs, ns.substring(with: m.range(at: 3))))
134 }
135 return result
136 }
137
138 /// The first `#+TBLFM` line after the table, blank lines allowed between.
139 func firstTblfm(after end: Int) -> String? {
140 saveExcursion {
141 point = end
142 while !eobp {
143 let line = substring(lineStart(point), lineEnd(point))
144 if line.trimmingCharacters(in: .whitespaces).isEmpty {
145 if forwardLine(1) != 0 { return nil }
146 continue
147 }
148 guard let r = line.range(of: Self.tblfmPattern, options: [.regularExpression, .caseInsensitive]) else { return nil }
149 let text = String(line[r])
150 return String(text[text.index(after: text.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
151 }
152 return nil
153 }
154 }
155
156 /// `org-table-formula-handle-first/last-rc`.
157 static func handleFirstLast(_ s: String, analysis: TableAnalysis) throws -> String {
158 var result = s
159 var start = 0
160 let regex = try! NSRegularExpression(pattern: "([@$])(<+|>+)|(remote\\([^)]+\\))")
161 while let m = regex.firstMatch(in: result, range: NSRange(location: start, length: (result as NSString).length - start)) {
162 let ns = result as NSString
163 if m.range(at: 3).location != NSNotFound {
164 start = NSMaxRange(m.range(at: 3))
165 continue
166 }
167 let kind = ns.substring(with: m.range(at: 1))
168 let nmax = kind == "@" ? analysis.dlines.count - 1 : analysis.ncol
169 let marks = ns.substring(with: m.range(at: 2))
170 let n = marks.first == "<" ? marks.count : nmax - marks.count + 1
171 if n < 1 || n > nmax { throw UserError(message: "Reference \"\(ns.substring(with: m.range))\" in expression \"\(result)\" points outside table") }
172 start = m.range.location
173 result = ns.replacingCharacters(in: m.range, with: kind + String(n))
174 }
175 return result
176 }
177
178 /// `org-table--row-type`.
179 static func rowType(hline: Bool, _ n: Int, _ start: Int, backwards: Bool, relative: Bool, analysis: TableAnalysis, desc: String) throws -> Int {
180 var i = start
181 let l = analysis.types.count
182 for _ in 0..<n {
183 while true {
184 i += backwards ? -1 : 1
185 guard i >= 0, i < l, analysis.types[i] != hline else { break }
186 }
187 }
188 if i < 0 || i >= l { throw UserError(message: "Row descriptor \(desc) leads outside table") }
189 return i == l - 1 ? i - 1 : i
190 }
191
192 /// `org-table--descriptor-line`.
193 static func descriptorLine(_ desc: String, _ cline: Int, analysis: TableAnalysis) throws -> Int {
194 if let n = Int(desc), desc.allSatisfy(\.isNumber) {
195 guard n < analysis.dlines.count else { throw Calc.Unsupported("row out of range") }
196 return analysis.dlines[n]
197 }
198 let ns = desc as NSString
199 let regex = try! NSRegularExpression(pattern: "^(([-+])?(I+))?(([-+])?([0-9]+))?")
200 let m = regex.firstMatch(in: desc, range: NSRange(location: 0, length: ns.length))!
201 func has(_ i: Int) -> Bool { m.range(at: i).location != NSNotFound }
202 if (!has(3) && !has(6)) || (has(3) && has(6) && !has(5)) { throw UserError(message: "Invalid row descriptor `\(desc)'") }
203 var hn = has(3) ? m.range(at: 3).length : nil
204 var hdir = has(2) ? ns.substring(with: m.range(at: 2)) : nil
205 let odir = has(5) ? ns.substring(with: m.range(at: 5)) : nil
206 let on = has(6) ? Int(ns.substring(with: m.range(at: 6))) : nil
207 let rel = has(6) && ((has(1) && !has(3)) || has(5))
208 var cline = cline
209 if hn != nil, hdir == nil {
210 cline = 0
211 hdir = "+"
212 if analysis.types[0] { hn! -= 1 }
213 }
214 if hn == nil, on != nil, odir == nil { throw UserError(message: "Should never happen") }
215 if let hn { cline = try rowType(hline: true, hn, cline, backwards: hdir == "-", relative: false, analysis: analysis, desc: desc) }
216 if let on { cline = try rowType(hline: false, on, cline, backwards: odir == "-", relative: rel, analysis: analysis, desc: desc) }
217 return cline
218 }
219
220 /// `org-table-get-field` on the line at point.
221 func tableField(_ column: Int) -> String {
222 saveExcursion {
223 tableGotoColumn(column)
224 skipBackwardNot([124, 10])
225 if bolp || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { return "" }
226 let start = point
227 while let c = character(at: point), c != 124, c != 10, c != 13 { point += 1 }
228 return substring(start, point)
229 }
230 }
231
232 func isDataLine() -> Bool {
233 looking("^[ \\t]*\\|[^-]", caseInsensitive: false, setsMatch: false) != nil
234 || substring(lineStart(point), lineEnd(point)).range(of: "^[ \\t]*\\|[^-]", options: .regularExpression) != nil
235 }
236
237 func gotoTableLine(_ line: Int, _ analysis: TableAnalysis) {
238 point = analysis.begin
239 forwardLine(line)
240 }
241
242 /// `org-table-get-range`: one field's text, or the fields of a rectangle.
243 func tableRange(_ desc: String, thisline: Int, col: Int, analysis: TableAnalysis) throws -> TableRangeValue {
244 var desc = desc
245 if desc.range(of: "^\\$[0-9]+\\.\\.\\$[0-9]+$", options: .regularExpression) != nil {
246 desc = desc.replacingOccurrences(of: "$", with: "@0$")
247 }
248 let ns = desc as NSString
249 guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
250 throw UserError(message: "Invalid table range specifier `\(desc)'")
251 }
252 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
253 let isRange = group(3) != nil
254 func row(_ r: String?) throws -> Int {
255 guard let r, r.contains(where: { !$0.isWhitespace }) else { return thisline }
256 return try Self.descriptorLine(r, thisline, analysis: analysis)
257 }
258 func column(_ c: String?) -> Int {
259 guard let c else { return col }
260 let body = String(c.dropFirst())
261 let n = Int(body) ?? 0
262 if n == 0 { return col }
263 return n + (body.first == "-" || body.first == "+" ? col : 0)
264 }
265 let r1 = try row(group(1))
266 let r2 = try row(group(4))
267 let c1 = column(group(2))
268 let c2 = column(group(5))
269 return try saveExcursion {
270 if !isRange || (r1 == r2 && c1 == c2) {
271 gotoTableLine(r1, analysis)
272 while !isDataLine() {
273 if forwardLine(1) != 0 { throw Calc.Unsupported("reference outside table") }
274 }
275 return .field(tableField(c1).trimmingCharacters(in: .whitespaces))
276 }
277 var firstRow = min(r1, r2)
278 let lastRow = max(r1, r2)
279 let firstColumn = min(c1, c2)
280 let lastColumn = max(c1, c2)
281 gotoTableLine(firstRow, analysis)
282 while !isDataLine() {
283 if forwardLine(1) != 0 { throw Calc.Unsupported("reference outside table") }
284 firstRow += 1
285 }
286 let startLine = lineStart(point)
287 forwardLine(lastRow - firstRow)
288 while !isDataLine() { forwardLine(-1) }
289 let endLine = lineStart(point)
290 var fields: [String] = []
291 point = startLine
292 while point <= endLine {
293 if !atTableHline {
294 for c in firstColumn...lastColumn { fields.append(tableField(c).trimmingCharacters(in: .whitespaces)) }
295 }
296 if forwardLine(1) != 0 { break }
297 }
298 return .list(fields)
299 }
300 }
301
302 enum TableRangeValue {
303 case field(String)
304 case list([String])
305 }
306
307 static let calcNumber = "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?$"
308 /// `org-ts-regexp-both`.
309 static let timestampBoth = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)[\\]>]"
310
311 /// How `org-table-make-reference` turns fields into formula text.
312 struct ReferenceMode {
313 enum Lisp { case none, lisp, literal }
314 var keepEmpty = false
315 var numbers = false
316 var lisp = Lisp.none
317 }
318
319 /// `number-to-string` of `string-to-number`.
320 static func numberText(_ s: String) -> String { Elisp.printed(Elisp.stringToNumber(s)) }
321
322 /// `org-table-make-reference`. For Calc, a field that isn't a number, a date or `nan`
323 /// would be a symbol, which isn't supported.
324 static func makeReference(_ value: TableRangeValue, _ mode: ReferenceMode) throws -> String {
325 func blank(_ s: String) -> Bool { !s.contains { !$0.isWhitespace } }
326 func lisp(_ s: String) -> String {
327 switch mode.lisp {
328 case .literal: s
329 default: mode.numbers ? numberText(s) : Elisp.printed(.string(s), escape: true)
330 }
331 }
332 func calc(_ s: String) throws -> String {
333 let text = mode.numbers ? numberText(s) : s
334 guard text.range(of: calcNumber, options: .regularExpression) != nil || text == "nan"
335 || text.range(of: "^" + timestampBoth + "$", options: .regularExpression) != nil else {
336 throw Calc.Unsupported("non-numeric field \(text)")
337 }
338 return text
339 }
340 let empty = !mode.keepEmpty || mode.numbers ? "0" : "nan"
341 switch value {
342 case .field(let s):
343 if mode.lisp != .none { return lisp(s) }
344 return blank(s) ? (empty == "0" ? "(0)" : "nan") : "(" + (try calc(s)) + ")"
345 case .list(var items):
346 if !mode.keepEmpty { items = items.filter { !blank($0) } }
347 if mode.lisp != .none { return items.map(lisp).joined(separator: " ") }
348 return "[" + (try items.map { blank($0) ? empty : try calc($0) }).joined(separator: ",") + "]"
349 }
350 }
351
352 /// A number written in a formula, small enough to work with.
353 static func integer(_ s: String) throws -> Int {
354 guard let n = Int(s.hasPrefix("+") ? String(s.dropFirst()) : s), (-999_999_999...999_999_999).contains(n) else { throw Calc.Unsupported("number size \(s)") }
355 return n
356 }
357
358 /// `org-table-time-string-to-seconds`.
359 static func timeStringToSeconds(_ s: String) throws -> String {
360 guard !s.isEmpty else { return s }
361 func seconds(_ sign: Substring, _ parts: [Substring]) throws -> String {
362 var total = 0
363 for (i, part) in parts.enumerated() {
364 let (scaled, o1) = (Int(part) ?? Int.max).multipliedReportingOverflow(by: [3600, 60, 1][i])
365 let (sum, o2) = total.addingReportingOverflow(scaled)
366 if o1 || o2 || Int(part) == nil { throw Calc.Unsupported("duration size") }
367 total = sum
368 }
369 return String(sign.isEmpty ? total : -total)
370 }
371 if let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+):([0-9]+)/) { return try seconds(m.1, [m.2, m.3, m.4]) }
372 if s.range(of: timestampBoth, options: .regularExpression) == nil, let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+)/) {
373 return try seconds(m.1, [m.2, m.3])
374 }
375 return numberText(s)
376 }
377
378 enum DurationFormat { case hms, hhmm, hours }
379
380 /// `org-table-time-seconds-to-string`, with `org-table-duration-custom-format` `hours`
381 /// and zero-padded hours.
382 static func secondsToString(_ seconds: Sexp, _ format: DurationFormat) throws -> String {
383 let value = (try? Elisp.number(seconds))?.double ?? 0
384 let magnitude = abs(value)
385 guard magnitude.isFinite, magnitude < 1e15 else { throw Calc.Unsupported("duration size") }
386 let result: String
387 switch format {
388 case .hours:
389 result = String(format: "%.2f", magnitude / 3600)
390 case .hms, .hhmm:
391 let total = Int(magnitude.rounded(.down))
392 let hms = String(format: "%02d:%02d:%02d", total / 3600, total / 60 % 60, total % 60)
393 result = format == .hhmm ? String(hms.dropLast(3)) : hms
394 }
395 return value < 0 ? "-" + result : result
396 }
397
398 /// `org-table-convert-refs-to-rc` for a remote reference: `B3` is `@3$2`.
399 static func refsToRC(_ s: String) -> String {
400 let regex = try! NSRegularExpression(pattern: "(?<![A-Za-z0-9_$@])([a-zA-Z]{1,2})([0-9]+)(?![A-Za-z0-9_])")
401 var out = s
402 while let m = regex.firstMatch(in: out, range: NSRange(location: 0, length: (out as NSString).length)) {
403 let ns = out as NSString
404 let column = ns.substring(with: m.range(at: 1)).uppercased().unicodeScalars.reduce(0) { $0 * 26 + Int($1.value) - 64 }
405 out = ns.replacingCharacters(in: m.range, with: "@\(ns.substring(with: m.range(at: 2)))$\(column)")
406 }
407 return out
408 }
409
410 /// `org-table-get-constant`: a parameter or named field, a `#+CONSTANTS` value, or the
411 /// entry's property for `PROP_name`.
412 func tableConstant(_ name: String, analysis: TableAnalysis) -> String {
413 if let parameter = analysis.parameters.last(where: { $0.name == name }) { return parameter.value }
414 for m in (settings.setupKeywords + string).matches(of: #/(?mi)^[ \t]*#\+CONSTANTS:(.*)$/#) {
415 for pair in m.1.split(whereSeparator: \.isWhitespace) {
416 let parts = pair.split(separator: "=", maxSplits: 1)
417 if parts.count == 2, parts[0] == name { return String(parts[1]) }
418 }
419 }
420 if name.hasPrefix("PROP_"), let value = inheritedProperty(String(name.dropFirst(5)))?.value { return value }
421 return "#UNDEFINED_NAME"
422 }
423
424 /// `org-table-formula-substitute-names`: column names become `$N`; parameters, named
425 /// fields and constants their values, in parentheses outside Lisp formulas.
426 func substituteNames(_ formula: String, analysis: TableAnalysis) throws -> String {
427 let parenthesize = !formula.hasPrefix("'")
428 let duration = formula.range(of: ";.*[Tt].*$", options: .regularExpression) != nil
429 var new = formula
430 if !analysis.columnNames.isEmpty {
431 let names = analysis.columnNames.map { NSRegularExpression.escapedPattern(for: $0.name) }.joined(separator: "|")
432 let regex = try! NSRegularExpression(pattern: "\\$(\(names))(?![[:alnum:]])")
433 var start = 0
434 while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
435 let ns = new as NSString
436 let column = analysis.columnNames.first { $0.name == ns.substring(with: m.range(at: 1)) }!.column
437 new = ns.replacingCharacters(in: m.range, with: "$\(column)")
438 start = m.range.location + 1
439 }
440 }
441 let regex = try! NSRegularExpression(pattern: "\\$([a-zA-Z][_a-zA-Z0-9]*)|(\\bremote\\([^)]*\\))")
442 var start = 0
443 var substitutions = 0
444 while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
445 let ns = new as NSString
446 // A constant whose value names itself would go on forever, as it does in Org.
447 substitutions += 1
448 if substitutions > 1000 { throw Calc.Unsupported("constants that refer to themselves") }
449 if m.range(at: 2).location != NSNotFound {
450 start = NSMaxRange(m.range(at: 2))
451 continue
452 }
453 start = m.range.location + 1
454 var value = tableConstant(ns.substring(with: m.range(at: 1)), analysis: analysis)
455 if duration, value.contains(where: { !$0.isWhitespace }) { value = try Self.timeStringToSeconds(value) }
456 new = ns.replacingCharacters(in: m.range, with: parenthesize ? "(" + value + ")" : value)
457 }
458 return new
459 }
460
461 /// `org-table-get-remote-range`: the table after `#+NAME: name` in this file, or the first
462 /// table in the entry with that ID, in this file or another.
463 func remoteRange(_ name: String, _ form: String) throws -> TableRangeValue {
464 let escaped = NSRegularExpression.escapedPattern(for: name)
465 let keyword = try! NSRegularExpression(pattern: "^[ \\t]*#\\+(tbl)?name:[ \\t]*" + escaped + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
466 let idLine = try! NSRegularExpression(pattern: "^[ \\t]*:ID:[ \\t]+" + escaped + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
467 func first(_ regex: NSRegularExpression, in text: String) -> Int? {
468 regex.firstMatch(in: text, range: NSRange(location: 0, length: (text as NSString).length))?.range.location
469 }
470 // `org-id-find`: the entry's heading, here or in the file holding the ID.
471 func heading(_ text: String, _ offset: Int) -> Int {
472 let before = try! NSRegularExpression(pattern: "^\\*+ ", options: .anchorsMatchLines)
473 return before.matches(in: text, range: NSRange(location: 0, length: offset)).last?.range.location ?? 0
474 }
475 var text = string
476 let location: Int
477 if let found = first(keyword, in: string) {
478 location = found
479 } else if let found = first(idLine, in: string) {
480 location = heading(string, found)
481 } else if let other = RemoteTables.fileWithID?(name), let found = first(idLine, in: other) {
482 text = other
483 location = heading(other, found)
484 } else {
485 throw UserError(message: "Can't find remote table \"\(name)\"")
486 }
487 let ns = text as NSString
488 let after = min(ns.length, location + 1)
489 let next = try! NSRegularExpression(pattern: "^(\\*+ )|^[ \\t]*\\|", options: .anchorsMatchLines)
490 guard let m = next.firstMatch(in: text, range: NSRange(location: after, length: ns.length - after)),
491 m.range(at: 1).location == NSNotFound else {
492 throw UserError(message: "Cannot find a table at NAME or ID \(name)")
493 }
494 let remote = EmacsBuffer(text, point: m.range.location, settings: settings, options: options)
495 let analysis = try remote.tableAnalyze()
496 let resolved = try remote.substituteNames(try Self.handleFirstLast(Self.refsToRC(form), analysis: analysis), analysis: analysis)
497 let range = try! NSRegularExpression(pattern: Self.rangePattern)
498 let rns = resolved as NSString
499 if let r = range.firstMatch(in: resolved, range: NSRange(location: 0, length: rns.length)), r.range.length > 1 {
500 return try remote.tableRange(rns.substring(with: r.range), thisline: 0, col: 1, analysis: analysis)
501 }
502 return .field(resolved)
503 }
504
505 /// `org-table-eval-formula` with the equation given, at point. `substituted` when names
506 /// and constants were already replaced, as `org-table-recalculate` does.
507 func tableEvalFormula(_ formula: String, analysis: TableAnalysis, substituted: Bool = true) throws {
508 var formula = formula
509 var modes = Calc.Modes()
510 var mode = ReferenceMode()
511 var duration: DurationFormat?
512 var literal = false
513 var fmt: String?
514 if let semicolon = formula.lastIndex(of: ";") {
515 var flags = (analysis.parameters.last { $0.name == "%" }?.value ?? "") + formula[formula.index(after: semicolon)...]
516 formula = String(formula[..<semicolon])
517 let numeric = try! NSRegularExpression(pattern: "([pnfse])(-?[0-9]+)")
518 while let m = numeric.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
519 let ns = flags as NSString
520 let n = try Self.integer(ns.substring(with: m.range(at: 2)))
521 switch ns.substring(with: m.range(at: 1)) {
522 case "p": modes.precision = n
523 case "n": modes.format = .float(n)
524 case "f": modes.format = .fix(n)
525 case "s": modes.format = .sci(n)
526 default: modes.format = .eng(n)
527 }
528 flags = ns.replacingCharacters(in: m.range, with: "")
529 }
530 let letters = try! NSRegularExpression(pattern: "[tTUNLEDRFSu]")
531 while let m = letters.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
532 let ns = flags as NSString
533 switch ns.substring(with: m.range) {
534 case "t": (duration, mode.numbers) = (.hours, true)
535 case "T": (duration, mode.numbers) = (.hms, true)
536 case "U": (duration, mode.numbers) = (.hhmm, true)
537 case "N": mode.numbers = true
538 case "L": literal = true
539 case "E": mode.keepEmpty = true
540 case "D": modes.degrees = true
541 case "R": modes.degrees = false
542 default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))")
543 }
544 flags = ns.replacingCharacters(in: m.range, with: "")
545 }
546 if flags.contains(where: { !$0.isWhitespace }) { fmt = flags }
547 }
548 if !substituted { formula = try Self.handleFirstLast(try substituteNames(formula, analysis: analysis), analysis: analysis) }
549 var fields = Self.splitFields(substring(lineStart(point), lineEnd(point)).trimmingCharacters(in: .whitespaces), separator: " *\\| *")
550 if duration != nil { fields = try fields.map(Self.timeStringToSeconds) }
551 if mode.numbers { fields = fields.map { $0.contains(where: { !$0.isWhitespace }) ? Self.numberText($0) : $0 } }
552 if formula.count > 2, formula.hasPrefix("'(") { mode.lisp = literal ? .literal : .lisp }
553 func reference(_ value: TableRangeValue) throws -> String {
554 guard duration != nil else { return try Self.makeReference(value, mode) }
555 switch value {
556 case .field(let s): return try Self.makeReference(.field(try Self.timeStringToSeconds(s)), mode)
557 case .list(let items): return try Self.makeReference(.list(try items.map(Self.timeStringToSeconds)), mode)
558 }
559 }
560 let n0 = tableCurrentColumn()
561 let thisline = try saveExcursion { () -> Int in
562 let here = lineStart(point)
563 point = analysis.begin
564 var count = 0
565 while point < here {
566 if forwardLine(1) != 0 { throw Calc.Unsupported("table position") }
567 count += 1
568 }
569 return count
570 }
571 var form = formula
572 form = form.replacingOccurrences(of: "@#", with: String(tableCurrentDataLine()))
573 form = form.replacingOccurrences(of: "$#", with: String(n0))
574 // `org-table-remote-reference-indirection`: `remote($1, …)` names the table in a field.
575 let indirect = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([@$][^ \\t,]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
576 var start = 0
577 while let m = indirect.firstMatch(in: form, range: NSRange(location: start, length: (form as NSString).length - start)) {
578 let ns = form as NSString
579 var eq = try Self.handleFirstLast(ns.substring(with: m.range(at: 1)), analysis: analysis)
580 if eq.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil { eq = "@0" + eq }
581 guard case .field(let name) = try tableRange(eq, thisline: thisline, col: n0, analysis: analysis) else {
582 throw Calc.Unsupported("remote table name from a range")
583 }
584 form = ns.replacingCharacters(in: m.range(at: 1), with: name)
585 start = m.range(at: 1).location + (name as NSString).length
586 }
587 let remote = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([^,)]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
588 while let m = remote.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
589 let ns = form as NSString
590 let name = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)
591 let value = try remoteRange(name, ns.substring(with: m.range(at: 2)))
592 form = ns.replacingCharacters(in: m.range, with: try reference(value))
593 }
594 let range = try! NSRegularExpression(pattern: Self.rangePattern)
595 while let m = range.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)), m.range.length > 1 {
596 let ns = form as NSString
597 let replacement = try reference(try tableRange(ns.substring(with: m.range), thisline: thisline, col: n0, analysis: analysis))
598 if replacement.contains(form) { throw UserError(message: "Spreadsheet error: invalid reference \"\(form)\"") }
599 form = ns.replacingCharacters(in: m.range, with: replacement)
600 }
601 let rowRange = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)\\.\\.\\$(([-+])?[0-9]+)")
602 while let m = rowRange.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
603 let ns = form as NSString
604 let a = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
605 let b = try Self.integer(ns.substring(with: m.range(at: 3))) + (m.range(at: 4).location != NSNotFound ? n0 : 0)
606 guard a >= 1, b <= fields.count, a - 1 <= b else { throw Calc.Unsupported("range outside row") }
607 form = ns.replacingCharacters(in: m.range, with: try Self.makeReference(.list(Array(fields[(a - 1)..<b])), mode))
608 }
609 let single = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)")
610 while let m = single.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
611 let ns = form as NSString
612 let n = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
613 let index = (n == 0 ? n0 : max(n, 1)) - 1
614 guard index < fields.count else { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
615 let replacement = try Self.makeReference(.field(fields[index]), mode)
616 if replacement.contains(formula) { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
617 form = ns.replacingCharacters(in: m.range, with: replacement)
618 }
619
620 var result: String
621 if mode.lisp != .none {
622 result = try evalLisp(form, duration: duration)
623 } else {
624 form = form.replacingOccurrences(of: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)\\]", with: "<$1>", options: .regularExpression)
625 form = Self.normalizeTimestamps(form)
626 if duration != nil, form.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil {
627 result = form
628 } else {
629 do {
630 result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
631 } catch is Calc.Failure {
632 (result, fmt) = ("#ERROR", nil)
633 }
634 }
635 if let duration, !result.isEmpty, result != "#ERROR" {
636 let seconds = result.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil ? try Self.timeStringToSeconds(result) : result
637 result = try Self.secondsToString(Elisp.stringToNumber(seconds), duration)
638 }
639 }
640 if let fmt {
641 do {
642 result = try Elisp.format([.string(fmt), Elisp.stringToNumber(result)])
643 } catch let error as Elisp.Signal {
644 throw UserError(message: error.message)
645 }
646 } else {
647 result = result.replacingOccurrences(of: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>", with: "[$1]", options: .regularExpression)
648 }
649 tableSetField(result)
650 }
651
652 /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`.
653 func evalLisp(_ form: String, duration: DurationFormat?) throws -> String {
654 let lisp = Elisp()
655 Self.defineLookups(lisp)
656 let value: Sexp
657 do {
658 value = try lisp.eval(try lisp.eval(try LispReader.readFirst(form).sexp))
659 } catch let unsupported as Elisp.Unsupported {
660 throw Calc.Unsupported("Lisp \(unsupported.what)")
661 } catch {
662 return "#ERROR"
663 }
664 var result = Elisp.printed(value)
665 if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) }
666 return result
667 }
668
669 /// `org-lookup-first`, `org-lookup-last` and `org-lookup-all`.
670 static func defineLookups(_ lisp: Elisp) {
671 func matches(_ lisp: Elisp, _ args: [Sexp]) throws -> [Sexp] {
672 try Elisp.arity(args, 3...4, "org-lookup")
673 let keys = try Elisp.elements(args[1])
674 let values = Elisp.isNil(args[2]) ? keys : try Elisp.elements(args[2])
675 let predicate = args.count > 3 && !Elisp.isNil(args[3]) ? args[3] : .symbol("equal")
676 var found: [Sexp] = []
677 for (i, key) in keys.enumerated() where !Elisp.isNil(try lisp.call(predicate, [args[0], key])) {
678 found.append(i < values.count ? values[i] : .nil)
679 }
680 return found
681 }
682 lisp.define("org-lookup-first") { lisp, args in try matches(lisp, args).first ?? .nil }
683 lisp.define("org-lookup-last") { lisp, args in try matches(lisp, args).last ?? .nil }
684 lisp.define("org-lookup-all") { lisp, args in
685 let found = try matches(lisp, args)
686 return found.isEmpty ? .nil : .list(found)
687 }
688 }
689
690 /// Timestamps in a formula as Calc reads them: `<YYYY-MM-DD Www>`, with ` HH:MM` when
691 /// the stamp has a time, as org formats them for Calc.
692 static func normalizeTimestamps(_ form: String) -> String {
693 let regex = try! NSRegularExpression(pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>")
694 var out = form
695 var start = 0
696 while let m = regex.firstMatch(in: out, range: NSRange(location: start, length: (out as NSString).length - start)) {
697 let ns = out as NSString
698 let stamp = ns.substring(with: m.range(at: 1))
699 let parts = stamp.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})/)!
700 let day = Days.absolute(year: Int(parts.1)!, month: Int(parts.2)!, day: Int(parts.3)!)
701 let date = Days.date(day)
702 var text = String(format: "<%04d-%02d-%02d %@", date.year, date.month, date.day, Calc.weekdays[Days.weekday(day)])
703 if let time = stamp.firstMatch(of: /([0-9]{1,2}):([0-9]{2})/) {
704 text += String(format: " %02d:%02d", Int(time.1)!, Int(time.2)!)
705 }
706 text += ">"
707 out = ns.replacingCharacters(in: m.range, with: text)
708 start = m.range.location + (text as NSString).length
709 }
710 return out
711 }
712
713 /// `string-to-number`.
714 static func stringToNumber(_ s: String) -> Double {
715 guard let r = s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return 0 }
716 return Double(s[r]) ?? 0
717 }
718
719 /// `org-table-justify-field-maybe` while the table needs realigning: the field becomes
720 /// ` NEW |`.
721 func tableSetField(_ value: String) {
722 let pos = point
723 guard tableCurrentColumn() > 0 else { return }
724 skipBackwardNot([124])
725 let start = point
726 var end = point
727 while let c = character(at: end), c != 124, c != 10 { end += 1 }
728 let closed = character(at: end) == 124
729 replaceRange(start, closed ? end + 1 : end, with: " \(value) |")
730 point = min(pos, length)
731 }
732
733 func replaceRange(_ start: Int, _ end: Int, with text: String) {
734 let saved = point
735 deleteRegion(start, end)
736 point = start
737 insert(text)
738 point = saved
739 }
740
741 /// `org-table-recalculate`: `all` for every row, otherwise the line at point; `tblfm`
742 /// replaces the stored formulas, as C-c C-c on a `#+TBLFM` line does.
743 func tableRecalculate(all: Bool, tblfm: String? = nil) throws {
744 guard atTable else { throw UserError(message: "Not at a table") }
745 let analysis = try tableAnalyze()
746 let end = tableEnd()
747 guard let line = tblfm ?? firstTblfm(after: end) else { return }
748 let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
749 guard !stored.isEmpty else { return }
750 var columnEquations: [(Int, String)] = []
751 var fieldEquations: [(String, String)] = []
752 for (oldLHS, rawRHS) in stored {
753 let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis)
754 if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
755 let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
756 if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil {
757 columnEquations.append((try Self.integer(String(lhs.dropFirst())), rhs))
758 } else {
759 fieldEquations.append((lhs, rhs))
760 }
761 }
762 // `org-table-expand-lhs-ranges`.
763 var fields: [(row: Int, column: Int, rhs: String)] = []
764 for (lhs, rhs) in fieldEquations {
765 if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) {
766 fields.append((try Self.integer(String(m.1)), try Self.integer(String(m.2)), rhs))
767 } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil {
768 guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else {
769 throw UserError(message: "Unknown field: \(lhs)")
770 }
771 fields.append((row, location.column, rhs))
772 } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil {
773 // `org-table-goto-field` knows only absolute fields and names.
774 throw UserError(message: "Unknown field: \(lhs)")
775 } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
776 let row = try Self.integer(String(m.1))
777 for c in 1...analysis.ncol { fields.append((row, c, rhs)) }
778 } else {
779 let corners = try rangeCorners(lhs, analysis: analysis)
780 guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
781 throw Calc.Unsupported("formula range")
782 }
783 for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs)) } }
784 }
785 }
786 let savedLine = lineStart(point)
787 let savedColumn = tableCurrentColumn()
788 let lineMarker = marker(savedLine)
789 defer { release(lineMarker) }
790
791 let endMarker = marker(end)
792 defer { release(endMarker) }
793 var beg: Int
794 var lineRegexp = "^[ \\t]*\\|[^-]"
795 if all, analysis.marked {
796 beg = analysis.begin
797 lineRegexp = "^[ \\t]*\\| *[#*] *(\\||$)"
798 } else if all {
799 beg = analysis.begin
800 point = beg
801 if searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) != nil,
802 searchForward("^[ \\t]*\\|-", bound: end, caseInsensitive: false) != nil,
803 let body = searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
804 beg = body[0]!.lowerBound
805 }
806 } else {
807 beg = lineStart(point)
808 endMarker.position = min(length, lineEnd(point) + 1)
809 }
810
811 let currentLine = savedLine - 0
812 var seen: Set<String> = []
813 var untouchable: Set<String> = []
814 for field in fields {
815 let reference = "@\(field.row)$\(field.column)"
816 guard seen.insert(reference).inserted else { throw UserError(message: "Several field/range formulas try to set \(reference)") }
817 guard field.row < analysis.dlines.count else { throw UserError(message: "Invalid row number in \(reference)") }
818 let lineStartOffset = saveExcursion { () -> Int in
819 gotoTableLine(analysis.dlines[field.row], analysis)
820 return lineStart(point)
821 }
822 if all || lineStartOffset == currentLine { untouchable.insert(reference) }
823 }
824
825 point = beg
826 let rowMarker = marker(beg)
827 defer { release(rowMarker) }
828 while let match = searchForward(lineRegexp, bound: endMarker.position, caseInsensitive: false) {
829 _ = match
830 let rowStart = lineStart(point)
831 rowMarker.position = rowStart
832 let first = saveExcursion { () -> String in
833 point = rowStart
834 return tableField(1)
835 }
836 if first.range(of: "^ *[_^!$/] *$", options: .regularExpression) == nil {
837 let dline = saveExcursion { () -> Int in
838 point = rowStart
839 return tableCurrentDataLine()
840 }
841 for (column, rhs) in columnEquations {
842 point = rowMarker.position
843 tableGotoColumn(column, force: true)
844 if untouchable.contains("@\(dline)$\(column)") { continue }
845 try tableEvalFormula(rhs, analysis: analysis)
846 }
847 }
848 point = rowMarker.position
849 if forwardLine(1) != 0 || point >= endMarker.position { break }
850 }
851 for field in fields {
852 gotoTableLine(analysis.dlines[field.row], analysis)
853 let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
854 if field.column > count { throw UserError(message: "Missing columns in the table. Aborting") }
855 tableGotoColumn(field.column)
856 try tableEvalFormula(field.rhs, analysis: analysis)
857 }
858 tableAlign()
859 point = lineMarker.position
860 tableGotoColumn(savedColumn)
861 }
862
863 /// `org-table-get-range` with `corners-only`.
864 func rangeCorners(_ desc: String, analysis: TableAnalysis) throws -> (r1: Int, c1: Int, r2: Int, c2: Int) {
865 let ns = desc as NSString
866 guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
867 throw UserError(message: "Invalid table range specifier `\(desc)'")
868 }
869 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
870 let thisline = 0
871 func row(_ r: String?) throws -> Int {
872 guard let r, !r.isEmpty else { return thisline }
873 return try Self.descriptorLine(r, thisline, analysis: analysis)
874 }
875 func column(_ c: String?) -> Int {
876 guard let c, let n = Int(c.dropFirst()), n != 0 else { return 1 }
877 return n + (c.dropFirst().first == "-" || c.dropFirst().first == "+" ? 1 : 0)
878 }
879 let r1 = try row(group(1))
880 let r2 = try row(group(4))
881 let c1 = column(group(2))
882 let c2 = column(group(5))
883 return (min(r1, r2), min(c1, c2), max(r1, r2), max(c1, c2))
884 }
885
886 /// `org-table-line-to-dline`.
887 static func lineToDline(_ line: Int, _ analysis: TableAnalysis, above: Bool = false) -> Int? {
888 let dlines = analysis.dlines
889 var low = 1
890 var high = dlines.count - 1
891 if dlines[low] > line || dlines[high] < line { return nil }
892 if line == dlines[high] { return high }
893 while high - low > 1 {
894 let mean = (high + low) / 2
895 if dlines[mean] == line { return mean }
896 if dlines[mean] > line { high = mean } else { low = mean }
897 }
898 if line == dlines[high] { return high }
899 if line == dlines[low] { return low }
900 return above ? low : high
901 }
902}
903
904/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the
905/// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app
906/// recalculates them in Emacs.
907public struct TableRecalculate: OrgCommand {
908 public let all: Bool
909 public init(all: Bool) { self.all = all }
910 public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" }
911 public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" }
912
913 public static let emacsMessage = "needs Emacs: "
914
915 public func applies(in context: EditContext) -> Bool {
916 KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil
917 }
918
919 static func tblfmLine(in context: EditContext) -> String? {
920 let buffer = EmacsBuffer(context.text, point: context.caret)
921 let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
922 guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
923 return line
924 }
925
926 public func run(in context: EditContext) -> CommandStep {
927 let step = commitBuffer(context) { buffer in
928 do {
929 if let line = Self.tblfmLine(in: context) {
930 // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
931 // point at the end of the table.
932 let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
933 let saved = buffer.marker(buffer.point)
934 defer { buffer.release(saved) }
935 guard let tableEnd = buffer.saveExcursion({ () -> Int? in
936 while buffer.forwardLine(-1) == 0 {
937 if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
938 }
939 return nil
940 }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
941 buffer.point = tableEnd
942 try buffer.tableRecalculate(all: true, tblfm: formulas)
943 buffer.point = saved.position
944 } else {
945 try buffer.tableRecalculate(all: all)
946 }
947 } catch let error as Calc.Unsupported {
948 throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason)
949 }
950 }
951 guard case .failed(let message) = step, message.hasPrefix(Self.emacsMessage) else { return step }
952 // Emacs recalculates the table; its text replaces the table here.
953 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
954 let onTblfm = Self.tblfmLine(in: context) != nil
955 if onTblfm {
956 while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {}
957 }
958 let table = buffer.tableBegin()..<buffer.tableEnd()
959 let tblfm = onTblfm ? Self.tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
960 let form = onTblfm ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
961 return .external(.emacsTable(
962 table: table, point: context.caret, form: form,
963 reason: String(message.dropFirst(Self.emacsMessage.count)), lisp: tblfm.contains("'(")
964 ))
965 }
966}
967
968// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
969extension EmacsBuffer {
970 /// `org-table-formula-make-cmp-string`.
971 static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
972 var a = lhs
973 if let arrow = a.firstMatch(of: /^\$([<>])/) {
974 a = (try? handleFirstLast(a, analysis: analysis)) ?? a
975 a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))"
976 }
977 guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil }
978 var key = ""
979 if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) }
980 if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) }
981 if let name = m.5 { key += "@@" + name }
982 return key
983 }
984
985 /// `sort` with `org-table-formula-less-p`.
986 static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] {
987 var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = []
988 // Stable insertion, as `sort` with a partial predicate.
989 for formula in formulas {
990 let key = formulaSortKey(formula.lhs, analysis: analysis)
991 var index = sorted.count
992 while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 }
993 sorted.insert((formula, key), at: index)
994 }
995 return sorted.map(\.formula)
996 }
997
998 /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`.
999 func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) {
1000 let sorted = Self.sortFormulas(formulas, analysis: analysis)
1001 saveExcursion {
1002 point = tableEnd()
1003 if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) {
1004 deleteRegion(match[3]!.lowerBound, match[0]!.upperBound)
1005 point = match[3]!.lowerBound
1006 } else {
1007 insert("#+TBLFM:")
1008 }
1009 insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n")
1010 }
1011 }
1012
1013 /// `org-table-get-formula` with EQUATION given: stores it for the current column, or with
1014 /// `named` the current field, and returns it.
1015 func tableGetFormula(_ equation: String, named: Bool, analysis: TableAnalysis) throws -> String {
1016 var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "")
1017 let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())"
1018 let scol = named ? ref : "$\(tableCurrentColumn())"
1019 let old = stored.first { $0.lhs == scol }?.rhs
1020 var eq = old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation
1021 guard eq.contains(where: { !$0.isWhitespace }) else {
1022 stored.removeAll { $0.lhs == scol }
1023 tableStoreFormulas(stored, analysis: analysis)
1024 throw UserError(message: "Formula removed")
1025 }
1026 eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression)
1027 eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression)
1028 var mustSave = false
1029 if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) {
1030 stored.remove(at: index)
1031 mustSave = true
1032 }
1033 if let index = stored.firstIndex(where: { $0.lhs == scol }) {
1034 stored[index].rhs = eq
1035 } else {
1036 stored.insert((scol, eq), at: 0)
1037 }
1038 if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) }
1039 return eq
1040 }
1041
1042 /// `org-table-eval-formula` for the current field with EQUATION, which is stored first.
1043 func tableEvalFormula(equation: String, named: Bool) throws {
1044 try checkInsideDataField()
1045 let analysis = try tableAnalyze()
1046 let formula = try tableGetFormula(equation, named: named, analysis: analysis)
1047 do {
1048 try tableEvalFormula(formula, analysis: analysis, substituted: false)
1049 } catch let error as Calc.Unsupported {
1050 throw UserError(message: "The formula was stored; recalculating it needs Emacs: " + error.reason)
1051 }
1052 tableAlign()
1053 }
1054
1055 /// `org-table-maybe-eval-formula`.
1056 func tableMaybeEvalFormula() throws {
1057 skipBackwardNot([124, 10])
1058 guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return }
1059 let start = point
1060 var end = point
1061 while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 }
1062 point = min(lineEnd(point), start + 1)
1063 let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
1064 guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return }
1065 try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":"))
1066 }
1067}
1068
1069/// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's
1070/// formula, the stored one offered.
1071public struct TableEvalFormula: OrgCommand {
1072 let named: Bool
1073 public init(named: Bool) { self.named = named }
1074 public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" }
1075 public var title: String { named ? "Set Field Formula" : "Set Column Formula" }
1076 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
1077 public func run(in context: EditContext) -> CommandStep {
1078 guard let answer = context.answers["formula"] else {
1079 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
1080 guard buffer.atTable else { return .failed("Not at a table") }
1081 let column = buffer.tableCurrentColumn()
1082 let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)"
1083 let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs
1084 return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? ""))
1085 }
1086 return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named) }
1087 }
1088}
1089
1090// The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor.
1091extension BlockEdit {
1092 static let formulasKind = "formulas"
1093
1094 /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as
1095 /// org's editor lists them. The range runs from the table (or that line) to the formulas.
1096 public static func formulas(at offset: Int, text: String) -> BlockEdit? {
1097 let buffer = EmacsBuffer(text, point: offset)
1098 let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset))
1099 let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil
1100 guard atTblfm || buffer.atTable else { return nil }
1101 let start: Int
1102 let end: Int
1103 let formulas: [(lhs: String, rhs: String)]
1104 if atTblfm {
1105 start = buffer.lineStart(offset)
1106 end = min(buffer.length, buffer.lineEnd(offset) + 1)
1107 let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " "))
1108 formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? []
1109 guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil }
1110 } else {
1111 start = buffer.tableBegin()
1112 let tableEnd = buffer.tableEnd()
1113 end = buffer.saveExcursion {
1114 buffer.point = tableEnd
1115 return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd
1116 }
1117 formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? []
1118 }
1119 guard let analysis = try? buffer.tableAnalyze() else { return nil }
1120 var content = ""
1121 var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")]
1122 for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) {
1123 let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named"
1124 if let index = titles.firstIndex(where: { $0.type == type }) {
1125 if !content.isEmpty { content += "\n" }
1126 content += titles[index].title
1127 titles.remove(at: index)
1128 }
1129 content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n"
1130 }
1131 let ns = text as NSString
1132 return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind)
1133 }
1134
1135 /// `org-table-fedit-finish`'s reading of the editor's text.
1136 static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] {
1137 let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines)
1138 let ns = content as NSString
1139 var result: [(lhs: String, rhs: String)] = []
1140 for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) {
1141 let lhs = ns.substring(with: m.range(at: 1))
1142 var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
1143 guard !rhs.isEmpty else { continue }
1144 rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
1145 if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") }
1146 result.insert((lhs, rhs), at: 0)
1147 }
1148 return result
1149 }
1150
1151 /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument.
1152 func installFormulas(_ content: String, in context: EditContext) -> CommandStep {
1153 let step = commitBuffer(context) { buffer in
1154 let formulas = try Self.parseFormulas(content)
1155 buffer.point = range.lowerBound
1156 let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in
1157 if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) }
1158 return try buffer.tableAnalyze()
1159 }
1160 buffer.tableStoreFormulas(formulas, analysis: analysis)
1161 }
1162 guard case .commit(let result) = step else { return step }
1163 return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection,
1164 effects: result.effects + [.message("New formulas installed - press C-u C-c C-c to apply.")]))
1165 }
1166}
1167
1168// `org-table-edit-field` (C-c `): a field's text edited apart, then put back.
1169extension BlockEdit {
1170 static let fieldKind = "field"
1171
1172 /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged.
1173 public static func field(at offset: Int, text: String) -> BlockEdit? {
1174 let buffer = EmacsBuffer(text, point: offset)
1175 guard buffer.insideDataField else { return nil }
1176 let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())"
1177 let field = buffer.saveExcursion { () -> String in
1178 buffer.skipBackwardNot([124, 10])
1179 return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound)
1180 }
1181 let start = buffer.lineStart(offset)
1182 let end = buffer.lineEnd(offset)
1183 return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines),
1184 language: nil, kind: fieldKind, point: offset, coordinate: coordinate)
1185 }
1186
1187 /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the
1188 /// table is aligned.
1189 func installField(_ content: String, in context: EditContext) -> CommandStep {
1190 var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression)
1191 text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression)
1192 text = text.trimmingCharacters(in: .whitespacesAndNewlines)
1193 return commitBuffer(context) { buffer in
1194 buffer.point = point ?? range.lowerBound
1195 guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") }
1196 buffer.skipBackwardNot([124, 10])
1197 let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound
1198 buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text)
1199 buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1)
1200 buffer.tableAlign()
1201 }
1202 }
1203}
1204
1205extension EmacsBuffer {
1206 /// `org-table-check-inside-data-field` with NOERROR.
1207 var insideDataField: Bool {
1208 atTable && !atTableHline
1209 && !saveExcursion { () -> Bool in
1210 while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 }
1211 return bolp
1212 }
1213 && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil
1214 }
1215}
1216
1217/// C-c `: `org-table-edit-field`, in the block editor.
1218public struct TableEditField: OrgCommand {
1219 public init() {}
1220 public var id: String { "org.table.edit-field" }
1221 public var title: String { "Edit Table Field" }
1222 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
1223 public func run(in context: EditContext) -> CommandStep {
1224 guard let edit = BlockEdit.field(at: context.caret, text: context.text) else {
1225 return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table")
1226 }
1227 return .external(.editBlock(edit))
1228 }
1229}