Sources/OrgCore/Compute/TableFormulas.swift
cmc Calc: precision modes, fractions, percent, factorial, radix, juxtaposition and more functions
24b578029b 6 days ago906 lines · 47945 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` 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 static let calcNumber = "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?$"
310 /// `org-ts-regexp-both`.
311 static let timestampBoth = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)[\\]>]"
312
313 /// How `org-table-make-reference` turns fields into formula text.
314 struct ReferenceMode {
315 enum Lisp { case none, lisp, literal }
316 var keepEmpty = false
317 var numbers = false
318 var lisp = Lisp.none
319 }
320
321 /// `number-to-string` of `string-to-number`.
322 static func numberText(_ s: String) -> String { Elisp.printed(Elisp.stringToNumber(s)) }
323
324 /// `org-table-make-reference`. For Calc, a field that isn't a number, a date or `nan`
325 /// would be a symbol, which isn't supported.
326 static func makeReference(_ value: TableRangeValue, _ mode: ReferenceMode) throws -> String {
327 func blank(_ s: String) -> Bool { !s.contains { !$0.isWhitespace } }
328 func lisp(_ s: String) -> String {
329 switch mode.lisp {
330 case .literal: s
331 default: mode.numbers ? numberText(s) : Elisp.printed(.string(s), escape: true)
332 }
333 }
334 func calc(_ s: String) throws -> String {
335 let text = mode.numbers ? numberText(s) : s
336 guard text.range(of: calcNumber, options: .regularExpression) != nil || text == "nan"
337 || text.range(of: "^[-+]?[0-9]+:[0-9:]+$", options: .regularExpression) != nil
338 || text.range(of: "^" + timestampBoth + "$", options: .regularExpression) != nil else {
339 throw Calc.Unsupported("non-numeric field \(text)")
340 }
341 return text
342 }
343 let empty = !mode.keepEmpty || mode.numbers ? "0" : "nan"
344 switch value {
345 case .field(let s):
346 if mode.lisp != .none { return lisp(s) }
347 return blank(s) ? (empty == "0" ? "(0)" : "nan") : "(" + (try calc(s)) + ")"
348 case .list(var items):
349 if !mode.keepEmpty { items = items.filter { !blank($0) } }
350 if mode.lisp != .none { return items.map(lisp).joined(separator: " ") }
351 return "[" + (try items.map { blank($0) ? empty : try calc($0) }).joined(separator: ",") + "]"
352 }
353 }
354
355 /// A number written in a formula, small enough to work with.
356 static func integer(_ s: String) throws -> Int {
357 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)") }
358 return n
359 }
360
361 /// `org-table-time-string-to-seconds`.
362 static func timeStringToSeconds(_ s: String) throws -> String {
363 guard !s.isEmpty else { return s }
364 func seconds(_ sign: Substring, _ parts: [Substring]) throws -> String {
365 var total = 0
366 for (i, part) in parts.enumerated() {
367 let (scaled, o1) = (Int(part) ?? Int.max).multipliedReportingOverflow(by: [3600, 60, 1][i])
368 let (sum, o2) = total.addingReportingOverflow(scaled)
369 if o1 || o2 || Int(part) == nil { throw Calc.Unsupported("duration size") }
370 total = sum
371 }
372 return String(sign.isEmpty ? total : -total)
373 }
374 if let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+):([0-9]+)/) { return try seconds(m.1, [m.2, m.3, m.4]) }
375 if s.range(of: timestampBoth, options: .regularExpression) == nil, let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+)/) {
376 return try seconds(m.1, [m.2, m.3])
377 }
378 return numberText(s)
379 }
380
381 enum DurationFormat { case hms, hhmm, hours }
382
383 /// `org-table-time-seconds-to-string`, with `org-table-duration-custom-format` `hours`
384 /// and zero-padded hours.
385 static func secondsToString(_ seconds: Sexp, _ format: DurationFormat) throws -> String {
386 let value = (try? Elisp.number(seconds))?.double ?? 0
387 let magnitude = abs(value)
388 guard magnitude.isFinite, magnitude < 1e15 else { throw Calc.Unsupported("duration size") }
389 let result: String
390 switch format {
391 case .hours:
392 result = String(format: "%.2f", magnitude / 3600)
393 case .hms, .hhmm:
394 let total = Int(magnitude.rounded(.down))
395 let hms = String(format: "%02d:%02d:%02d", total / 3600, total / 60 % 60, total % 60)
396 result = format == .hhmm ? String(hms.dropLast(3)) : hms
397 }
398 return value < 0 ? "-" + result : result
399 }
400
401 /// `org-table-convert-refs-to-rc` for a remote reference: `B3` is `@3$2`.
402 static func refsToRC(_ s: String) -> String {
403 let regex = try! NSRegularExpression(pattern: "(?<![A-Za-z0-9_$@])([a-zA-Z]{1,2})([0-9]+)(?![A-Za-z0-9_])")
404 var out = s
405 while let m = regex.firstMatch(in: out, range: NSRange(location: 0, length: (out as NSString).length)) {
406 let ns = out as NSString
407 let column = ns.substring(with: m.range(at: 1)).uppercased().unicodeScalars.reduce(0) { $0 * 26 + Int($1.value) - 64 }
408 out = ns.replacingCharacters(in: m.range, with: "@\(ns.substring(with: m.range(at: 2)))$\(column)")
409 }
410 return out
411 }
412
413 /// `org-table-get-constant`: a parameter or named field, a `#+CONSTANTS` value, or the
414 /// entry's property for `PROP_name`.
415 func tableConstant(_ name: String, analysis: TableAnalysis) -> String {
416 if let parameter = analysis.parameters.last(where: { $0.name == name }) { return parameter.value }
417 for m in (settings.setupKeywords + string).matches(of: #/(?mi)^[ \t]*#\+CONSTANTS:(.*)$/#) {
418 for pair in m.1.split(whereSeparator: \.isWhitespace) {
419 let parts = pair.split(separator: "=", maxSplits: 1)
420 if parts.count == 2, parts[0] == name { return String(parts[1]) }
421 }
422 }
423 if name.hasPrefix("PROP_"), let value = inheritedProperty(String(name.dropFirst(5)))?.value { return value }
424 return "#UNDEFINED_NAME"
425 }
426
427 /// `org-table-formula-substitute-names`: column names become `$N`; parameters, named
428 /// fields and constants their values, in parentheses outside Lisp formulas.
429 func substituteNames(_ formula: String, analysis: TableAnalysis) throws -> String {
430 let parenthesize = !formula.hasPrefix("'")
431 let duration = formula.range(of: ";.*[Tt].*$", options: .regularExpression) != nil
432 var new = formula
433 if !analysis.columnNames.isEmpty {
434 let names = analysis.columnNames.map { NSRegularExpression.escapedPattern(for: $0.name) }.joined(separator: "|")
435 let regex = try! NSRegularExpression(pattern: "\\$(\(names))(?![[:alnum:]])")
436 var start = 0
437 while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
438 let ns = new as NSString
439 let column = analysis.columnNames.first { $0.name == ns.substring(with: m.range(at: 1)) }!.column
440 new = ns.replacingCharacters(in: m.range, with: "$\(column)")
441 start = m.range.location + 1
442 }
443 }
444 let regex = try! NSRegularExpression(pattern: "\\$([a-zA-Z][_a-zA-Z0-9]*)|(\\bremote\\([^)]*\\))")
445 var start = 0
446 var substitutions = 0
447 while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
448 let ns = new as NSString
449 // A constant whose value names itself would go on forever, as it does in Org.
450 substitutions += 1
451 if substitutions > 1000 { throw Calc.Unsupported("constants that refer to themselves") }
452 if m.range(at: 2).location != NSNotFound {
453 start = NSMaxRange(m.range(at: 2))
454 continue
455 }
456 start = m.range.location + 1
457 var value = tableConstant(ns.substring(with: m.range(at: 1)), analysis: analysis)
458 if duration, value.contains(where: { !$0.isWhitespace }) { value = try Self.timeStringToSeconds(value) }
459 new = ns.replacingCharacters(in: m.range, with: parenthesize ? "(" + value + ")" : value)
460 }
461 return new
462 }
463
464 /// `org-table-get-remote-range`: the table after `#+NAME: name` in this file, or the first
465 /// table in the entry with that ID, in this file or another.
466 func remoteRange(_ name: String, _ form: String) throws -> TableRangeValue {
467 let escaped = NSRegularExpression.escapedPattern(for: name)
468 let keyword = try! NSRegularExpression(pattern: "^[ \\t]*#\\+(tbl)?name:[ \\t]*" + escaped + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
469 let idLine = try! NSRegularExpression(pattern: "^[ \\t]*:ID:[ \\t]+" + escaped + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
470 func first(_ regex: NSRegularExpression, in text: String) -> Int? {
471 regex.firstMatch(in: text, range: NSRange(location: 0, length: (text as NSString).length))?.range.location
472 }
473 // `org-id-find`: the entry's heading, here or in the file holding the ID.
474 func heading(_ text: String, _ offset: Int) -> Int {
475 let before = try! NSRegularExpression(pattern: "^\\*+ ", options: .anchorsMatchLines)
476 return before.matches(in: text, range: NSRange(location: 0, length: offset)).last?.range.location ?? 0
477 }
478 var text = string
479 let location: Int
480 if let found = first(keyword, in: string) {
481 location = found
482 } else if let found = first(idLine, in: string) {
483 location = heading(string, found)
484 } else if let other = RemoteTables.fileWithID?(name), let found = first(idLine, in: other) {
485 text = other
486 location = heading(other, found)
487 } else {
488 throw UserError(message: "Can't find remote table \"\(name)\"")
489 }
490 let ns = text as NSString
491 let after = min(ns.length, location + 1)
492 let next = try! NSRegularExpression(pattern: "^(\\*+ )|^[ \\t]*\\|", options: .anchorsMatchLines)
493 guard let m = next.firstMatch(in: text, range: NSRange(location: after, length: ns.length - after)),
494 m.range(at: 1).location == NSNotFound else {
495 throw UserError(message: "Cannot find a table at NAME or ID \(name)")
496 }
497 let remote = EmacsBuffer(text, point: m.range.location, settings: settings, options: options)
498 let analysis = try remote.tableAnalyze()
499 let resolved = try remote.substituteNames(try Self.handleFirstLast(Self.refsToRC(form), analysis: analysis), analysis: analysis)
500 let range = try! NSRegularExpression(pattern: Self.rangePattern)
501 let rns = resolved as NSString
502 if let r = range.firstMatch(in: resolved, range: NSRange(location: 0, length: rns.length)), r.range.length > 1 {
503 return try remote.tableRange(rns.substring(with: r.range), thisline: 0, col: 1, analysis: analysis)
504 }
505 return .field(resolved)
506 }
507
508 /// `org-table-eval-formula` with the equation given, at point. `substituted` when names
509 /// and constants were already replaced, as `org-table-recalculate` does.
510 func tableEvalFormula(_ formula: String, analysis: TableAnalysis, substituted: Bool = true) throws {
511 var formula = formula
512 var modes = Calc.Modes()
513 var mode = ReferenceMode()
514 var duration: DurationFormat?
515 var literal = false
516 var fmt: String?
517 if let semicolon = formula.lastIndex(of: ";") {
518 var flags = (analysis.parameters.last { $0.name == "%" }?.value ?? "") + formula[formula.index(after: semicolon)...]
519 formula = String(formula[..<semicolon])
520 let numeric = try! NSRegularExpression(pattern: "([pnfse])(-?[0-9]+)")
521 while let m = numeric.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
522 let ns = flags as NSString
523 let n = try Self.integer(ns.substring(with: m.range(at: 2)))
524 switch ns.substring(with: m.range(at: 1)) {
525 case "p": modes.precision = n
526 case "n": modes.format = .float(n)
527 case "f": modes.format = .fix(n)
528 case "s": modes.format = .sci(n)
529 default: modes.format = .eng(n)
530 }
531 flags = ns.replacingCharacters(in: m.range, with: "")
532 }
533 let letters = try! NSRegularExpression(pattern: "[tTUNLEDRFSu]")
534 while let m = letters.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
535 let ns = flags as NSString
536 switch ns.substring(with: m.range) {
537 case "t": (duration, mode.numbers) = (.hours, true)
538 case "T": (duration, mode.numbers) = (.hms, true)
539 case "U": (duration, mode.numbers) = (.hhmm, true)
540 case "N": mode.numbers = true
541 case "L": literal = true
542 case "E": mode.keepEmpty = true
543 case "F": modes.preferFractions = true
544 case "D": modes.degrees = true
545 case "R": modes.degrees = false
546 default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))")
547 }
548 flags = ns.replacingCharacters(in: m.range, with: "")
549 }
550 if flags.contains(where: { !$0.isWhitespace }) { fmt = flags }
551 }
552 if !substituted { formula = try Self.handleFirstLast(try substituteNames(formula, analysis: analysis), analysis: analysis) }
553 var fields = Self.splitFields(substring(lineStart(point), lineEnd(point)).trimmingCharacters(in: .whitespaces), separator: " *\\| *")
554 if duration != nil { fields = try fields.map(Self.timeStringToSeconds) }
555 if mode.numbers { fields = fields.map { $0.contains(where: { !$0.isWhitespace }) ? Self.numberText($0) : $0 } }
556 if formula.count > 2, formula.hasPrefix("'(") { mode.lisp = literal ? .literal : .lisp }
557 func reference(_ value: TableRangeValue) throws -> String {
558 guard duration != nil else { return try Self.makeReference(value, mode) }
559 switch value {
560 case .field(let s): return try Self.makeReference(.field(try Self.timeStringToSeconds(s)), mode)
561 case .list(let items): return try Self.makeReference(.list(try items.map(Self.timeStringToSeconds)), mode)
562 }
563 }
564 let n0 = tableCurrentColumn()
565 let thisline = try saveExcursion { () -> Int in
566 let here = lineStart(point)
567 point = analysis.begin
568 var count = 0
569 while point < here {
570 if forwardLine(1) != 0 { throw Calc.Unsupported("table position") }
571 count += 1
572 }
573 return count
574 }
575 var form = formula
576 form = form.replacingOccurrences(of: "@#", with: String(tableCurrentDataLine()))
577 form = form.replacingOccurrences(of: "$#", with: String(n0))
578 // `org-table-remote-reference-indirection`: `remote($1, …)` names the table in a field.
579 let indirect = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([@$][^ \\t,]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
580 var start = 0
581 while let m = indirect.firstMatch(in: form, range: NSRange(location: start, length: (form as NSString).length - start)) {
582 let ns = form as NSString
583 var eq = try Self.handleFirstLast(ns.substring(with: m.range(at: 1)), analysis: analysis)
584 if eq.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil { eq = "@0" + eq }
585 guard case .field(let name) = try tableRange(eq, thisline: thisline, col: n0, analysis: analysis) else {
586 throw Calc.Unsupported("remote table name from a range")
587 }
588 form = ns.replacingCharacters(in: m.range(at: 1), with: name)
589 start = m.range(at: 1).location + (name as NSString).length
590 }
591 let remote = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([^,)]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
592 while let m = remote.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
593 let ns = form as NSString
594 let name = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)
595 let value = try remoteRange(name, ns.substring(with: m.range(at: 2)))
596 form = ns.replacingCharacters(in: m.range, with: try reference(value))
597 }
598 let range = try! NSRegularExpression(pattern: Self.rangePattern)
599 while let m = range.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)), m.range.length > 1 {
600 let ns = form as NSString
601 let replacement = try reference(try tableRange(ns.substring(with: m.range), thisline: thisline, col: n0, analysis: analysis))
602 if replacement.contains(form) { throw UserError(message: "Spreadsheet error: invalid reference \"\(form)\"") }
603 form = ns.replacingCharacters(in: m.range, with: replacement)
604 }
605 let rowRange = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)\\.\\.\\$(([-+])?[0-9]+)")
606 while let m = rowRange.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
607 let ns = form as NSString
608 let a = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
609 let b = try Self.integer(ns.substring(with: m.range(at: 3))) + (m.range(at: 4).location != NSNotFound ? n0 : 0)
610 guard a >= 1, b <= fields.count, a - 1 <= b else { throw Calc.Unsupported("range outside row") }
611 form = ns.replacingCharacters(in: m.range, with: try Self.makeReference(.list(Array(fields[(a - 1)..<b])), mode))
612 }
613 let single = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)")
614 while let m = single.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
615 let ns = form as NSString
616 let n = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
617 let index = (n == 0 ? n0 : max(n, 1)) - 1
618 guard index < fields.count else { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
619 let replacement = try Self.makeReference(.field(fields[index]), mode)
620 if replacement.contains(formula) { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
621 form = ns.replacingCharacters(in: m.range, with: replacement)
622 }
623
624 var result: String
625 if mode.lisp != .none {
626 result = try evalLisp(form, duration: duration)
627 } else {
628 form = form.replacingOccurrences(of: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)\\]", with: "<$1>", options: .regularExpression)
629 form = Self.normalizeTimestamps(form)
630 if duration != nil, form.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil {
631 result = form
632 } else {
633 do {
634 result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
635 } catch is Calc.Failure {
636 (result, fmt) = ("#ERROR", nil)
637 }
638 }
639 if let duration, !result.isEmpty, result != "#ERROR" {
640 let seconds = result.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil ? try Self.timeStringToSeconds(result) : result
641 result = try Self.secondsToString(Elisp.stringToNumber(seconds), duration)
642 }
643 }
644 if let fmt {
645 do {
646 result = try Elisp.format([.string(fmt), Elisp.stringToNumber(result)])
647 } catch let error as Elisp.Signal {
648 throw UserError(message: error.message)
649 }
650 } else {
651 result = result.replacingOccurrences(of: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>", with: "[$1]", options: .regularExpression)
652 }
653 tableSetField(result)
654 }
655
656 /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`.
657 func evalLisp(_ form: String, duration: DurationFormat?) throws -> String {
658 let lisp = Elisp()
659 Self.defineLookups(lisp)
660 let value: Sexp
661 do {
662 value = try lisp.eval(try lisp.eval(try LispReader.readFirst(form).sexp))
663 } catch let unsupported as Elisp.Unsupported {
664 throw Calc.Unsupported("Lisp \(unsupported.what)")
665 } catch {
666 return "#ERROR"
667 }
668 var result = Elisp.printed(value)
669 if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) }
670 return result
671 }
672
673 /// `org-lookup-first`, `org-lookup-last` and `org-lookup-all`.
674 static func defineLookups(_ lisp: Elisp) {
675 func matches(_ lisp: Elisp, _ args: [Sexp]) throws -> [Sexp] {
676 try Elisp.arity(args, 3...4, "org-lookup")
677 let keys = try Elisp.elements(args[1])
678 let values = Elisp.isNil(args[2]) ? keys : try Elisp.elements(args[2])
679 let predicate = args.count > 3 && !Elisp.isNil(args[3]) ? args[3] : .symbol("equal")
680 var found: [Sexp] = []
681 for (i, key) in keys.enumerated() where !Elisp.isNil(try lisp.call(predicate, [args[0], key])) {
682 found.append(i < values.count ? values[i] : .nil)
683 }
684 return found
685 }
686 lisp.define("org-lookup-first") { lisp, args in try matches(lisp, args).first ?? .nil }
687 lisp.define("org-lookup-last") { lisp, args in try matches(lisp, args).last ?? .nil }
688 lisp.define("org-lookup-all") { lisp, args in
689 let found = try matches(lisp, args)
690 return found.isEmpty ? .nil : .list(found)
691 }
692 }
693
694 /// Timestamps in a formula as Calc reads them: `<YYYY-MM-DD Www>`, with ` HH:MM` when
695 /// the stamp has a time, as org formats them for Calc.
696 static func normalizeTimestamps(_ form: String) -> String {
697 let regex = try! NSRegularExpression(pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>")
698 var out = form
699 var start = 0
700 while let m = regex.firstMatch(in: out, range: NSRange(location: start, length: (out as NSString).length - start)) {
701 let ns = out as NSString
702 let stamp = ns.substring(with: m.range(at: 1))
703 let parts = stamp.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})/)!
704 let day = Days.absolute(year: Int(parts.1)!, month: Int(parts.2)!, day: Int(parts.3)!)
705 let date = Days.date(day)
706 var text = String(format: "<%04d-%02d-%02d %@", date.year, date.month, date.day, Calc.weekdays[Days.weekday(day)])
707 if let time = stamp.firstMatch(of: /([0-9]{1,2}):([0-9]{2})/) {
708 text += String(format: " %02d:%02d", Int(time.1)!, Int(time.2)!)
709 }
710 text += ">"
711 out = ns.replacingCharacters(in: m.range, with: text)
712 start = m.range.location + (text as NSString).length
713 }
714 return out
715 }
716
717 /// `string-to-number`.
718 static func stringToNumber(_ s: String) -> Double {
719 guard let r = s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return 0 }
720 return Double(s[r]) ?? 0
721 }
722
723 /// `org-table-justify-field-maybe` while the table needs realigning: the field becomes
724 /// ` NEW |`.
725 func tableSetField(_ value: String) {
726 let pos = point
727 guard tableCurrentColumn() > 0 else { return }
728 skipBackwardNot([124])
729 let start = point
730 var end = point
731 while let c = character(at: end), c != 124, c != 10 { end += 1 }
732 let closed = character(at: end) == 124
733 replaceRange(start, closed ? end + 1 : end, with: " \(value) |")
734 point = min(pos, length)
735 }
736
737 func replaceRange(_ start: Int, _ end: Int, with text: String) {
738 let saved = point
739 deleteRegion(start, end)
740 point = start
741 insert(text)
742 point = saved
743 }
744
745 /// `org-table-recalculate`: `all` for every row, otherwise the line at point; `tblfm`
746 /// replaces the stored formulas, as C-c C-c on a `#+TBLFM` line does.
747 func tableRecalculate(all: Bool, tblfm: String? = nil) throws {
748 guard atTable else { throw UserError(message: "Not at a table") }
749 let analysis = try tableAnalyze()
750 let end = tableEnd()
751 guard let line = tblfm ?? firstTblfm(after: end) else { return }
752 let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
753 guard !stored.isEmpty else { return }
754 var columnEquations: [(Int, String)] = []
755 var fieldEquations: [(String, String)] = []
756 for (oldLHS, rawRHS) in stored {
757 let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis)
758 if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
759 let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
760 if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil {
761 columnEquations.append((try Self.integer(String(lhs.dropFirst())), rhs))
762 } else {
763 fieldEquations.append((lhs, rhs))
764 }
765 }
766 // `org-table-expand-lhs-ranges`.
767 var fields: [(row: Int, column: Int, rhs: String)] = []
768 for (lhs, rhs) in fieldEquations {
769 if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) {
770 fields.append((try Self.integer(String(m.1)), try Self.integer(String(m.2)), rhs))
771 } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil {
772 guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else {
773 throw UserError(message: "Unknown field: \(lhs)")
774 }
775 fields.append((row, location.column, rhs))
776 } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil {
777 // `org-table-goto-field` knows only absolute fields and names.
778 throw UserError(message: "Unknown field: \(lhs)")
779 } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
780 let row = try Self.integer(String(m.1))
781 for c in 1...analysis.ncol { fields.append((row, c, rhs)) }
782 } else {
783 let corners = try rangeCorners(lhs, analysis: analysis)
784 guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
785 throw Calc.Unsupported("formula range")
786 }
787 for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs)) } }
788 }
789 }
790 let savedLine = lineStart(point)
791 let savedColumn = tableCurrentColumn()
792 let lineMarker = marker(savedLine)
793 defer { release(lineMarker) }
794
795 let endMarker = marker(end)
796 defer { release(endMarker) }
797 var beg: Int
798 var lineRegexp = "^[ \\t]*\\|[^-]"
799 if all, analysis.marked {
800 beg = analysis.begin
801 lineRegexp = "^[ \\t]*\\| *[#*] *(\\||$)"
802 } else if all {
803 beg = analysis.begin
804 point = beg
805 if searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) != nil,
806 searchForward("^[ \\t]*\\|-", bound: end, caseInsensitive: false) != nil,
807 let body = searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
808 beg = body[0]!.lowerBound
809 }
810 } else {
811 beg = lineStart(point)
812 endMarker.position = min(length, lineEnd(point) + 1)
813 }
814
815 let currentLine = savedLine - 0
816 var seen: Set<String> = []
817 var untouchable: Set<String> = []
818 for field in fields {
819 let reference = "@\(field.row)$\(field.column)"
820 guard seen.insert(reference).inserted else { throw UserError(message: "Several field/range formulas try to set \(reference)") }
821 guard field.row < analysis.dlines.count else { throw UserError(message: "Invalid row number in \(reference)") }
822 let lineStartOffset = saveExcursion { () -> Int in
823 gotoTableLine(analysis.dlines[field.row], analysis)
824 return lineStart(point)
825 }
826 if all || lineStartOffset == currentLine { untouchable.insert(reference) }
827 }
828
829 point = beg
830 let rowMarker = marker(beg)
831 defer { release(rowMarker) }
832 while let match = searchForward(lineRegexp, bound: endMarker.position, caseInsensitive: false) {
833 _ = match
834 let rowStart = lineStart(point)
835 rowMarker.position = rowStart
836 let first = saveExcursion { () -> String in
837 point = rowStart
838 return tableField(1)
839 }
840 if first.range(of: "^ *[_^!$/] *$", options: .regularExpression) == nil {
841 let dline = saveExcursion { () -> Int in
842 point = rowStart
843 return tableCurrentDataLine()
844 }
845 for (column, rhs) in columnEquations {
846 point = rowMarker.position
847 tableGotoColumn(column, force: true)
848 if untouchable.contains("@\(dline)$\(column)") { continue }
849 try tableEvalFormula(rhs, analysis: analysis)
850 }
851 }
852 point = rowMarker.position
853 if forwardLine(1) != 0 || point >= endMarker.position { break }
854 }
855 for field in fields {
856 gotoTableLine(analysis.dlines[field.row], analysis)
857 let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
858 if field.column > count { throw UserError(message: "Missing columns in the table. Aborting") }
859 tableGotoColumn(field.column)
860 try tableEvalFormula(field.rhs, analysis: analysis)
861 }
862 tableAlign()
863 point = lineMarker.position
864 tableGotoColumn(savedColumn)
865 }
866
867 /// `org-table-get-range` with `corners-only`.
868 func rangeCorners(_ desc: String, analysis: TableAnalysis) throws -> (r1: Int, c1: Int, r2: Int, c2: Int) {
869 let ns = desc as NSString
870 guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
871 throw UserError(message: "Invalid table range specifier `\(desc)'")
872 }
873 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
874 let thisline = 0
875 func row(_ r: String?) throws -> Int {
876 guard let r, !r.isEmpty else { return thisline }
877 return try Self.descriptorLine(r, thisline, analysis: analysis)
878 }
879 func column(_ c: String?) -> Int {
880 guard let c, let n = Int(c.dropFirst()), n != 0 else { return 1 }
881 return n + (c.dropFirst().first == "-" || c.dropFirst().first == "+" ? 1 : 0)
882 }
883 let r1 = try row(group(1))
884 let r2 = try row(group(4))
885 let c1 = column(group(2))
886 let c2 = column(group(5))
887 return (min(r1, r2), min(c1, c2), max(r1, r2), max(c1, c2))
888 }
889
890 /// `org-table-line-to-dline`.
891 static func lineToDline(_ line: Int, _ analysis: TableAnalysis, above: Bool = false) -> Int? {
892 let dlines = analysis.dlines
893 var low = 1
894 var high = dlines.count - 1
895 if dlines[low] > line || dlines[high] < line { return nil }
896 if line == dlines[high] { return high }
897 while high - low > 1 {
898 let mean = (high + low) / 2
899 if dlines[mean] == line { return mean }
900 if dlines[mean] > line { high = mean } else { low = mean }
901 }
902 if line == dlines[high] { return high }
903 if line == dlines[low] { return low }
904 return above ? low : high
905 }
906}