Sources/OrgCore/Compute/TableFormulas.swift
927 lines · 49191 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. Calc features beyond
5// `Calc` and Lisp beyond `Elisp` throw `Calc.Unsupported`; the caller then
6// recalculates the table in Emacs. `remote()` finds tables by name in the file, and by ID
7// here or, through `RemoteTables`, in other files.
8
9/// Where `remote()` finds tables by ID in other files.
10public enum RemoteTables {
11 /// The text of the file holding the entry with an ID; the app sets it, from its index.
12 nonisolated(unsafe) public static var fileWithID: ((String) -> String?)?
13}
14
15extension EmacsBuffer {
16 struct TableAnalysis {
17 /// Table-relative line index of each data line, from 1 (index 0 unused).
18 var dlines: [Int]
19 /// Hline flag per line, with an extra hline after the last.
20 var types: [Bool]
21 var ncol: Int
22 var begin: Int
23 /// `org-table-column-names`: from the first `!` row.
24 var columnNames: [(name: String, column: Int)] = []
25 /// `org-table-local-parameters`, in the order org pushes them; the last match wins.
26 var parameters: [(name: String, value: String)] = []
27 /// `org-table-named-field-locations`: the table-relative line and the column.
28 var namedFields: [(name: String, line: Int, column: Int)] = []
29 /// A row marked for calculation (`org-table-calculate-mark-regexp`).
30 var marked = false
31 }
32
33 static let tblfmPattern = "^[ \\t]*#\\+TBLFM: *(.*)"
34 static let rangePattern = "@([-+]?I*[-+]?[0-9]*)(\\$[-+]?[0-9]+)?(\\.\\.@?([-+]?I*[-+]?[0-9]*)(\\$[-+]?[0-9]+)?)?"
35
36 /// `org-table-analyze`.
37 func tableAnalyze() throws -> TableAnalysis {
38 let begin = tableBegin()
39 let end = tableEnd()
40 return try saveExcursion {
41 point = begin
42 var dlines = [0]
43 var types: [Bool] = []
44 var lines: [String] = []
45 var line = 0
46 while point < end || (point == end && false) {
47 let content = substring(lineStart(point), lineEnd(point))
48 guard content.range(of: "^[ \\t]*\\|", options: .regularExpression) != nil else { break }
49 lines.append(content)
50 let isHline = content.range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil
51 types.append(isHline)
52 if !isHline { dlines.append(line) }
53 line += 1
54 if forwardLine(1) != 0 || point >= end { break }
55 }
56 types.append(true)
57 guard dlines.count > 1 else { throw UserError(message: "No data lines in table") }
58 point = begin
59 forwardLine(dlines[1])
60 let first = substring(lineStart(point), lineEnd(point))
61 let ncol = Self.splitFields(first, separator: "[ \\t]*\\|[ \\t]*").count
62 var analysis = TableAnalysis(dlines: dlines, types: types, ncol: ncol, begin: begin)
63 Self.names(lines, into: &analysis)
64 return analysis
65 }
66 }
67
68 /// The names part of `org-table-analyze`.
69 static func names(_ lines: [String], into analysis: inout TableAnalysis) {
70 let identifier = "^[a-zA-Z][_a-zA-Z0-9]*$"
71 func rest(_ line: String, _ pattern: String) -> String? {
72 guard let m = try! NSRegularExpression(pattern: pattern).firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) else { return nil }
73 return (line as NSString).substring(with: m.range(at: m.numberOfRanges - 1))
74 }
75 if let names = lines.lazy.compactMap({ rest($0, "^[ \\t]*\\| *! *(\\|.*)") }).first {
76 for (i, name) in splitFields(names, separator: " *\\| *").enumerated() where name.range(of: identifier, options: .regularExpression) != nil {
77 analysis.columnNames.append((name, i + 2))
78 }
79 }
80 for line in lines {
81 guard let fields = rest(line, "^[ \\t]*\\| *\\$ *(\\|.*)") else { continue }
82 for field in splitFields(fields, separator: " *\\| *") {
83 if let m = field.firstMatch(of: /^([a-zA-Z][_a-zA-Z0-9]*|%) *= *(.*)/) { analysis.parameters.append((String(m.1), String(m.2))) }
84 }
85 }
86 for (k, line) in lines.enumerated() {
87 guard let m = line.firstMatch(of: /^[ \t]*\| *([_^]) *(\|.*)/) else { continue }
88 let target = m.1 == "_" ? k + 1 : k - 1
89 guard lines.indices.contains(target), let values = rest(lines[target], "^[ \\t]*\\|[^|]*(\\|.*)") else { continue }
90 for (i, (name, value)) in zip(splitFields(String(m.2), separator: " *\\| *"), splitFields(values, separator: " *\\| *")).enumerated()
91 where name.range(of: identifier, options: .regularExpression) != nil {
92 analysis.parameters.append((name, value))
93 analysis.namedFields.append((name, target, i + 2))
94 }
95 }
96 analysis.marked = lines.contains { $0.range(of: "^[ \\t]*\\| *[!$^_#*] *(\\||$)", options: .regularExpression) != nil }
97 }
98
99 /// `org-split-string`: leading and trailing separators produce no empty strings.
100 static func splitFields(_ s: String, separator: String) -> [String] {
101 let ns = s as NSString
102 let regex = try! NSRegularExpression(pattern: separator)
103 let matches = regex.matches(in: s, range: NSRange(location: 0, length: ns.length))
104 guard !matches.isEmpty else { return [s] }
105 var results: [String] = []
106 var i = 0
107 for (k, m) in matches.enumerated() {
108 if k == 0, m.range.location == 0 {
109 i = NSMaxRange(m.range)
110 continue
111 }
112 results.append(ns.substring(with: NSRange(location: i, length: m.range.location - i)))
113 i = NSMaxRange(m.range)
114 }
115 if i != ns.length { results.append(ns.substring(from: i)) }
116 return results
117 }
118
119 /// `org-table-get-stored-formulas` from the `#+TBLFM` text `line`.
120 static func storedFormulas(_ line: String) throws -> [(lhs: String, rhs: String)] {
121 var result: [(String, String)] = []
122 var seen: Set<String> = []
123 let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|\\$([_a-zA-Z0-9]+|[<>]+)) *= *(.*[^ \\t])")
124 for part in splitFields(line, separator: " *:: *") {
125 let ns = part as NSString
126 guard let m = regex.firstMatch(in: part, range: NSRange(location: 0, length: ns.length)) else { continue }
127 let whole = ns.substring(with: m.range(at: 1))
128 var lhs = whole
129 if m.range(at: 2).location != NSNotFound,
130 whole.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) == nil {
131 lhs = ns.substring(with: m.range(at: 2))
132 }
133 guard seen.insert(lhs).inserted else { throw UserError(message: "Double definition `\(lhs)=' in TBLFM line, please fix by hand") }
134 result.append((lhs, ns.substring(with: m.range(at: 3))))
135 }
136 return result
137 }
138
139 /// The first `#+TBLFM` line after the table, blank lines allowed between.
140 func firstTblfm(after end: Int) -> String? {
141 saveExcursion {
142 point = end
143 while !eobp {
144 let line = substring(lineStart(point), lineEnd(point))
145 if line.trimmingCharacters(in: .whitespaces).isEmpty {
146 if forwardLine(1) != 0 { return nil }
147 continue
148 }
149 guard let r = line.range(of: Self.tblfmPattern, options: [.regularExpression, .caseInsensitive]) else { return nil }
150 let text = String(line[r])
151 return String(text[text.index(after: text.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
152 }
153 return nil
154 }
155 }
156
157 /// `org-table-formula-handle-first/last-rc`.
158 static func handleFirstLast(_ s: String, analysis: TableAnalysis) throws -> String {
159 var result = s
160 var start = 0
161 let regex = try! NSRegularExpression(pattern: "([@$])(<+|>+)|(remote\\([^)]+\\))")
162 while let m = regex.firstMatch(in: result, range: NSRange(location: start, length: (result as NSString).length - start)) {
163 let ns = result as NSString
164 if m.range(at: 3).location != NSNotFound {
165 start = NSMaxRange(m.range(at: 3))
166 continue
167 }
168 let kind = ns.substring(with: m.range(at: 1))
169 let nmax = kind == "@" ? analysis.dlines.count - 1 : analysis.ncol
170 let marks = ns.substring(with: m.range(at: 2))
171 let n = marks.first == "<" ? marks.count : nmax - marks.count + 1
172 if n < 1 || n > nmax { throw UserError(message: "Reference \"\(ns.substring(with: m.range))\" in expression \"\(result)\" points outside table") }
173 start = m.range.location
174 result = ns.replacingCharacters(in: m.range, with: kind + String(n))
175 }
176 return result
177 }
178
179 /// `org-table--row-type`.
180 static func rowType(hline: Bool, _ n: Int, _ start: Int, backwards: Bool, relative: Bool, analysis: TableAnalysis, desc: String) throws -> Int {
181 var i = start
182 let l = analysis.types.count
183 for _ in 0..<n {
184 while true {
185 i += backwards ? -1 : 1
186 guard i >= 0, i < l, analysis.types[i] != hline else { break }
187 }
188 }
189 if i < 0 || i >= l { throw UserError(message: "Row descriptor \(desc) leads outside table") }
190 return i == l - 1 ? i - 1 : i
191 }
192
193 /// `org-table--descriptor-line`, with `org-table-get-range`'s fallback to the current
194 /// line for `@0`, whose `org-table-dlines` entry is nil.
195 static func descriptorLine(_ desc: String, _ cline: Int, analysis: TableAnalysis) throws -> Int {
196 if let n = Int(desc), desc.allSatisfy(\.isNumber) {
197 guard n < analysis.dlines.count else { throw Calc.Unsupported("row out of range") }
198 return n == 0 ? cline : analysis.dlines[n]
199 }
200 let ns = desc as NSString
201 let regex = try! NSRegularExpression(pattern: "^(([-+])?(I+))?(([-+])?([0-9]+))?")
202 let m = regex.firstMatch(in: desc, range: NSRange(location: 0, length: ns.length))!
203 func has(_ i: Int) -> Bool { m.range(at: i).location != NSNotFound }
204 if (!has(3) && !has(6)) || (has(3) && has(6) && !has(5)) { throw UserError(message: "Invalid row descriptor `\(desc)'") }
205 var hn = has(3) ? m.range(at: 3).length : nil
206 var hdir = has(2) ? ns.substring(with: m.range(at: 2)) : nil
207 let odir = has(5) ? ns.substring(with: m.range(at: 5)) : nil
208 let on = has(6) ? Int(ns.substring(with: m.range(at: 6))) : nil
209 let rel = has(6) && ((has(1) && !has(3)) || has(5))
210 var cline = cline
211 if hn != nil, hdir == nil {
212 cline = 0
213 hdir = "+"
214 if analysis.types[0] { hn! -= 1 }
215 }
216 if hn == nil, on != nil, odir == nil { throw UserError(message: "Should never happen") }
217 if let hn { cline = try rowType(hline: true, hn, cline, backwards: hdir == "-", relative: false, analysis: analysis, desc: desc) }
218 if let on { cline = try rowType(hline: false, on, cline, backwards: odir == "-", relative: rel, analysis: analysis, desc: desc) }
219 return cline
220 }
221
222 /// `org-table-get-field` on the line at point.
223 func tableField(_ column: Int) -> String {
224 saveExcursion {
225 tableGotoColumn(column)
226 skipBackwardNot([124, 10])
227 if bolp || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { return "" }
228 let start = point
229 while let c = character(at: point), c != 124, c != 10, c != 13 { point += 1 }
230 return substring(start, point)
231 }
232 }
233
234 func isDataLine() -> Bool {
235 looking("^[ \\t]*\\|[^-]", caseInsensitive: false, setsMatch: false) != nil
236 || substring(lineStart(point), lineEnd(point)).range(of: "^[ \\t]*\\|[^-]", options: .regularExpression) != nil
237 }
238
239 func gotoTableLine(_ line: Int, _ analysis: TableAnalysis) {
240 point = analysis.begin
241 forwardLine(line)
242 }
243
244 /// `org-table-get-range`: one field's text, or the fields of a rectangle.
245 func tableRange(_ desc: String, thisline: Int, col: Int, analysis: TableAnalysis) throws -> TableRangeValue {
246 var desc = desc
247 if desc.range(of: "^\\$[0-9]+\\.\\.\\$[0-9]+$", options: .regularExpression) != nil {
248 desc = desc.replacingOccurrences(of: "$", with: "@0$")
249 }
250 let ns = desc as NSString
251 guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
252 throw UserError(message: "Invalid table range specifier `\(desc)'")
253 }
254 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
255 let isRange = group(3) != nil
256 func row(_ r: String?) throws -> Int {
257 guard let r, r.contains(where: { !$0.isWhitespace }) else { return thisline }
258 return try Self.descriptorLine(r, thisline, analysis: analysis)
259 }
260 func column(_ c: String?) -> Int {
261 guard let c else { return col }
262 let body = String(c.dropFirst())
263 let n = Int(body) ?? 0
264 if n == 0 { return col }
265 return n + (body.first == "-" || body.first == "+" ? col : 0)
266 }
267 let r1 = try row(group(1))
268 let r2 = try row(group(4))
269 let c1 = column(group(2))
270 let c2 = column(group(5))
271 return try saveExcursion {
272 if !isRange || (r1 == r2 && c1 == c2) {
273 gotoTableLine(r1, analysis)
274 while !isDataLine() {
275 if forwardLine(1) != 0 { throw Calc.Unsupported("reference outside table") }
276 }
277 return .field(tableField(c1).trimmingCharacters(in: .whitespaces))
278 }
279 var firstRow = min(r1, r2)
280 let lastRow = max(r1, r2)
281 let firstColumn = min(c1, c2)
282 let lastColumn = max(c1, c2)
283 gotoTableLine(firstRow, analysis)
284 while !isDataLine() {
285 if forwardLine(1) != 0 { throw Calc.Unsupported("reference outside table") }
286 firstRow += 1
287 }
288 let startLine = lineStart(point)
289 forwardLine(lastRow - firstRow)
290 while !isDataLine() { forwardLine(-1) }
291 let endLine = lineStart(point)
292 var fields: [String] = []
293 point = startLine
294 while point <= endLine {
295 if !atTableHline {
296 for c in firstColumn...lastColumn { fields.append(tableField(c).trimmingCharacters(in: .whitespaces)) }
297 }
298 if forwardLine(1) != 0 { break }
299 }
300 return .list(fields)
301 }
302 }
303
304 enum TableRangeValue {
305 case field(String)
306 case list([String])
307 }
308
309 /// `org-ts-regexp-both`.
310 static let timestampBoth = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)[\\]>]"
311
312 /// How `org-table-make-reference` turns fields into formula text.
313 struct ReferenceMode {
314 enum Lisp { case none, lisp, literal }
315 var keepEmpty = false
316 var numbers = false
317 var lisp = Lisp.none
318 }
319
320 /// `number-to-string` of `string-to-number`.
321 static func numberText(_ s: String) -> String { Elisp.printed(Elisp.stringToNumber(s)) }
322
323 /// `org-table-make-reference`. For Calc, a field's text goes in as it is, so text that
324 /// isn't a number reads as variables.
325 static func makeReference(_ value: TableRangeValue, _ mode: ReferenceMode) throws -> String {
326 func blank(_ s: String) -> Bool { !s.contains { !$0.isWhitespace } }
327 func lisp(_ s: String) -> String {
328 switch mode.lisp {
329 case .literal: s
330 default: mode.numbers ? numberText(s) : Elisp.printed(.string(s), escape: true)
331 }
332 }
333 func calc(_ s: String) -> String { mode.numbers ? numberText(s) : s }
334 let empty = !mode.keepEmpty || mode.numbers ? "0" : "nan"
335 switch value {
336 case .field(let s):
337 if mode.lisp != .none { return lisp(s) }
338 return blank(s) ? (empty == "0" ? "(0)" : "nan") : "(" + calc(s) + ")"
339 case .list(var items):
340 if !mode.keepEmpty { items = items.filter { !blank($0) } }
341 if mode.lisp != .none { return items.map(lisp).joined(separator: " ") }
342 return "[" + items.map { blank($0) ? empty : calc($0) }.joined(separator: ",") + "]"
343 }
344 }
345
346 /// A number written in a formula, small enough to work with.
347 static func integer(_ s: String) throws -> Int {
348 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)") }
349 return n
350 }
351
352 /// `org-table-time-string-to-seconds`.
353 static func timeStringToSeconds(_ s: String) throws -> String {
354 guard !s.isEmpty else { return s }
355 func seconds(_ sign: Substring, _ parts: [Substring]) throws -> String {
356 var total = 0
357 for (i, part) in parts.enumerated() {
358 let (scaled, o1) = (Int(part) ?? Int.max).multipliedReportingOverflow(by: [3600, 60, 1][i])
359 let (sum, o2) = total.addingReportingOverflow(scaled)
360 if o1 || o2 || Int(part) == nil { throw Calc.Unsupported("duration size") }
361 total = sum
362 }
363 return String(sign.isEmpty ? total : -total)
364 }
365 if let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+):([0-9]+)/) { return try seconds(m.1, [m.2, m.3, m.4]) }
366 if s.range(of: timestampBoth, options: .regularExpression) == nil, let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+)/) {
367 return try seconds(m.1, [m.2, m.3])
368 }
369 return numberText(s)
370 }
371
372 enum DurationFormat { case hms, hhmm, hours }
373
374 /// `org-table-time-seconds-to-string`, with `org-table-duration-custom-format` `hours`
375 /// and zero-padded hours.
376 static func secondsToString(_ seconds: Sexp, _ format: DurationFormat) throws -> String {
377 let value = (try? Elisp.number(seconds))?.double ?? 0
378 let magnitude = abs(value)
379 guard magnitude.isFinite, magnitude < 1e15 else { throw Calc.Unsupported("duration size") }
380 let result: String
381 switch format {
382 case .hours:
383 result = String(format: "%.2f", magnitude / 3600)
384 case .hms, .hhmm:
385 let total = Int(magnitude.rounded(.down))
386 let hms = String(format: "%02d:%02d:%02d", total / 3600, total / 60 % 60, total % 60)
387 result = format == .hhmm ? String(hms.dropLast(3)) : hms
388 }
389 return value < 0 ? "-" + result : result
390 }
391
392 /// `org-table-convert-refs-to-rc` for a remote reference: `B3` is `@3$2`.
393 static func refsToRC(_ s: String) -> String {
394 let regex = try! NSRegularExpression(pattern: "(?<![A-Za-z0-9_$@])([a-zA-Z]{1,2})([0-9]+)(?![A-Za-z0-9_])")
395 var out = s
396 while let m = regex.firstMatch(in: out, range: NSRange(location: 0, length: (out as NSString).length)) {
397 let ns = out as NSString
398 let column = ns.substring(with: m.range(at: 1)).uppercased().unicodeScalars.reduce(0) { $0 * 26 + Int($1.value) - 64 }
399 out = ns.replacingCharacters(in: m.range, with: "@\(ns.substring(with: m.range(at: 2)))$\(column)")
400 }
401 return out
402 }
403
404 /// `org-table-get-constant`: a parameter or named field, a `#+CONSTANTS` value, or the
405 /// entry's property for `PROP_name`.
406 func tableConstant(_ name: String, analysis: TableAnalysis) -> String {
407 if let parameter = analysis.parameters.last(where: { $0.name == name }) { return parameter.value }
408 for m in (settings.setupKeywords + string).matches(of: #/(?mi)^[ \t]*#\+CONSTANTS:(.*)$/#) {
409 for pair in m.1.split(whereSeparator: \.isWhitespace) {
410 let parts = pair.split(separator: "=", maxSplits: 1)
411 if parts.count == 2, parts[0] == name { return String(parts[1]) }
412 }
413 }
414 if name.hasPrefix("PROP_"), let value = inheritedProperty(String(name.dropFirst(5)))?.value { return value }
415 return "#UNDEFINED_NAME"
416 }
417
418 /// `org-table-formula-substitute-names`: column names become `$N`; parameters, named
419 /// fields and constants their values, in parentheses outside Lisp formulas.
420 func substituteNames(_ formula: String, analysis: TableAnalysis) throws -> String {
421 let parenthesize = !formula.hasPrefix("'")
422 let duration = formula.range(of: ";.*[Tt].*$", options: .regularExpression) != nil
423 var new = formula
424 if !analysis.columnNames.isEmpty {
425 let names = analysis.columnNames.map { NSRegularExpression.escapedPattern(for: $0.name) }.joined(separator: "|")
426 let regex = try! NSRegularExpression(pattern: "\\$(\(names))(?![[:alnum:]])")
427 var start = 0
428 while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
429 let ns = new as NSString
430 let column = analysis.columnNames.first { $0.name == ns.substring(with: m.range(at: 1)) }!.column
431 new = ns.replacingCharacters(in: m.range, with: "$\(column)")
432 start = m.range.location + 1
433 }
434 }
435 let regex = try! NSRegularExpression(pattern: "\\$([a-zA-Z][_a-zA-Z0-9]*)|(\\bremote\\([^)]*\\))")
436 var start = 0
437 var substitutions = 0
438 while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
439 let ns = new as NSString
440 // A constant whose value names itself would go on forever, as it does in Org.
441 substitutions += 1
442 if substitutions > 1000 { throw Calc.Unsupported("constants that refer to themselves") }
443 if m.range(at: 2).location != NSNotFound {
444 start = NSMaxRange(m.range(at: 2))
445 continue
446 }
447 start = m.range.location + 1
448 var value = tableConstant(ns.substring(with: m.range(at: 1)), analysis: analysis)
449 if duration, value.contains(where: { !$0.isWhitespace }) { value = try Self.timeStringToSeconds(value) }
450 new = ns.replacingCharacters(in: m.range, with: parenthesize ? "(" + value + ")" : value)
451 }
452 return new
453 }
454
455 /// `org-table-get-remote-range`: the table after `#+NAME: name` in this file, or the first
456 /// table in the entry with that ID, in this file or another.
457 func remoteRange(_ name: String, _ form: String) throws -> TableRangeValue {
458 let escaped = NSRegularExpression.escapedPattern(for: name)
459 let keyword = try! NSRegularExpression(pattern: "^[ \\t]*#\\+(tbl)?name:[ \\t]*" + escaped + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
460 let idLine = try! NSRegularExpression(pattern: "^[ \\t]*:ID:[ \\t]+" + escaped + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
461 func first(_ regex: NSRegularExpression, in text: String) -> Int? {
462 regex.firstMatch(in: text, range: NSRange(location: 0, length: (text as NSString).length))?.range.location
463 }
464 // `org-id-find`: the entry's heading, here or in the file holding the ID.
465 func heading(_ text: String, _ offset: Int) -> Int {
466 let before = try! NSRegularExpression(pattern: "^\\*+ ", options: .anchorsMatchLines)
467 return before.matches(in: text, range: NSRange(location: 0, length: offset)).last?.range.location ?? 0
468 }
469 var text = string
470 let location: Int
471 if let found = first(keyword, in: string) {
472 location = found
473 } else if let found = first(idLine, in: string) {
474 location = heading(string, found)
475 } else if let other = RemoteTables.fileWithID?(name), let found = first(idLine, in: other) {
476 text = other
477 location = heading(other, found)
478 } else {
479 throw UserError(message: "Can't find remote table \"\(name)\"")
480 }
481 let ns = text as NSString
482 let after = min(ns.length, location + 1)
483 let next = try! NSRegularExpression(pattern: "^(\\*+ )|^[ \\t]*\\|", options: .anchorsMatchLines)
484 guard let m = next.firstMatch(in: text, range: NSRange(location: after, length: ns.length - after)),
485 m.range(at: 1).location == NSNotFound else {
486 throw UserError(message: "Cannot find a table at NAME or ID \(name)")
487 }
488 let remote = EmacsBuffer(text, point: m.range.location, settings: settings, options: options)
489 let analysis = try remote.tableAnalyze()
490 let resolved = try remote.substituteNames(try Self.handleFirstLast(Self.refsToRC(form), analysis: analysis), analysis: analysis)
491 let range = try! NSRegularExpression(pattern: Self.rangePattern)
492 let rns = resolved as NSString
493 if let r = range.firstMatch(in: resolved, range: NSRange(location: 0, length: rns.length)), r.range.length > 1 {
494 return try remote.tableRange(rns.substring(with: r.range), thisline: 0, col: 1, analysis: analysis)
495 }
496 return .field(resolved)
497 }
498
499 /// `org-table-eval-formula` with the equation given, at point. `substituted` when names
500 /// and constants were already replaced, as `org-table-recalculate` does.
501 func tableEvalFormula(_ formula: String, analysis: TableAnalysis, substituted: Bool = true) throws {
502 var formula = formula
503 var modes = Calc.Modes()
504 var mode = ReferenceMode()
505 var duration: DurationFormat?
506 var literal = false
507 var fmt: String?
508 if let semicolon = formula.lastIndex(of: ";") {
509 var flags = (analysis.parameters.last { $0.name == "%" }?.value ?? "") + formula[formula.index(after: semicolon)...]
510 formula = String(formula[..<semicolon])
511 let numeric = try! NSRegularExpression(pattern: "([pnfse])(-?[0-9]+)")
512 while let m = numeric.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
513 let ns = flags as NSString
514 let n = try Self.integer(ns.substring(with: m.range(at: 2)))
515 switch ns.substring(with: m.range(at: 1)) {
516 case "p": modes.precision = n
517 case "n": modes.format = .float(n)
518 case "f": modes.format = .fix(n)
519 case "s": modes.format = .sci(n)
520 default: modes.format = .eng(n)
521 }
522 flags = ns.replacingCharacters(in: m.range, with: "")
523 }
524 let letters = try! NSRegularExpression(pattern: "[tTUNLEDRFSu]")
525 while let m = letters.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
526 let ns = flags as NSString
527 switch ns.substring(with: m.range) {
528 case "t": (duration, mode.numbers) = (.hours, true)
529 case "T": (duration, mode.numbers) = (.hms, true)
530 case "U": (duration, mode.numbers) = (.hhmm, true)
531 case "N": mode.numbers = true
532 case "L": literal = true
533 case "E": mode.keepEmpty = true
534 case "F": modes.preferFractions = true
535 case "D": modes.degrees = true
536 case "R": modes.degrees = false
537 case "S": modes.symbolic = true
538 default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))")
539 }
540 flags = ns.replacingCharacters(in: m.range, with: "")
541 }
542 if flags.contains(where: { !$0.isWhitespace }) { fmt = flags }
543 }
544 if !substituted { formula = try Self.handleFirstLast(try substituteNames(formula, analysis: analysis), analysis: analysis) }
545 var fields = Self.splitFields(substring(lineStart(point), lineEnd(point)).trimmingCharacters(in: .whitespaces), separator: " *\\| *")
546 if duration != nil { fields = try fields.map(Self.timeStringToSeconds) }
547 if mode.numbers { fields = fields.map { $0.contains(where: { !$0.isWhitespace }) ? Self.numberText($0) : $0 } }
548 if formula.count > 2, formula.hasPrefix("'(") { mode.lisp = literal ? .literal : .lisp }
549 func reference(_ value: TableRangeValue) throws -> String {
550 guard duration != nil else { return try Self.makeReference(value, mode) }
551 switch value {
552 case .field(let s): return try Self.makeReference(.field(try Self.timeStringToSeconds(s)), mode)
553 case .list(let items): return try Self.makeReference(.list(try items.map(Self.timeStringToSeconds)), mode)
554 }
555 }
556 let n0 = tableCurrentColumn()
557 let thisline = try saveExcursion { () -> Int in
558 let here = lineStart(point)
559 point = analysis.begin
560 var count = 0
561 while point < here {
562 if forwardLine(1) != 0 { throw Calc.Unsupported("table position") }
563 count += 1
564 }
565 return count
566 }
567 var form = formula
568 form = form.replacingOccurrences(of: "@#", with: String(tableCurrentDataLine()))
569 form = form.replacingOccurrences(of: "$#", with: String(n0))
570 // `org-table-remote-reference-indirection`: `remote($1, …)` names the table in a field.
571 let indirect = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([@$][^ \\t,]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
572 var start = 0
573 while let m = indirect.firstMatch(in: form, range: NSRange(location: start, length: (form as NSString).length - start)) {
574 let ns = form as NSString
575 var eq = try Self.handleFirstLast(ns.substring(with: m.range(at: 1)), analysis: analysis)
576 if eq.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil { eq = "@0" + eq }
577 guard case .field(let name) = try tableRange(eq, thisline: thisline, col: n0, analysis: analysis) else {
578 throw Calc.Unsupported("remote table name from a range")
579 }
580 form = ns.replacingCharacters(in: m.range(at: 1), with: name)
581 start = m.range(at: 1).location + (name as NSString).length
582 }
583 let remote = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([^,)]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
584 while let m = remote.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
585 let ns = form as NSString
586 let name = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)
587 let value = try remoteRange(name, ns.substring(with: m.range(at: 2)))
588 form = ns.replacingCharacters(in: m.range, with: try reference(value))
589 }
590 let range = try! NSRegularExpression(pattern: Self.rangePattern)
591 while let m = range.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)), m.range.length > 1 {
592 let ns = form as NSString
593 let replacement = try reference(try tableRange(ns.substring(with: m.range), thisline: thisline, col: n0, analysis: analysis))
594 if replacement.contains(form) { throw UserError(message: "Spreadsheet error: invalid reference \"\(form)\"") }
595 form = ns.replacingCharacters(in: m.range, with: replacement)
596 }
597 let rowRange = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)\\.\\.\\$(([-+])?[0-9]+)")
598 while let m = rowRange.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
599 let ns = form as NSString
600 let a = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
601 let b = try Self.integer(ns.substring(with: m.range(at: 3))) + (m.range(at: 4).location != NSNotFound ? n0 : 0)
602 guard a >= 1, b <= fields.count, a - 1 <= b else { throw Calc.Unsupported("range outside row") }
603 form = ns.replacingCharacters(in: m.range, with: try Self.makeReference(.list(Array(fields[(a - 1)..<b])), mode))
604 }
605 let single = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)")
606 while let m = single.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
607 let ns = form as NSString
608 let n = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
609 let index = (n == 0 ? n0 : max(n, 1)) - 1
610 guard index < fields.count else { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
611 let replacement = try Self.makeReference(.field(fields[index]), mode)
612 if replacement.contains(formula) { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
613 form = ns.replacingCharacters(in: m.range, with: replacement)
614 }
615
616 var result: String
617 if mode.lisp != .none {
618 if let value = try evalLisp(form, duration: duration) { result = value } else { (result, fmt) = ("#ERROR", nil) }
619 } else {
620 form = form.replacingOccurrences(of: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)\\]", with: "<$1>", options: .regularExpression)
621 form = Self.normalizeTimestamps(form)
622 if duration != nil, form.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil {
623 result = form
624 } else {
625 do {
626 result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
627 } catch let failure as Calc.Failure {
628 // A duration formula takes Calc's error for a string, as org does.
629 if duration != nil { throw UserError(message: "Wrong type argument: stringp, (\(failure.position) \"\(failure.reason)\")") }
630 (result, fmt) = ("#ERROR", nil)
631 }
632 }
633 if let duration, !result.isEmpty, result != "#ERROR" {
634 let seconds = result.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil ? try Self.timeStringToSeconds(result) : result
635 result = try Self.secondsToString(Elisp.stringToNumber(seconds), duration)
636 }
637 }
638 if let fmt {
639 do {
640 result = try Elisp.format([.string(fmt), Elisp.stringToNumber(result)])
641 } catch let error as Elisp.Signal {
642 throw UserError(message: error.message)
643 }
644 } else {
645 result = result.replacingOccurrences(of: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>", with: "[$1]", options: .regularExpression)
646 }
647 tableSetField(result)
648 }
649
650 /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`, and a cons is nil
651 /// (`#ERROR` without the format).
652 func evalLisp(_ form: String, duration: DurationFormat?) throws -> String? {
653 let lisp = Elisp()
654 lisp.standardTime()
655 Self.defineLookups(lisp)
656 Babel.defineSbe(lisp) { [unowned self] in text as String }
657 let value: Sexp
658 do {
659 value = try lisp.eval(try lisp.eval(try LispReader.readFirst(form).sexp))
660 } catch let unsupported as Elisp.Unsupported {
661 throw Calc.Unsupported("Lisp \(unsupported.what)")
662 } catch {
663 return "#ERROR"
664 }
665 // Emacs prints functions as `#[ARGS BODY ENV]`.
666 if Elisp.containsClosure(value) { throw Calc.Unsupported("Lisp formula with a function value") }
667 switch value {
668 case .list([]): break
669 case .list, .dotted:
670 // Org converts a duration before checking for a cons, which signals.
671 if duration != nil { throw Calc.Unsupported("Lisp formula with a list value and a duration") }
672 return nil
673 default: break
674 }
675 var result = Elisp.printed(value)
676 if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) }
677 return result
678 }
679
680 /// `org-lookup-first`, `org-lookup-last` and `org-lookup-all`.
681 static func defineLookups(_ lisp: Elisp) {
682 func matches(_ lisp: Elisp, _ args: [Sexp]) throws -> [Sexp] {
683 try Elisp.arity(args, 3...4, "org-lookup")
684 let keys = try Elisp.elements(args[1])
685 let values = Elisp.isNil(args[2]) ? keys : try Elisp.elements(args[2])
686 let predicate = args.count > 3 && !Elisp.isNil(args[3]) ? args[3] : .symbol("equal")
687 var found: [Sexp] = []
688 for (i, key) in keys.enumerated() where !Elisp.isNil(try lisp.call(predicate, [args[0], key])) {
689 found.append(i < values.count ? values[i] : .nil)
690 }
691 return found
692 }
693 lisp.define("org-lookup-first") { lisp, args in try matches(lisp, args).first ?? .nil }
694 lisp.define("org-lookup-last") { lisp, args in try matches(lisp, args).last ?? .nil }
695 lisp.define("org-lookup-all") { lisp, args in
696 let found = try matches(lisp, args)
697 return found.isEmpty ? .nil : .list(found)
698 }
699 }
700
701 /// Timestamps in a formula as Calc reads them: `<YYYY-MM-DD Www>`, with ` HH:MM` when
702 /// the stamp has a time, as org formats them for Calc.
703 static func normalizeTimestamps(_ form: String) -> String {
704 let regex = try! NSRegularExpression(pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>")
705 var out = form
706 var start = 0
707 while let m = regex.firstMatch(in: out, range: NSRange(location: start, length: (out as NSString).length - start)) {
708 let ns = out as NSString
709 let stamp = ns.substring(with: m.range(at: 1))
710 let parts = stamp.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})/)!
711 let day = Days.absolute(year: Int(parts.1)!, month: Int(parts.2)!, day: Int(parts.3)!)
712 let date = Days.date(day)
713 var text = String(format: "<%04d-%02d-%02d %@", date.year, date.month, date.day, Calc.weekdays[Days.weekday(day)])
714 if let time = stamp.firstMatch(of: /([0-9]{1,2}):([0-9]{2})/) {
715 text += String(format: " %02d:%02d", Int(time.1)!, Int(time.2)!)
716 }
717 text += ">"
718 out = ns.replacingCharacters(in: m.range, with: text)
719 start = m.range.location + (text as NSString).length
720 }
721 return out
722 }
723
724 /// `string-to-number`.
725 static func stringToNumber(_ s: String) -> Double {
726 guard let r = s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return 0 }
727 return Double(s[r]) ?? 0
728 }
729
730 /// `org-table-justify-field-maybe` while the table needs realigning: the field becomes
731 /// ` NEW |`.
732 func tableSetField(_ value: String) {
733 let pos = point
734 guard tableCurrentColumn() > 0 else { return }
735 skipBackwardNot([124])
736 let start = point
737 var end = point
738 while let c = character(at: end), c != 124, c != 10 { end += 1 }
739 let closed = character(at: end) == 124
740 replaceRange(start, closed ? end + 1 : end, with: " \(value) |")
741 point = min(pos, length)
742 }
743
744 func replaceRange(_ start: Int, _ end: Int, with text: String) {
745 let saved = point
746 deleteRegion(start, end)
747 point = start
748 insert(text)
749 point = saved
750 }
751
752 /// `org-table-recalculate`: `all` for every row, otherwise the line at point; `tblfm`
753 /// replaces the stored formulas, as C-c C-c on a `#+TBLFM` line does.
754 func tableRecalculate(all: Bool, tblfm: String? = nil) throws {
755 guard atTable else { throw UserError(message: "Not at a table") }
756 let analysis = try tableAnalyze()
757 let end = tableEnd()
758 guard let line = tblfm ?? firstTblfm(after: end) else { return }
759 let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
760 guard !stored.isEmpty else { return }
761 // `org-table-save-field`: the field is restored even when a formula fails.
762 let savedLine = lineStart(point)
763 let savedColumn = tableCurrentColumn()
764 let lineMarker = marker(savedLine)
765 defer { release(lineMarker) }
766 defer {
767 point = lineMarker.position
768 tableGotoColumn(savedColumn)
769 }
770 var columnEquations: [(column: Int, rhs: String, lhs: String)] = []
771 var fieldEquations: [(String, String, String)] = []
772 for (oldLHS, rawRHS) in stored {
773 let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis)
774 if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
775 let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
776 if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil {
777 columnEquations.append((try Self.integer(String(lhs.dropFirst())), rhs, oldLHS))
778 } else {
779 fieldEquations.append((lhs, rhs, oldLHS))
780 }
781 }
782 // `org-table-expand-lhs-ranges`.
783 var fields: [(row: Int, column: Int, rhs: String, lhs: String)] = []
784 for (lhs, rhs, oldLHS) in fieldEquations {
785 if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) {
786 fields.append((try Self.integer(String(m.1)), try Self.integer(String(m.2)), rhs, oldLHS))
787 } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil {
788 guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else {
789 throw UserError(message: "Unknown field: \(lhs)")
790 }
791 fields.append((row, location.column, rhs, oldLHS))
792 } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil {
793 // `org-table-goto-field` knows only absolute fields and names.
794 throw UserError(message: "Unknown field: \(lhs)")
795 } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
796 let row = try Self.integer(String(m.1))
797 for c in 1...analysis.ncol { fields.append((row, c, rhs, oldLHS)) }
798 } else {
799 let corners = try rangeCorners(lhs, analysis: analysis)
800 guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
801 throw Calc.Unsupported("formula range")
802 }
803 for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs, oldLHS)) } }
804 }
805 }
806 let endMarker = marker(end)
807 defer { release(endMarker) }
808 var beg: Int
809 var lineRegexp = "^[ \\t]*\\|[^-]"
810 if all, analysis.marked {
811 beg = analysis.begin
812 lineRegexp = "^[ \\t]*\\| *[#*] *(\\||$)"
813 } else if all {
814 beg = analysis.begin
815 point = beg
816 if searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) != nil,
817 searchForward("^[ \\t]*\\|-", bound: end, caseInsensitive: false) != nil,
818 let body = searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
819 beg = body[0]!.lowerBound
820 }
821 } else {
822 beg = lineStart(point)
823 endMarker.position = min(length, lineEnd(point) + 1)
824 }
825
826 let currentLine = savedLine - 0
827 var seen: Set<String> = []
828 var untouchable: Set<String> = []
829 for field in fields {
830 let reference = "@\(field.row)$\(field.column)"
831 guard seen.insert(reference).inserted else { throw UserError(message: "Several field/range formulas try to set \(reference)") }
832 guard field.row < analysis.dlines.count else { throw UserError(message: "Invalid row number in \(reference)") }
833 let lineStartOffset = saveExcursion { () -> Int in
834 gotoTableLine(analysis.dlines[field.row], analysis)
835 return lineStart(point)
836 }
837 if all || lineStartOffset == currentLine { untouchable.insert(reference) }
838 }
839
840 point = beg
841 let rowMarker = marker(beg)
842 defer { release(rowMarker) }
843 while let match = searchForward(lineRegexp, bound: endMarker.position, caseInsensitive: false) {
844 _ = match
845 let rowStart = lineStart(point)
846 rowMarker.position = rowStart
847 let first = saveExcursion { () -> String in
848 point = rowStart
849 return tableField(1)
850 }
851 if first.range(of: "^ *[_^!$/] *$", options: .regularExpression) == nil {
852 let dline = saveExcursion { () -> Int in
853 point = rowStart
854 return tableCurrentDataLine()
855 }
856 for (column, rhs, lhs) in columnEquations {
857 point = rowMarker.position
858 tableGotoColumn(column, force: true)
859 // Org reads the mark at point, which in a field of one space is on the bar
860 // after it, so the column formula still runs there.
861 if untouchable.contains("@\(dline)$\(column)"), let c = character(at: point), c != 124, c != 10 { continue }
862 try Self.naming(lhs) { try tableEvalFormula(rhs, analysis: analysis) }
863 }
864 }
865 point = rowMarker.position
866 if forwardLine(1) != 0 || point >= endMarker.position { break }
867 }
868 for field in fields {
869 gotoTableLine(analysis.dlines[field.row], analysis)
870 let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
871 if field.column > count { throw UserError(message: "Missing columns in the table. Aborting") }
872 tableGotoColumn(field.column)
873 try Self.naming(field.lhs) { try tableEvalFormula(field.rhs, analysis: analysis) }
874 }
875 tableAlign()
876 }
877
878 /// `body`, with the formula `lhs` named in a `Calc.Unsupported` it throws.
879 static func naming(_ lhs: String, _ body: () throws -> Void) throws {
880 do {
881 try body()
882 } catch var error as Calc.Unsupported {
883 error.formula = lhs
884 throw error
885 }
886 }
887
888 /// `org-table-get-range` with `corners-only`.
889 func rangeCorners(_ desc: String, analysis: TableAnalysis) throws -> (r1: Int, c1: Int, r2: Int, c2: Int) {
890 let ns = desc as NSString
891 guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
892 throw UserError(message: "Invalid table range specifier `\(desc)'")
893 }
894 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
895 let thisline = 0
896 func row(_ r: String?) throws -> Int {
897 guard let r, !r.isEmpty else { return thisline }
898 return try Self.descriptorLine(r, thisline, analysis: analysis)
899 }
900 func column(_ c: String?) -> Int {
901 guard let c, let n = Int(c.dropFirst()), n != 0 else { return 1 }
902 return n + (c.dropFirst().first == "-" || c.dropFirst().first == "+" ? 1 : 0)
903 }
904 let r1 = try row(group(1))
905 let r2 = try row(group(4))
906 let c1 = column(group(2))
907 let c2 = column(group(5))
908 return (min(r1, r2), min(c1, c2), max(r1, r2), max(c1, c2))
909 }
910
911 /// `org-table-line-to-dline`.
912 static func lineToDline(_ line: Int, _ analysis: TableAnalysis, above: Bool = false) -> Int? {
913 let dlines = analysis.dlines
914 var low = 1
915 var high = dlines.count - 1
916 if dlines[low] > line || dlines[high] < line { return nil }
917 if line == dlines[high] { return high }
918 while high - low > 1 {
919 let mean = (high + low) / 2
920 if dlines[mean] == line { return mean }
921 if dlines[mean] > line { high = mean } else { low = mean }
922 }
923 if line == dlines[high] { return high }
924 if line == dlines[low] { return low }
925 return above ? low : high
926 }
927}