Sources/OrgCore/Compute/TableFormulas.swift

02bd211f34ad3cc0aa94ba6eb19d312da340d818
orgstar/Sources/OrgCore/Compute/TableFormulas.swift

1203 lines · 64196 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    /// A number written in a formula, small enough to work with.
 347    static func integer(_ s: String) throws -> Int {
 348        guard let n = Int(s.hasPrefix("+") ? String(s.dropFirst()) : s), (-999_999_999...999_999_999).contains(n) else { throw Calc.Unsupported("number size \(s)") }
 349        return n
 350    }
 351
 352    /// `org-table-time-string-to-seconds`.
 353    static func timeStringToSeconds(_ s: String) throws -> String {
 354        guard !s.isEmpty else { return s }
 355        func seconds(_ sign: Substring, _ parts: [Substring]) throws -> String {
 356            var total = 0
 357            for (i, part) in parts.enumerated() {
 358                let (scaled, o1) = (Int(part) ?? Int.max).multipliedReportingOverflow(by: [3600, 60, 1][i])
 359                let (sum, o2) = total.addingReportingOverflow(scaled)
 360                if o1 || o2 || Int(part) == nil { throw Calc.Unsupported("duration size") }
 361                total = sum
 362            }
 363            return String(sign.isEmpty ? total : -total)
 364        }
 365        if let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+):([0-9]+)/) { return try seconds(m.1, [m.2, m.3, m.4]) }
 366        if s.range(of: timestampBoth, options: .regularExpression) == nil, let m = s.firstMatch(of: /(-?)([0-9]+):([0-9]+)/) {
 367            return try seconds(m.1, [m.2, m.3])
 368        }
 369        return numberText(s)
 370    }
 371
 372    enum DurationFormat { case hms, hhmm, hours }
 373
 374    /// `org-table-time-seconds-to-string`, with `org-table-duration-custom-format` `hours`
 375    /// and zero-padded hours.
 376    static func secondsToString(_ seconds: Sexp, _ format: DurationFormat) throws -> String {
 377        let value = (try? Elisp.number(seconds))?.double ?? 0
 378        let magnitude = abs(value)
 379        guard magnitude.isFinite, magnitude < 1e15 else { throw Calc.Unsupported("duration size") }
 380        let result: String
 381        switch format {
 382        case .hours:
 383            result = String(format: "%.2f", magnitude / 3600)
 384        case .hms, .hhmm:
 385            let total = Int(magnitude.rounded(.down))
 386            let hms = String(format: "%02d:%02d:%02d", total / 3600, total / 60 % 60, total % 60)
 387            result = format == .hhmm ? String(hms.dropLast(3)) : hms
 388        }
 389        return value < 0 ? "-" + result : result
 390    }
 391
 392    /// `org-table-convert-refs-to-rc` for a remote reference: `B3` is `@3$2`.
 393    static func refsToRC(_ s: String) -> String {
 394        let regex = try! NSRegularExpression(pattern: "(?<![A-Za-z0-9_$@])([a-zA-Z]{1,2})([0-9]+)(?![A-Za-z0-9_])")
 395        var out = s
 396        while let m = regex.firstMatch(in: out, range: NSRange(location: 0, length: (out as NSString).length)) {
 397            let ns = out as NSString
 398            let column = ns.substring(with: m.range(at: 1)).uppercased().unicodeScalars.reduce(0) { $0 * 26 + Int($1.value) - 64 }
 399            out = ns.replacingCharacters(in: m.range, with: "@\(ns.substring(with: m.range(at: 2)))$\(column)")
 400        }
 401        return out
 402    }
 403
 404    /// `org-table-get-constant`: a parameter or named field, a `#+CONSTANTS` value, or the
 405    /// entry's property for `PROP_name`.
 406    func tableConstant(_ name: String, analysis: TableAnalysis) -> String {
 407        if let parameter = analysis.parameters.last(where: { $0.name == name }) { return parameter.value }
 408        for m in (settings.setupKeywords + string).matches(of: #/(?mi)^[ \t]*#\+CONSTANTS:(.*)$/#) {
 409            for pair in m.1.split(whereSeparator: \.isWhitespace) {
 410                let parts = pair.split(separator: "=", maxSplits: 1)
 411                if parts.count == 2, parts[0] == name { return String(parts[1]) }
 412            }
 413        }
 414        if name.hasPrefix("PROP_"), let value = inheritedProperty(String(name.dropFirst(5)))?.value { return value }
 415        return "#UNDEFINED_NAME"
 416    }
 417
 418    /// `org-table-formula-substitute-names`: column names become `$N`; parameters, named
 419    /// fields and constants their values, in parentheses outside Lisp formulas.
 420    func substituteNames(_ formula: String, analysis: TableAnalysis) throws -> String {
 421        let parenthesize = !formula.hasPrefix("'")
 422        let duration = formula.range(of: ";.*[Tt].*$", options: .regularExpression) != nil
 423        var new = formula
 424        if !analysis.columnNames.isEmpty {
 425            let names = analysis.columnNames.map { NSRegularExpression.escapedPattern(for: $0.name) }.joined(separator: "|")
 426            let regex = try! NSRegularExpression(pattern: "\\$(\(names))(?![[:alnum:]])")
 427            var start = 0
 428            while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
 429                let ns = new as NSString
 430                let column = analysis.columnNames.first { $0.name == ns.substring(with: m.range(at: 1)) }!.column
 431                new = ns.replacingCharacters(in: m.range, with: "$\(column)")
 432                start = m.range.location + 1
 433            }
 434        }
 435        let regex = try! NSRegularExpression(pattern: "\\$([a-zA-Z][_a-zA-Z0-9]*)|(\\bremote\\([^)]*\\))")
 436        var start = 0
 437        var substitutions = 0
 438        while let m = regex.firstMatch(in: new, range: NSRange(location: start, length: (new as NSString).length - start)) {
 439            let ns = new as NSString
 440            // A constant whose value names itself would go on forever, as it does in Org.
 441            substitutions += 1
 442            if substitutions > 1000 { throw Calc.Unsupported("constants that refer to themselves") }
 443            if m.range(at: 2).location != NSNotFound {
 444                start = NSMaxRange(m.range(at: 2))
 445                continue
 446            }
 447            start = m.range.location + 1
 448            var value = tableConstant(ns.substring(with: m.range(at: 1)), analysis: analysis)
 449            if duration, value.contains(where: { !$0.isWhitespace }) { value = try Self.timeStringToSeconds(value) }
 450            new = ns.replacingCharacters(in: m.range, with: parenthesize ? "(" + value + ")" : value)
 451        }
 452        return new
 453    }
 454
 455    /// `org-table-get-remote-range`: the table after `#+NAME: name` in this file.
 456    func remoteRange(_ name: String, _ form: String) throws -> TableRangeValue {
 457        let ns = string as NSString
 458        let pattern = "^[ \\t]*#\\+(tbl)?name:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
 459        let keyword = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
 460        guard let found = keyword.firstMatch(in: string, range: NSRange(location: 0, length: ns.length)) else {
 461            throw Calc.Unsupported("remote table \(name) by ID")
 462        }
 463        let after = min(ns.length, found.range.location + 1)
 464        let next = try! NSRegularExpression(pattern: "^(\\*+ )|^[ \\t]*\\|", options: .anchorsMatchLines)
 465        guard let m = next.firstMatch(in: string, range: NSRange(location: after, length: ns.length - after)),
 466              m.range(at: 1).location == NSNotFound else {
 467            throw UserError(message: "Cannot find a table at NAME or ID \(name)")
 468        }
 469        let remote = EmacsBuffer(string, point: m.range.location, settings: settings, options: options)
 470        let analysis = try remote.tableAnalyze()
 471        let resolved = try remote.substituteNames(try Self.handleFirstLast(Self.refsToRC(form), analysis: analysis), analysis: analysis)
 472        let range = try! NSRegularExpression(pattern: Self.rangePattern)
 473        let rns = resolved as NSString
 474        if let r = range.firstMatch(in: resolved, range: NSRange(location: 0, length: rns.length)), r.range.length > 1 {
 475            return try remote.tableRange(rns.substring(with: r.range), thisline: 0, col: 1, analysis: analysis)
 476        }
 477        return .field(resolved)
 478    }
 479
 480    /// `org-table-eval-formula` with the equation given, at point. `substituted` when names
 481    /// and constants were already replaced, as `org-table-recalculate` does.
 482    func tableEvalFormula(_ formula: String, analysis: TableAnalysis, substituted: Bool = true) throws {
 483        var formula = formula
 484        var modes = Calc.Modes()
 485        var mode = ReferenceMode()
 486        var duration: DurationFormat?
 487        var literal = false
 488        var fmt: String?
 489        if let semicolon = formula.lastIndex(of: ";") {
 490            var flags = (analysis.parameters.last { $0.name == "%" }?.value ?? "") + formula[formula.index(after: semicolon)...]
 491            formula = String(formula[..<semicolon])
 492            let numeric = try! NSRegularExpression(pattern: "([pnfse])(-?[0-9]+)")
 493            while let m = numeric.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
 494                let ns = flags as NSString
 495                let n = try Self.integer(ns.substring(with: m.range(at: 2)))
 496                switch ns.substring(with: m.range(at: 1)) {
 497                case "p": modes.precision = n
 498                case "n": modes.format = .float(n)
 499                case "f": modes.format = .fix(n)
 500                case "s": modes.format = .sci(n)
 501                default: modes.format = .eng(n)
 502                }
 503                flags = ns.replacingCharacters(in: m.range, with: "")
 504            }
 505            let letters = try! NSRegularExpression(pattern: "[tTUNLEDRFSu]")
 506            while let m = letters.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
 507                let ns = flags as NSString
 508                switch ns.substring(with: m.range) {
 509                case "t": (duration, mode.numbers) = (.hours, true)
 510                case "T": (duration, mode.numbers) = (.hms, true)
 511                case "U": (duration, mode.numbers) = (.hhmm, true)
 512                case "N": mode.numbers = true
 513                case "L": literal = true
 514                case "E": mode.keepEmpty = true
 515                case "D": modes.degrees = true
 516                case "R": modes.degrees = false
 517                default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))")
 518                }
 519                flags = ns.replacingCharacters(in: m.range, with: "")
 520            }
 521            if flags.contains(where: { !$0.isWhitespace }) { fmt = flags }
 522        }
 523        if !substituted { formula = try Self.handleFirstLast(try substituteNames(formula, analysis: analysis), analysis: analysis) }
 524        var fields = Self.splitFields(substring(lineStart(point), lineEnd(point)).trimmingCharacters(in: .whitespaces), separator: " *\\| *")
 525        if duration != nil { fields = try fields.map(Self.timeStringToSeconds) }
 526        if mode.numbers { fields = fields.map { $0.contains(where: { !$0.isWhitespace }) ? Self.numberText($0) : $0 } }
 527        if formula.count > 2, formula.hasPrefix("'(") { mode.lisp = literal ? .literal : .lisp }
 528        func reference(_ value: TableRangeValue) throws -> String {
 529            guard duration != nil else { return try Self.makeReference(value, mode) }
 530            switch value {
 531            case .field(let s): return try Self.makeReference(.field(try Self.timeStringToSeconds(s)), mode)
 532            case .list(let items): return try Self.makeReference(.list(try items.map(Self.timeStringToSeconds)), mode)
 533            }
 534        }
 535        let n0 = tableCurrentColumn()
 536        let thisline = try saveExcursion { () -> Int in
 537            let here = lineStart(point)
 538            point = analysis.begin
 539            var count = 0
 540            while point < here {
 541                if forwardLine(1) != 0 { throw Calc.Unsupported("table position") }
 542                count += 1
 543            }
 544            return count
 545        }
 546        var form = formula
 547        form = form.replacingOccurrences(of: "@#", with: String(tableCurrentDataLine()))
 548        form = form.replacingOccurrences(of: "$#", with: String(n0))
 549        // `org-table-remote-reference-indirection`: `remote($1, …)` names the table in a field.
 550        let indirect = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([@$][^ \\t,]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
 551        var start = 0
 552        while let m = indirect.firstMatch(in: form, range: NSRange(location: start, length: (form as NSString).length - start)) {
 553            let ns = form as NSString
 554            var eq = try Self.handleFirstLast(ns.substring(with: m.range(at: 1)), analysis: analysis)
 555            if eq.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil { eq = "@0" + eq }
 556            guard case .field(let name) = try tableRange(eq, thisline: thisline, col: n0, analysis: analysis) else {
 557                throw Calc.Unsupported("remote table name from a range")
 558            }
 559            form = ns.replacingCharacters(in: m.range(at: 1), with: name)
 560            start = m.range(at: 1).location + (name as NSString).length
 561        }
 562        let remote = try! NSRegularExpression(pattern: "\\bremote\\([ \\t]*([^,)]+)[ \\t]*,[ \\t]*([^\\n)]+)\\)")
 563        while let m = remote.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
 564            let ns = form as NSString
 565            let name = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)
 566            let value = try remoteRange(name, ns.substring(with: m.range(at: 2)))
 567            form = ns.replacingCharacters(in: m.range, with: try reference(value))
 568        }
 569        let range = try! NSRegularExpression(pattern: Self.rangePattern)
 570        while let m = range.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)), m.range.length > 1 {
 571            let ns = form as NSString
 572            let replacement = try reference(try tableRange(ns.substring(with: m.range), thisline: thisline, col: n0, analysis: analysis))
 573            if replacement.contains(form) { throw UserError(message: "Spreadsheet error: invalid reference \"\(form)\"") }
 574            form = ns.replacingCharacters(in: m.range, with: replacement)
 575        }
 576        let rowRange = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)\\.\\.\\$(([-+])?[0-9]+)")
 577        while let m = rowRange.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
 578            let ns = form as NSString
 579            let a = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
 580            let b = try Self.integer(ns.substring(with: m.range(at: 3))) + (m.range(at: 4).location != NSNotFound ? n0 : 0)
 581            guard a >= 1, b <= fields.count, a - 1 <= b else { throw Calc.Unsupported("range outside row") }
 582            form = ns.replacingCharacters(in: m.range, with: try Self.makeReference(.list(Array(fields[(a - 1)..<b])), mode))
 583        }
 584        let single = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)")
 585        while let m = single.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
 586            let ns = form as NSString
 587            let n = try Self.integer(ns.substring(with: m.range(at: 1))) + (m.range(at: 2).location != NSNotFound ? n0 : 0)
 588            let index = (n == 0 ? n0 : max(n, 1)) - 1
 589            guard index < fields.count else { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
 590            let replacement = try Self.makeReference(.field(fields[index]), mode)
 591            if replacement.contains(formula) { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
 592            form = ns.replacingCharacters(in: m.range, with: replacement)
 593        }
 594
 595        var result: String
 596        if mode.lisp != .none {
 597            result = try evalLisp(form, duration: duration)
 598        } else {
 599            form = form.replacingOccurrences(of: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)\\]", with: "<$1>", options: .regularExpression)
 600            form = Self.normalizeTimestamps(form)
 601            if duration != nil, form.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil {
 602                result = form
 603            } else {
 604                do {
 605                    result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
 606                } catch is Calc.Failure {
 607                    (result, fmt) = ("#ERROR", nil)
 608                }
 609            }
 610            if let duration, !result.isEmpty, result != "#ERROR" {
 611                let seconds = result.range(of: "^[0-9]+:[0-9]+(:[0-9]+)?$", options: .regularExpression) != nil ? try Self.timeStringToSeconds(result) : result
 612                result = try Self.secondsToString(Elisp.stringToNumber(seconds), duration)
 613            }
 614        }
 615        if let fmt {
 616            do {
 617                result = try Elisp.format([.string(fmt), Elisp.stringToNumber(result)])
 618            } catch let error as Elisp.Signal {
 619                throw UserError(message: error.message)
 620            }
 621        } else {
 622            result = result.replacingOccurrences(of: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>", with: "[$1]", options: .regularExpression)
 623        }
 624        tableSetField(result)
 625    }
 626
 627    /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`.
 628    func evalLisp(_ form: String, duration: DurationFormat?) throws -> String {
 629        let lisp = Elisp()
 630        Self.defineLookups(lisp)
 631        let value: Sexp
 632        do {
 633            value = try lisp.eval(try lisp.eval(try LispReader.readFirst(form).sexp))
 634        } catch let unsupported as Elisp.Unsupported {
 635            throw Calc.Unsupported("Lisp \(unsupported.what)")
 636        } catch {
 637            return "#ERROR"
 638        }
 639        var result = Elisp.printed(value)
 640        if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) }
 641        return result
 642    }
 643
 644    /// `org-lookup-first`, `org-lookup-last` and `org-lookup-all`.
 645    static func defineLookups(_ lisp: Elisp) {
 646        func matches(_ lisp: Elisp, _ args: [Sexp]) throws -> [Sexp] {
 647            try Elisp.arity(args, 3...4, "org-lookup")
 648            let keys = try Elisp.elements(args[1])
 649            let values = Elisp.isNil(args[2]) ? keys : try Elisp.elements(args[2])
 650            let predicate = args.count > 3 && !Elisp.isNil(args[3]) ? args[3] : .symbol("equal")
 651            var found: [Sexp] = []
 652            for (i, key) in keys.enumerated() where !Elisp.isNil(try lisp.call(predicate, [args[0], key])) {
 653                found.append(i < values.count ? values[i] : .nil)
 654            }
 655            return found
 656        }
 657        lisp.define("org-lookup-first") { lisp, args in try matches(lisp, args).first ?? .nil }
 658        lisp.define("org-lookup-last") { lisp, args in try matches(lisp, args).last ?? .nil }
 659        lisp.define("org-lookup-all") { lisp, args in
 660            let found = try matches(lisp, args)
 661            return found.isEmpty ? .nil : .list(found)
 662        }
 663    }
 664
 665    /// Timestamps in a formula as Calc reads them: `<YYYY-MM-DD Www>`, with ` HH:MM` when
 666    /// the stamp has a time, as org formats them for Calc.
 667    static func normalizeTimestamps(_ form: String) -> String {
 668        let regex = try! NSRegularExpression(pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)>")
 669        var out = form
 670        var start = 0
 671        while let m = regex.firstMatch(in: out, range: NSRange(location: start, length: (out as NSString).length - start)) {
 672            let ns = out as NSString
 673            let stamp = ns.substring(with: m.range(at: 1))
 674            let parts = stamp.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})/)!
 675            let day = Days.absolute(year: Int(parts.1)!, month: Int(parts.2)!, day: Int(parts.3)!)
 676            let date = Days.date(day)
 677            var text = String(format: "<%04d-%02d-%02d %@", date.year, date.month, date.day, Calc.weekdays[Days.weekday(day)])
 678            if let time = stamp.firstMatch(of: /([0-9]{1,2}):([0-9]{2})/) {
 679                text += String(format: " %02d:%02d", Int(time.1)!, Int(time.2)!)
 680            }
 681            text += ">"
 682            out = ns.replacingCharacters(in: m.range, with: text)
 683            start = m.range.location + (text as NSString).length
 684        }
 685        return out
 686    }
 687
 688    /// `string-to-number`.
 689    static func stringToNumber(_ s: String) -> Double {
 690        guard let r = s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return 0 }
 691        return Double(s[r]) ?? 0
 692    }
 693
 694    /// `org-table-justify-field-maybe` while the table needs realigning: the field becomes
 695    /// ` NEW |`.
 696    func tableSetField(_ value: String) {
 697        let pos = point
 698        guard tableCurrentColumn() > 0 else { return }
 699        skipBackwardNot([124])
 700        let start = point
 701        var end = point
 702        while let c = character(at: end), c != 124, c != 10 { end += 1 }
 703        let closed = character(at: end) == 124
 704        replaceRange(start, closed ? end + 1 : end, with: " \(value) |")
 705        point = min(pos, length)
 706    }
 707
 708    func replaceRange(_ start: Int, _ end: Int, with text: String) {
 709        let saved = point
 710        deleteRegion(start, end)
 711        point = start
 712        insert(text)
 713        point = saved
 714    }
 715
 716    /// `org-table-recalculate`: `all` for every row, otherwise the line at point; `tblfm`
 717    /// replaces the stored formulas, as C-c C-c on a `#+TBLFM` line does.
 718    func tableRecalculate(all: Bool, tblfm: String? = nil) throws {
 719        guard atTable else { throw UserError(message: "Not at a table") }
 720        let analysis = try tableAnalyze()
 721        let end = tableEnd()
 722        guard let line = tblfm ?? firstTblfm(after: end) else { return }
 723        let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
 724        guard !stored.isEmpty else { return }
 725        var columnEquations: [(Int, String)] = []
 726        var fieldEquations: [(String, String)] = []
 727        for (oldLHS, rawRHS) in stored {
 728            let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis)
 729            if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
 730            let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
 731            if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil {
 732                columnEquations.append((try Self.integer(String(lhs.dropFirst())), rhs))
 733            } else {
 734                fieldEquations.append((lhs, rhs))
 735            }
 736        }
 737        // `org-table-expand-lhs-ranges`.
 738        var fields: [(row: Int, column: Int, rhs: String)] = []
 739        for (lhs, rhs) in fieldEquations {
 740            if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) {
 741                fields.append((try Self.integer(String(m.1)), try Self.integer(String(m.2)), rhs))
 742            } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil {
 743                guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else {
 744                    throw UserError(message: "Unknown field: \(lhs)")
 745                }
 746                fields.append((row, location.column, rhs))
 747            } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil {
 748                throw Calc.Unsupported("relative field formula")
 749            } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
 750                let row = try Self.integer(String(m.1))
 751                for c in 1...analysis.ncol { fields.append((row, c, rhs)) }
 752            } else {
 753                let corners = try rangeCorners(lhs, analysis: analysis)
 754                guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
 755                    throw Calc.Unsupported("formula range")
 756                }
 757                for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs)) } }
 758            }
 759        }
 760        let savedLine = lineStart(point)
 761        let savedColumn = tableCurrentColumn()
 762        let lineMarker = marker(savedLine)
 763        defer { release(lineMarker) }
 764
 765        let endMarker = marker(end)
 766        defer { release(endMarker) }
 767        var beg: Int
 768        var lineRegexp = "^[ \\t]*\\|[^-]"
 769        if all, analysis.marked {
 770            beg = analysis.begin
 771            lineRegexp = "^[ \\t]*\\| *[#*] *(\\||$)"
 772        } else if all {
 773            beg = analysis.begin
 774            point = beg
 775            if searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) != nil,
 776               searchForward("^[ \\t]*\\|-", bound: end, caseInsensitive: false) != nil,
 777               let body = searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
 778                beg = body[0]!.lowerBound
 779            }
 780        } else {
 781            beg = lineStart(point)
 782            endMarker.position = min(length, lineEnd(point) + 1)
 783        }
 784
 785        let currentLine = savedLine - 0
 786        var seen: Set<String> = []
 787        var untouchable: Set<String> = []
 788        for field in fields {
 789            let reference = "@\(field.row)$\(field.column)"
 790            guard seen.insert(reference).inserted else { throw UserError(message: "Several field/range formulas try to set \(reference)") }
 791            guard field.row < analysis.dlines.count else { throw UserError(message: "Invalid row number in \(reference)") }
 792            let lineStartOffset = saveExcursion { () -> Int in
 793                gotoTableLine(analysis.dlines[field.row], analysis)
 794                return lineStart(point)
 795            }
 796            if all || lineStartOffset == currentLine { untouchable.insert(reference) }
 797        }
 798
 799        point = beg
 800        let rowMarker = marker(beg)
 801        defer { release(rowMarker) }
 802        while let match = searchForward(lineRegexp, bound: endMarker.position, caseInsensitive: false) {
 803            _ = match
 804            let rowStart = lineStart(point)
 805            rowMarker.position = rowStart
 806            let first = saveExcursion { () -> String in
 807                point = rowStart
 808                return tableField(1)
 809            }
 810            if first.range(of: "^ *[_^!$/] *$", options: .regularExpression) == nil {
 811                let dline = saveExcursion { () -> Int in
 812                    point = rowStart
 813                    return tableCurrentDataLine()
 814                }
 815                for (column, rhs) in columnEquations {
 816                    point = rowMarker.position
 817                    tableGotoColumn(column, force: true)
 818                    if untouchable.contains("@\(dline)$\(column)") { continue }
 819                    try tableEvalFormula(rhs, analysis: analysis)
 820                }
 821            }
 822            point = rowMarker.position
 823            if forwardLine(1) != 0 || point >= endMarker.position { break }
 824        }
 825        for field in fields {
 826            gotoTableLine(analysis.dlines[field.row], analysis)
 827            let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
 828            if field.column > count { throw UserError(message: "Missing columns in the table.  Aborting") }
 829            tableGotoColumn(field.column)
 830            try tableEvalFormula(field.rhs, analysis: analysis)
 831        }
 832        tableAlign()
 833        point = lineMarker.position
 834        tableGotoColumn(savedColumn)
 835    }
 836
 837    /// `org-table-get-range` with `corners-only`.
 838    func rangeCorners(_ desc: String, analysis: TableAnalysis) throws -> (r1: Int, c1: Int, r2: Int, c2: Int) {
 839        let ns = desc as NSString
 840        guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
 841            throw UserError(message: "Invalid table range specifier `\(desc)'")
 842        }
 843        func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
 844        let thisline = 0
 845        func row(_ r: String?) throws -> Int {
 846            guard let r, !r.isEmpty else { return thisline }
 847            return try Self.descriptorLine(r, thisline, analysis: analysis)
 848        }
 849        func column(_ c: String?) -> Int {
 850            guard let c, let n = Int(c.dropFirst()), n != 0 else { return 1 }
 851            return n + (c.dropFirst().first == "-" || c.dropFirst().first == "+" ? 1 : 0)
 852        }
 853        let r1 = try row(group(1))
 854        let r2 = try row(group(4))
 855        let c1 = column(group(2))
 856        let c2 = column(group(5))
 857        return (min(r1, r2), min(c1, c2), max(r1, r2), max(c1, c2))
 858    }
 859
 860    /// `org-table-line-to-dline`.
 861    static func lineToDline(_ line: Int, _ analysis: TableAnalysis, above: Bool = false) -> Int? {
 862        let dlines = analysis.dlines
 863        var low = 1
 864        var high = dlines.count - 1
 865        if dlines[low] > line || dlines[high] < line { return nil }
 866        if line == dlines[high] { return high }
 867        while high - low > 1 {
 868            let mean = (high + low) / 2
 869            if dlines[mean] == line { return mean }
 870            if dlines[mean] > line { high = mean } else { low = mean }
 871        }
 872        if line == dlines[high] { return high }
 873        if line == dlines[low] { return low }
 874        return above ? low : high
 875    }
 876}
 877
 878/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the
 879/// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app
 880/// recalculates them in Emacs.
 881public struct TableRecalculate: OrgCommand {
 882    public let all: Bool
 883    public init(all: Bool) { self.all = all }
 884    public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" }
 885    public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" }
 886
 887    public static let emacsMessage = "needs Emacs: "
 888
 889    public func applies(in context: EditContext) -> Bool {
 890        KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil
 891    }
 892
 893    static func tblfmLine(in context: EditContext) -> String? {
 894        let buffer = EmacsBuffer(context.text, point: context.caret)
 895        let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
 896        guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
 897        return line
 898    }
 899
 900    public func run(in context: EditContext) -> CommandStep {
 901        let step = commitBuffer(context) { buffer in
 902            do {
 903                if let line = Self.tblfmLine(in: context) {
 904                    // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
 905                    // point at the end of the table.
 906                    let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
 907                    let saved = buffer.marker(buffer.point)
 908                    defer { buffer.release(saved) }
 909                    guard let tableEnd = buffer.saveExcursion({ () -> Int? in
 910                        while buffer.forwardLine(-1) == 0 {
 911                            if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
 912                        }
 913                        return nil
 914                    }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
 915                    buffer.point = tableEnd
 916                    try buffer.tableRecalculate(all: true, tblfm: formulas)
 917                    buffer.point = saved.position
 918                } else {
 919                    try buffer.tableRecalculate(all: all)
 920                }
 921            } catch let error as Calc.Unsupported {
 922                throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason)
 923            }
 924        }
 925        guard case .failed(let message) = step, message.hasPrefix(Self.emacsMessage) else { return step }
 926        // Emacs recalculates the table; its text replaces the table here.
 927        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
 928        let onTblfm = Self.tblfmLine(in: context) != nil
 929        if onTblfm {
 930            while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {}
 931        }
 932        let table = buffer.tableBegin()..<buffer.tableEnd()
 933        let tblfm = onTblfm ? Self.tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
 934        let form = onTblfm ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
 935        return .external(.emacsTable(
 936            table: table, point: context.caret, form: form,
 937            reason: String(message.dropFirst(Self.emacsMessage.count)), lisp: tblfm.contains("'(")
 938        ))
 939    }
 940}
 941
 942// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
 943extension EmacsBuffer {
 944    /// `org-table-formula-make-cmp-string`.
 945    static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
 946        var a = lhs
 947        if let arrow = a.firstMatch(of: /^\$([<>])/) {
 948            a = (try? handleFirstLast(a, analysis: analysis)) ?? a
 949            a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))"
 950        }
 951        guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil }
 952        var key = ""
 953        if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) }
 954        if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) }
 955        if let name = m.5 { key += "@@" + name }
 956        return key
 957    }
 958
 959    /// `sort` with `org-table-formula-less-p`.
 960    static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] {
 961        var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = []
 962        // Stable insertion, as `sort` with a partial predicate.
 963        for formula in formulas {
 964            let key = formulaSortKey(formula.lhs, analysis: analysis)
 965            var index = sorted.count
 966            while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 }
 967            sorted.insert((formula, key), at: index)
 968        }
 969        return sorted.map(\.formula)
 970    }
 971
 972    /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`.
 973    func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) {
 974        let sorted = Self.sortFormulas(formulas, analysis: analysis)
 975        saveExcursion {
 976            point = tableEnd()
 977            if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) {
 978                deleteRegion(match[3]!.lowerBound, match[0]!.upperBound)
 979                point = match[3]!.lowerBound
 980            } else {
 981                insert("#+TBLFM:")
 982            }
 983            insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n")
 984        }
 985    }
 986
 987    /// `org-table-get-formula` with EQUATION given: stores it for the current column, or with
 988    /// `named` the current field, and returns it.
 989    func tableGetFormula(_ equation: String, named: Bool, analysis: TableAnalysis) throws -> String {
 990        var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "")
 991        let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())"
 992        let scol = named ? ref : "$\(tableCurrentColumn())"
 993        let old = stored.first { $0.lhs == scol }?.rhs
 994        var eq = old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation
 995        guard eq.contains(where: { !$0.isWhitespace }) else {
 996            stored.removeAll { $0.lhs == scol }
 997            tableStoreFormulas(stored, analysis: analysis)
 998            throw UserError(message: "Formula removed")
 999        }
1000        eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression)
1001        eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression)
1002        var mustSave = false
1003        if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) {
1004            stored.remove(at: index)
1005            mustSave = true
1006        }
1007        if let index = stored.firstIndex(where: { $0.lhs == scol }) {
1008            stored[index].rhs = eq
1009        } else {
1010            stored.insert((scol, eq), at: 0)
1011        }
1012        if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) }
1013        return eq
1014    }
1015
1016    /// `org-table-eval-formula` for the current field with EQUATION, which is stored first.
1017    func tableEvalFormula(equation: String, named: Bool) throws {
1018        try checkInsideDataField()
1019        let analysis = try tableAnalyze()
1020        let formula = try tableGetFormula(equation, named: named, analysis: analysis)
1021        do {
1022            try tableEvalFormula(formula, analysis: analysis, substituted: false)
1023        } catch let error as Calc.Unsupported {
1024            throw UserError(message: "The formula was stored; recalculating it needs Emacs: " + error.reason)
1025        }
1026        tableAlign()
1027    }
1028
1029    /// `org-table-maybe-eval-formula`.
1030    func tableMaybeEvalFormula() throws {
1031        skipBackwardNot([124, 10])
1032        guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return }
1033        let start = point
1034        var end = point
1035        while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 }
1036        point = min(lineEnd(point), start + 1)
1037        let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
1038        guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return }
1039        try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":"))
1040    }
1041}
1042
1043/// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's
1044/// formula, the stored one offered.
1045public struct TableEvalFormula: OrgCommand {
1046    let named: Bool
1047    public init(named: Bool) { self.named = named }
1048    public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" }
1049    public var title: String { named ? "Set Field Formula" : "Set Column Formula" }
1050    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
1051    public func run(in context: EditContext) -> CommandStep {
1052        guard let answer = context.answers["formula"] else {
1053            let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
1054            guard buffer.atTable else { return .failed("Not at a table") }
1055            let column = buffer.tableCurrentColumn()
1056            let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)"
1057            let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs
1058            return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? ""))
1059        }
1060        return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named) }
1061    }
1062}
1063
1064// The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor.
1065extension BlockEdit {
1066    static let formulasKind = "formulas"
1067
1068    /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as
1069    /// org's editor lists them. The range runs from the table (or that line) to the formulas.
1070    public static func formulas(at offset: Int, text: String) -> BlockEdit? {
1071        let buffer = EmacsBuffer(text, point: offset)
1072        let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset))
1073        let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil
1074        guard atTblfm || buffer.atTable else { return nil }
1075        let start: Int
1076        let end: Int
1077        let formulas: [(lhs: String, rhs: String)]
1078        if atTblfm {
1079            start = buffer.lineStart(offset)
1080            end = min(buffer.length, buffer.lineEnd(offset) + 1)
1081            let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " "))
1082            formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? []
1083            guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil }
1084        } else {
1085            start = buffer.tableBegin()
1086            let tableEnd = buffer.tableEnd()
1087            end = buffer.saveExcursion {
1088                buffer.point = tableEnd
1089                return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd
1090            }
1091            formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? []
1092        }
1093        guard let analysis = try? buffer.tableAnalyze() else { return nil }
1094        var content = ""
1095        var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")]
1096        for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) {
1097            let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named"
1098            if let index = titles.firstIndex(where: { $0.type == type }) {
1099                if !content.isEmpty { content += "\n" }
1100                content += titles[index].title
1101                titles.remove(at: index)
1102            }
1103            content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n"
1104        }
1105        let ns = text as NSString
1106        return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind)
1107    }
1108
1109    /// `org-table-fedit-finish`'s reading of the editor's text.
1110    static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] {
1111        let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines)
1112        let ns = content as NSString
1113        var result: [(lhs: String, rhs: String)] = []
1114        for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) {
1115            let lhs = ns.substring(with: m.range(at: 1))
1116            var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
1117            guard !rhs.isEmpty else { continue }
1118            rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
1119            if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") }
1120            result.insert((lhs, rhs), at: 0)
1121        }
1122        return result
1123    }
1124
1125    /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument.
1126    func installFormulas(_ content: String, in context: EditContext) -> CommandStep {
1127        let step = commitBuffer(context) { buffer in
1128            let formulas = try Self.parseFormulas(content)
1129            buffer.point = range.lowerBound
1130            let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in
1131                if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) }
1132                return try buffer.tableAnalyze()
1133            }
1134            buffer.tableStoreFormulas(formulas, analysis: analysis)
1135        }
1136        guard case .commit(let result) = step else { return step }
1137        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection,
1138                                  effects: result.effects + [.message("New formulas installed - press C-u C-c C-c to apply.")]))
1139    }
1140}
1141
1142// `org-table-edit-field` (C-c `): a field's text edited apart, then put back.
1143extension BlockEdit {
1144    static let fieldKind = "field"
1145
1146    /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged.
1147    public static func field(at offset: Int, text: String) -> BlockEdit? {
1148        let buffer = EmacsBuffer(text, point: offset)
1149        guard buffer.insideDataField else { return nil }
1150        let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())"
1151        let field = buffer.saveExcursion { () -> String in
1152            buffer.skipBackwardNot([124, 10])
1153            return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound)
1154        }
1155        let start = buffer.lineStart(offset)
1156        let end = buffer.lineEnd(offset)
1157        return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines),
1158                         language: nil, kind: fieldKind, point: offset, coordinate: coordinate)
1159    }
1160
1161    /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the
1162    /// table is aligned.
1163    func installField(_ content: String, in context: EditContext) -> CommandStep {
1164        var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression)
1165        text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression)
1166        text = text.trimmingCharacters(in: .whitespacesAndNewlines)
1167        return commitBuffer(context) { buffer in
1168            buffer.point = point ?? range.lowerBound
1169            guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") }
1170            buffer.skipBackwardNot([124, 10])
1171            let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound
1172            buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text)
1173            buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1)
1174            buffer.tableAlign()
1175        }
1176    }
1177}
1178
1179extension EmacsBuffer {
1180    /// `org-table-check-inside-data-field` with NOERROR.
1181    var insideDataField: Bool {
1182        atTable && !atTableHline
1183            && !saveExcursion { () -> Bool in
1184                while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 }
1185                return bolp
1186            }
1187            && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil
1188    }
1189}
1190
1191/// C-c `: `org-table-edit-field`, in the block editor.
1192public struct TableEditField: OrgCommand {
1193    public init() {}
1194    public var id: String { "org.table.edit-field" }
1195    public var title: String { "Edit Table Field" }
1196    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
1197    public func run(in context: EditContext) -> CommandStep {
1198        guard let edit = BlockEdit.field(at: context.caret, text: context.text) else {
1199            return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table")
1200        }
1201        return .external(.editBlock(edit))
1202    }
1203}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form