Sources/OrgCore/Compute/TableFormulas.swift

7f4768ef8f7de8b64da04e67a271c08d6645fef3
orgstar/Sources/OrgCore/Compute/TableFormulas.swift history · blame · raw

1230 lines · 65694 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 "F": modes.preferFractions = true
 541                case "D": modes.degrees = true
 542                case "R": modes.degrees = false
 543                default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))")
 544                }
 545                flags = ns.replacingCharacters(in: m.range, with: "")
 546            }
 547            if flags.contains(where: { !$0.isWhitespace }) { fmt = flags }
 548        }
 549        if !substituted { formula = try Self.handleFirstLast(try substituteNames(formula, analysis: analysis), analysis: analysis) }
 550        var fields = Self.splitFields(substring(lineStart(point), lineEnd(point)).trimmingCharacters(in: .whitespaces), separator: " *\\| *")
 551        if duration != nil { fields = try fields.map(Self.timeStringToSeconds) }
 552        if mode.numbers { fields = fields.map { $0.contains(where: { !$0.isWhitespace }) ? Self.numberText($0) : $0 } }
 553        if formula.count > 2, formula.hasPrefix("'(") { mode.lisp = literal ? .literal : .lisp }
 554        func reference(_ value: TableRangeValue) throws -> String {
 555            guard duration != nil else { return try Self.makeReference(value, mode) }
 556            switch value {
 557            case .field(let s): return try Self.makeReference(.field(try Self.timeStringToSeconds(s)), mode)
 558            case .list(let items): return try Self.makeReference(.list(try items.map(Self.timeStringToSeconds)), mode)
 559            }
 560        }
 561        let n0 = tableCurrentColumn()
 562        let thisline = try saveExcursion { () -> Int in
 563            let here = lineStart(point)
 564            point = analysis.begin
 565            var count = 0
 566            while point < here {
 567                if forwardLine(1) != 0 { throw Calc.Unsupported("table position") }
 568                count += 1
 569            }
 570            return count
 571        }
 572        var form = formula
 573        form = form.replacingOccurrences(of: "@#", with: String(tableCurrentDataLine()))
 574        form = form.replacingOccurrences(of: "$#", with: String(n0))
 575        // `org-table-remote-reference-indirection`: `remote($1, …)` names the table in a field.
 576        let indirect = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([@$][^ \\t,]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
 577        var start = 0
 578        while let m = indirect.firstMatch(in: form, range: NSRange(location: start, length: (form as NSString).length - start)) {
 579            let ns = form as NSString
 580            var eq = try Self.handleFirstLast(ns.substring(with: m.range(at: 1)), analysis: analysis)
 581            if eq.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil { eq = "@0" + eq }
 582            guard case .field(let name) = try tableRange(eq, thisline: thisline, col: n0, analysis: analysis) else {
 583                throw Calc.Unsupported("remote table name from a range")
 584            }
 585            form = ns.replacingCharacters(in: m.range(at: 1), with: name)
 586            start = m.range(at: 1).location + (name as NSString).length
 587        }
 588        let remote = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([^,)]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
 589        while let m = remote.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
 590            let ns = form as NSString
 591            let name = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)
 592            let value = try remoteRange(name, ns.substring(with: m.range(at: 2)))
 593            form = ns.replacingCharacters(in: m.range, with: try reference(value))
 594        }
 595        let range = try! NSRegularExpression(pattern: Self.rangePattern)
 596        while let m = range.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)), m.range.length > 1 {
 597            let ns = form as NSString
 598            let replacement = try reference(try tableRange(ns.substring(with: m.range), thisline: thisline, col: n0, analysis: analysis))
 599            if replacement.contains(form) { throw UserError(message: "Spreadsheet error: invalid reference \"\(form)\"") }
 600            form = ns.replacingCharacters(in: m.range, with: replacement)
 601        }
 602        let rowRange = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)\\.\\.\\$(([-+])?[0-9]+)")
 603        while let m = rowRange.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
 604            let ns = form as NSString
 605            let a = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
 606            let b = try Self.integer(ns.substring(with: m.range(at: 3))) + (m.range(at: 4).location != NSNotFound ? n0 : 0)
 607            guard a >= 1, b <= fields.count, a - 1 <= b else { throw Calc.Unsupported("range outside row") }
 608            form = ns.replacingCharacters(in: m.range, with: try Self.makeReference(.list(Array(fields[(a - 1)..<b])), mode))
 609        }
 610        let single = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)")
 611        while let m = single.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
 612            let ns = form as NSString
 613            let n = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
 614            let index = (n == 0 ? n0 : max(n, 1)) - 1
 615            guard index < fields.count else { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
 616            let replacement = try Self.makeReference(.field(fields[index]), mode)
 617            if replacement.contains(formula) { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
 618            form = ns.replacingCharacters(in: m.range, with: replacement)
 619        }
 620
 621        var result: String
 622        if mode.lisp != .none {
 623            result = try evalLisp(form, duration: duration)
 624        } else {
 625            form = form.replacingOccurrences(of: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)\\]", with: "<$1>", options: .regularExpression)
 626            form = Self.normalizeTimestamps(form)
 627            if duration != nil, form.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil {
 628                result = form
 629            } else {
 630                do {
 631                    result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
 632                } catch is Calc.Failure {
 633                    (result, fmt) = ("#ERROR", nil)
 634                }
 635            }
 636            if let duration, !result.isEmpty, result != "#ERROR" {
 637                let seconds = result.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil ? try Self.timeStringToSeconds(result) : result
 638                result = try Self.secondsToString(Elisp.stringToNumber(seconds), duration)
 639            }
 640        }
 641        if let fmt {
 642            do {
 643                result = try Elisp.format([.string(fmt), Elisp.stringToNumber(result)])
 644            } catch let error as Elisp.Signal {
 645                throw UserError(message: error.message)
 646            }
 647        } else {
 648            result = result.replacingOccurrences(of: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>", with: "[$1]", options: .regularExpression)
 649        }
 650        tableSetField(result)
 651    }
 652
 653    /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`.
 654    func evalLisp(_ form: String, duration: DurationFormat?) throws -> String {
 655        let lisp = Elisp()
 656        Self.defineLookups(lisp)
 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        var result = Elisp.printed(value)
 666        if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) }
 667        return result
 668    }
 669
 670    /// `org-lookup-first`, `org-lookup-last` and `org-lookup-all`.
 671    static func defineLookups(_ lisp: Elisp) {
 672        func matches(_ lisp: Elisp, _ args: [Sexp]) throws -> [Sexp] {
 673            try Elisp.arity(args, 3...4, "org-lookup")
 674            let keys = try Elisp.elements(args[1])
 675            let values = Elisp.isNil(args[2]) ? keys : try Elisp.elements(args[2])
 676            let predicate = args.count > 3 && !Elisp.isNil(args[3]) ? args[3] : .symbol("equal")
 677            var found: [Sexp] = []
 678            for (i, key) in keys.enumerated() where !Elisp.isNil(try lisp.call(predicate, [args[0], key])) {
 679                found.append(i < values.count ? values[i] : .nil)
 680            }
 681            return found
 682        }
 683        lisp.define("org-lookup-first") { lisp, args in try matches(lisp, args).first ?? .nil }
 684        lisp.define("org-lookup-last") { lisp, args in try matches(lisp, args).last ?? .nil }
 685        lisp.define("org-lookup-all") { lisp, args in
 686            let found = try matches(lisp, args)
 687            return found.isEmpty ? .nil : .list(found)
 688        }
 689    }
 690
 691    /// Timestamps in a formula as Calc reads them: `<YYYY-MM-DD Www>`, with ` HH:MM` when
 692    /// the stamp has a time, as org formats them for Calc.
 693    static func normalizeTimestamps(_ form: String) -> String {
 694        let regex = try! NSRegularExpression(pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>")
 695        var out = form
 696        var start = 0
 697        while let m = regex.firstMatch(in: out, range: NSRange(location: start, length: (out as NSString).length - start)) {
 698            let ns = out as NSString
 699            let stamp = ns.substring(with: m.range(at: 1))
 700            let parts = stamp.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})/)!
 701            let day = Days.absolute(year: Int(parts.1)!, month: Int(parts.2)!, day: Int(parts.3)!)
 702            let date = Days.date(day)
 703            var text = String(format: "<%04d-%02d-%02d %@", date.year, date.month, date.day, Calc.weekdays[Days.weekday(day)])
 704            if let time = stamp.firstMatch(of: /([0-9]{1,2}):([0-9]{2})/) {
 705                text += String(format: " %02d:%02d", Int(time.1)!, Int(time.2)!)
 706            }
 707            text += ">"
 708            out = ns.replacingCharacters(in: m.range, with: text)
 709            start = m.range.location + (text as NSString).length
 710        }
 711        return out
 712    }
 713
 714    /// `string-to-number`.
 715    static func stringToNumber(_ s: String) -> Double {
 716        guard let r = s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return 0 }
 717        return Double(s[r]) ?? 0
 718    }
 719
 720    /// `org-table-justify-field-maybe` while the table needs realigning: the field becomes
 721    /// ` NEW |`.
 722    func tableSetField(_ value: String) {
 723        let pos = point
 724        guard tableCurrentColumn() > 0 else { return }
 725        skipBackwardNot([124])
 726        let start = point
 727        var end = point
 728        while let c = character(at: end), c != 124, c != 10 { end += 1 }
 729        let closed = character(at: end) == 124
 730        replaceRange(start, closed ? end + 1 : end, with: " \(value) |")
 731        point = min(pos, length)
 732    }
 733
 734    func replaceRange(_ start: Int, _ end: Int, with text: String) {
 735        let saved = point
 736        deleteRegion(start, end)
 737        point = start
 738        insert(text)
 739        point = saved
 740    }
 741
 742    /// `org-table-recalculate`: `all` for every row, otherwise the line at point; `tblfm`
 743    /// replaces the stored formulas, as C-c C-c on a `#+TBLFM` line does.
 744    func tableRecalculate(all: Bool, tblfm: String? = nil) throws {
 745        guard atTable else { throw UserError(message: "Not at a table") }
 746        let analysis = try tableAnalyze()
 747        let end = tableEnd()
 748        guard let line = tblfm ?? firstTblfm(after: end) else { return }
 749        let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
 750        guard !stored.isEmpty else { return }
 751        var columnEquations: [(Int, String)] = []
 752        var fieldEquations: [(String, String)] = []
 753        for (oldLHS, rawRHS) in stored {
 754            let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis)
 755            if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
 756            let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
 757            if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil {
 758                columnEquations.append((try Self.integer(String(lhs.dropFirst())), rhs))
 759            } else {
 760                fieldEquations.append((lhs, rhs))
 761            }
 762        }
 763        // `org-table-expand-lhs-ranges`.
 764        var fields: [(row: Int, column: Int, rhs: String)] = []
 765        for (lhs, rhs) in fieldEquations {
 766            if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) {
 767                fields.append((try Self.integer(String(m.1)), try Self.integer(String(m.2)), rhs))
 768            } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil {
 769                guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else {
 770                    throw UserError(message: "Unknown field: \(lhs)")
 771                }
 772                fields.append((row, location.column, rhs))
 773            } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil {
 774                // `org-table-goto-field` knows only absolute fields and names.
 775                throw UserError(message: "Unknown field: \(lhs)")
 776            } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
 777                let row = try Self.integer(String(m.1))
 778                for c in 1...analysis.ncol { fields.append((row, c, rhs)) }
 779            } else {
 780                let corners = try rangeCorners(lhs, analysis: analysis)
 781                guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
 782                    throw Calc.Unsupported("formula range")
 783                }
 784                for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs)) } }
 785            }
 786        }
 787        let savedLine = lineStart(point)
 788        let savedColumn = tableCurrentColumn()
 789        let lineMarker = marker(savedLine)
 790        defer { release(lineMarker) }
 791
 792        let endMarker = marker(end)
 793        defer { release(endMarker) }
 794        var beg: Int
 795        var lineRegexp = "^[ \\t]*\\|[^-]"
 796        if all, analysis.marked {
 797            beg = analysis.begin
 798            lineRegexp = "^[ \\t]*\\| *[#*] *(\\||$)"
 799        } else if all {
 800            beg = analysis.begin
 801            point = beg
 802            if searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) != nil,
 803               searchForward("^[ \\t]*\\|-", bound: end, caseInsensitive: false) != nil,
 804               let body = searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
 805                beg = body[0]!.lowerBound
 806            }
 807        } else {
 808            beg = lineStart(point)
 809            endMarker.position = min(length, lineEnd(point) + 1)
 810        }
 811
 812        let currentLine = savedLine - 0
 813        var seen: Set<String> = []
 814        var untouchable: Set<String> = []
 815        for field in fields {
 816            let reference = "@\(field.row)$\(field.column)"
 817            guard seen.insert(reference).inserted else { throw UserError(message: "Several field/range formulas try to set \(reference)") }
 818            guard field.row < analysis.dlines.count else { throw UserError(message: "Invalid row number in \(reference)") }
 819            let lineStartOffset = saveExcursion { () -> Int in
 820                gotoTableLine(analysis.dlines[field.row], analysis)
 821                return lineStart(point)
 822            }
 823            if all || lineStartOffset == currentLine { untouchable.insert(reference) }
 824        }
 825
 826        point = beg
 827        let rowMarker = marker(beg)
 828        defer { release(rowMarker) }
 829        while let match = searchForward(lineRegexp, bound: endMarker.position, caseInsensitive: false) {
 830            _ = match
 831            let rowStart = lineStart(point)
 832            rowMarker.position = rowStart
 833            let first = saveExcursion { () -> String in
 834                point = rowStart
 835                return tableField(1)
 836            }
 837            if first.range(of: "^ *[_^!$/] *$", options: .regularExpression) == nil {
 838                let dline = saveExcursion { () -> Int in
 839                    point = rowStart
 840                    return tableCurrentDataLine()
 841                }
 842                for (column, rhs) in columnEquations {
 843                    point = rowMarker.position
 844                    tableGotoColumn(column, force: true)
 845                    if untouchable.contains("@\(dline)$\(column)") { continue }
 846                    try tableEvalFormula(rhs, analysis: analysis)
 847                }
 848            }
 849            point = rowMarker.position
 850            if forwardLine(1) != 0 || point >= endMarker.position { break }
 851        }
 852        for field in fields {
 853            gotoTableLine(analysis.dlines[field.row], analysis)
 854            let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
 855            if field.column > count { throw UserError(message: "Missing columns in the table.  Aborting") }
 856            tableGotoColumn(field.column)
 857            try tableEvalFormula(field.rhs, analysis: analysis)
 858        }
 859        tableAlign()
 860        point = lineMarker.position
 861        tableGotoColumn(savedColumn)
 862    }
 863
 864    /// `org-table-get-range` with `corners-only`.
 865    func rangeCorners(_ desc: String, analysis: TableAnalysis) throws -> (r1: Int, c1: Int, r2: Int, c2: Int) {
 866        let ns = desc as NSString
 867        guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
 868            throw UserError(message: "Invalid table range specifier `\(desc)'")
 869        }
 870        func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
 871        let thisline = 0
 872        func row(_ r: String?) throws -> Int {
 873            guard let r, !r.isEmpty else { return thisline }
 874            return try Self.descriptorLine(r, thisline, analysis: analysis)
 875        }
 876        func column(_ c: String?) -> Int {
 877            guard let c, let n = Int(c.dropFirst()), n != 0 else { return 1 }
 878            return n + (c.dropFirst().first == "-" || c.dropFirst().first == "+" ? 1 : 0)
 879        }
 880        let r1 = try row(group(1))
 881        let r2 = try row(group(4))
 882        let c1 = column(group(2))
 883        let c2 = column(group(5))
 884        return (min(r1, r2), min(c1, c2), max(r1, r2), max(c1, c2))
 885    }
 886
 887    /// `org-table-line-to-dline`.
 888    static func lineToDline(_ line: Int, _ analysis: TableAnalysis, above: Bool = false) -> Int? {
 889        let dlines = analysis.dlines
 890        var low = 1
 891        var high = dlines.count - 1
 892        if dlines[low] > line || dlines[high] < line { return nil }
 893        if line == dlines[high] { return high }
 894        while high - low > 1 {
 895            let mean = (high + low) / 2
 896            if dlines[mean] == line { return mean }
 897            if dlines[mean] > line { high = mean } else { low = mean }
 898        }
 899        if line == dlines[high] { return high }
 900        if line == dlines[low] { return low }
 901        return above ? low : high
 902    }
 903}
 904
 905/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the
 906/// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app
 907/// recalculates them in Emacs.
 908public struct TableRecalculate: OrgCommand {
 909    public let all: Bool
 910    public init(all: Bool) { self.all = all }
 911    public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" }
 912    public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" }
 913
 914    public static let emacsMessage = "needs Emacs: "
 915
 916    public func applies(in context: EditContext) -> Bool {
 917        KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil
 918    }
 919
 920    static func tblfmLine(in context: EditContext) -> String? {
 921        let buffer = EmacsBuffer(context.text, point: context.caret)
 922        let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
 923        guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
 924        return line
 925    }
 926
 927    public func run(in context: EditContext) -> CommandStep {
 928        let step = commitBuffer(context) { buffer in
 929            do {
 930                if let line = Self.tblfmLine(in: context) {
 931                    // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
 932                    // point at the end of the table.
 933                    let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
 934                    let saved = buffer.marker(buffer.point)
 935                    defer { buffer.release(saved) }
 936                    guard let tableEnd = buffer.saveExcursion({ () -> Int? in
 937                        while buffer.forwardLine(-1) == 0 {
 938                            if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
 939                        }
 940                        return nil
 941                    }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
 942                    buffer.point = tableEnd
 943                    try buffer.tableRecalculate(all: true, tblfm: formulas)
 944                    buffer.point = saved.position
 945                } else {
 946                    try buffer.tableRecalculate(all: all)
 947                }
 948            } catch let error as Calc.Unsupported {
 949                throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason)
 950            }
 951        }
 952        guard case .failed(let message) = step, message.hasPrefix(Self.emacsMessage) else { return step }
 953        // Emacs recalculates the table; its text replaces the table here.
 954        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
 955        let onTblfm = Self.tblfmLine(in: context) != nil
 956        if onTblfm {
 957            while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {}
 958        }
 959        let table = buffer.tableBegin()..<buffer.tableEnd()
 960        let tblfm = onTblfm ? Self.tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
 961        let form = onTblfm ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
 962        return .external(.emacsTable(
 963            table: table, point: context.caret, form: form,
 964            reason: String(message.dropFirst(Self.emacsMessage.count)), lisp: tblfm.contains("'(")
 965        ))
 966    }
 967}
 968
 969// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
 970extension EmacsBuffer {
 971    /// `org-table-formula-make-cmp-string`.
 972    static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
 973        var a = lhs
 974        if let arrow = a.firstMatch(of: /^\$([<>])/) {
 975            a = (try? handleFirstLast(a, analysis: analysis)) ?? a
 976            a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))"
 977        }
 978        guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil }
 979        var key = ""
 980        if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) }
 981        if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) }
 982        if let name = m.5 { key += "@@" + name }
 983        return key
 984    }
 985
 986    /// `sort` with `org-table-formula-less-p`.
 987    static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] {
 988        var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = []
 989        // Stable insertion, as `sort` with a partial predicate.
 990        for formula in formulas {
 991            let key = formulaSortKey(formula.lhs, analysis: analysis)
 992            var index = sorted.count
 993            while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 }
 994            sorted.insert((formula, key), at: index)
 995        }
 996        return sorted.map(\.formula)
 997    }
 998
 999    /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`.
1000    func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) {
1001        let sorted = Self.sortFormulas(formulas, analysis: analysis)
1002        saveExcursion {
1003            point = tableEnd()
1004            if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) {
1005                deleteRegion(match[3]!.lowerBound, match[0]!.upperBound)
1006                point = match[3]!.lowerBound
1007            } else {
1008                insert("#+TBLFM:")
1009            }
1010            insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n")
1011        }
1012    }
1013
1014    /// `org-table-get-formula` with EQUATION given: stores it for the current column, or with
1015    /// `named` the current field, and returns it.
1016    func tableGetFormula(_ equation: String, named: Bool, analysis: TableAnalysis) throws -> String {
1017        var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "")
1018        let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())"
1019        let scol = named ? ref : "$\(tableCurrentColumn())"
1020        let old = stored.first { $0.lhs == scol }?.rhs
1021        var eq = old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation
1022        guard eq.contains(where: { !$0.isWhitespace }) else {
1023            stored.removeAll { $0.lhs == scol }
1024            tableStoreFormulas(stored, analysis: analysis)
1025            throw UserError(message: "Formula removed")
1026        }
1027        eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression)
1028        eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression)
1029        var mustSave = false
1030        if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) {
1031            stored.remove(at: index)
1032            mustSave = true
1033        }
1034        if let index = stored.firstIndex(where: { $0.lhs == scol }) {
1035            stored[index].rhs = eq
1036        } else {
1037            stored.insert((scol, eq), at: 0)
1038        }
1039        if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) }
1040        return eq
1041    }
1042
1043    /// `org-table-eval-formula` for the current field with EQUATION, which is stored first.
1044    func tableEvalFormula(equation: String, named: Bool) throws {
1045        try checkInsideDataField()
1046        let analysis = try tableAnalyze()
1047        let formula = try tableGetFormula(equation, named: named, analysis: analysis)
1048        do {
1049            try tableEvalFormula(formula, analysis: analysis, substituted: false)
1050        } catch let error as Calc.Unsupported {
1051            throw UserError(message: "The formula was stored; recalculating it needs Emacs: " + error.reason)
1052        }
1053        tableAlign()
1054    }
1055
1056    /// `org-table-maybe-eval-formula`.
1057    func tableMaybeEvalFormula() throws {
1058        skipBackwardNot([124, 10])
1059        guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return }
1060        let start = point
1061        var end = point
1062        while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 }
1063        point = min(lineEnd(point), start + 1)
1064        let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
1065        guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return }
1066        try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":"))
1067    }
1068}
1069
1070/// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's
1071/// formula, the stored one offered.
1072public struct TableEvalFormula: OrgCommand {
1073    let named: Bool
1074    public init(named: Bool) { self.named = named }
1075    public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" }
1076    public var title: String { named ? "Set Field Formula" : "Set Column Formula" }
1077    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
1078    public func run(in context: EditContext) -> CommandStep {
1079        guard let answer = context.answers["formula"] else {
1080            let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
1081            guard buffer.atTable else { return .failed("Not at a table") }
1082            let column = buffer.tableCurrentColumn()
1083            let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)"
1084            let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs
1085            return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? ""))
1086        }
1087        return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named) }
1088    }
1089}
1090
1091// The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor.
1092extension BlockEdit {
1093    static let formulasKind = "formulas"
1094
1095    /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as
1096    /// org's editor lists them. The range runs from the table (or that line) to the formulas.
1097    public static func formulas(at offset: Int, text: String) -> BlockEdit? {
1098        let buffer = EmacsBuffer(text, point: offset)
1099        let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset))
1100        let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil
1101        guard atTblfm || buffer.atTable else { return nil }
1102        let start: Int
1103        let end: Int
1104        let formulas: [(lhs: String, rhs: String)]
1105        if atTblfm {
1106            start = buffer.lineStart(offset)
1107            end = min(buffer.length, buffer.lineEnd(offset) + 1)
1108            let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " "))
1109            formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? []
1110            guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil }
1111        } else {
1112            start = buffer.tableBegin()
1113            let tableEnd = buffer.tableEnd()
1114            end = buffer.saveExcursion {
1115                buffer.point = tableEnd
1116                return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd
1117            }
1118            formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? []
1119        }
1120        guard let analysis = try? buffer.tableAnalyze() else { return nil }
1121        var content = ""
1122        var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")]
1123        for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) {
1124            let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named"
1125            if let index = titles.firstIndex(where: { $0.type == type }) {
1126                if !content.isEmpty { content += "\n" }
1127                content += titles[index].title
1128                titles.remove(at: index)
1129            }
1130            content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n"
1131        }
1132        let ns = text as NSString
1133        return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind)
1134    }
1135
1136    /// `org-table-fedit-finish`'s reading of the editor's text.
1137    static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] {
1138        let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines)
1139        let ns = content as NSString
1140        var result: [(lhs: String, rhs: String)] = []
1141        for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) {
1142            let lhs = ns.substring(with: m.range(at: 1))
1143            var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
1144            guard !rhs.isEmpty else { continue }
1145            rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
1146            if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") }
1147            result.insert((lhs, rhs), at: 0)
1148        }
1149        return result
1150    }
1151
1152    /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument.
1153    func installFormulas(_ content: String, in context: EditContext) -> CommandStep {
1154        let step = commitBuffer(context) { buffer in
1155            let formulas = try Self.parseFormulas(content)
1156            buffer.point = range.lowerBound
1157            let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in
1158                if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) }
1159                return try buffer.tableAnalyze()
1160            }
1161            buffer.tableStoreFormulas(formulas, analysis: analysis)
1162        }
1163        guard case .commit(let result) = step else { return step }
1164        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection,
1165                                  effects: result.effects + [.message("New formulas installed - press C-u C-c C-c to apply.")]))
1166    }
1167}
1168
1169// `org-table-edit-field` (C-c `): a field's text edited apart, then put back.
1170extension BlockEdit {
1171    static let fieldKind = "field"
1172
1173    /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged.
1174    public static func field(at offset: Int, text: String) -> BlockEdit? {
1175        let buffer = EmacsBuffer(text, point: offset)
1176        guard buffer.insideDataField else { return nil }
1177        let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())"
1178        let field = buffer.saveExcursion { () -> String in
1179            buffer.skipBackwardNot([124, 10])
1180            return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound)
1181        }
1182        let start = buffer.lineStart(offset)
1183        let end = buffer.lineEnd(offset)
1184        return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines),
1185                         language: nil, kind: fieldKind, point: offset, coordinate: coordinate)
1186    }
1187
1188    /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the
1189    /// table is aligned.
1190    func installField(_ content: String, in context: EditContext) -> CommandStep {
1191        var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression)
1192        text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression)
1193        text = text.trimmingCharacters(in: .whitespacesAndNewlines)
1194        return commitBuffer(context) { buffer in
1195            buffer.point = point ?? range.lowerBound
1196            guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") }
1197            buffer.skipBackwardNot([124, 10])
1198            let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound
1199            buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text)
1200            buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1)
1201            buffer.tableAlign()
1202        }
1203    }
1204}
1205
1206extension EmacsBuffer {
1207    /// `org-table-check-inside-data-field` with NOERROR.
1208    var insideDataField: Bool {
1209        atTable && !atTableHline
1210            && !saveExcursion { () -> Bool in
1211                while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 }
1212                return bolp
1213            }
1214            && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil
1215    }
1216}
1217
1218/// C-c `: `org-table-edit-field`, in the block editor.
1219public struct TableEditField: OrgCommand {
1220    public init() {}
1221    public var id: String { "org.table.edit-field" }
1222    public var title: String { "Edit Table Field" }
1223    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
1224    public func run(in context: EditContext) -> CommandStep {
1225        guard let edit = BlockEdit.field(at: context.caret, text: context.text) else {
1226            return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table")
1227        }
1228        return .external(.editBlock(edit))
1229    }
1230}