Sources/OrgCore/Compute/TableFormulas.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgCore/Compute/TableFormulas.swift history · blame · raw

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