Sources/OrgCore/Compute/TableFormulas.swift

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

834 lines · 43070 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 evaluated natively. Column names, constants, named
  5// fields, marked rows, `remote()`, Lisp formulas, durations and Calc features beyond `Calc`
  6// 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    }
 17
 18    static let tblfmPattern = "^[ \\t]*#\\+TBLFM: *(.*)"
 19    static let rangePattern = "@([-+]?I*[-+]?[0-9]*)(\\$[-+]?[0-9]+)?(\\.\\.@?([-+]?I*[-+]?[0-9]*)(\\$[-+]?[0-9]+)?)?"
 20
 21    /// `org-table-analyze`.
 22    func tableAnalyze() throws -> TableAnalysis {
 23        let begin = tableBegin()
 24        let end = tableEnd()
 25        return try saveExcursion {
 26            point = begin
 27            var dlines = [0]
 28            var types: [Bool] = []
 29            var line = 0
 30            while point < end || (point == end && false) {
 31                let content = substring(lineStart(point), lineEnd(point))
 32                guard content.range(of: "^[ \\t]*\\|", options: .regularExpression) != nil else { break }
 33                if content.range(of: "^[ \\t]*\\| *[!$_^] *(\\||$)", options: .regularExpression) != nil {
 34                    throw Calc.Unsupported("named columns, parameters or fields")
 35                }
 36                let isHline = content.range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil
 37                types.append(isHline)
 38                if !isHline { dlines.append(line) }
 39                line += 1
 40                if forwardLine(1) != 0 || point >= end { break }
 41            }
 42            types.append(true)
 43            guard dlines.count > 1 else { throw UserError(message: "No data lines in table") }
 44            point = begin
 45            forwardLine(dlines[1])
 46            let first = substring(lineStart(point), lineEnd(point))
 47            let ncol = Self.splitFields(first, separator: "[ \\t]*\\|[ \\t]*").count
 48            return TableAnalysis(dlines: dlines, types: types, ncol: ncol, begin: begin)
 49        }
 50    }
 51
 52    /// `org-split-string`: leading and trailing separators produce no empty strings.
 53    static func splitFields(_ s: String, separator: String) -> [String] {
 54        let ns = s as NSString
 55        let regex = try! NSRegularExpression(pattern: separator)
 56        let matches = regex.matches(in: s, range: NSRange(location: 0, length: ns.length))
 57        guard !matches.isEmpty else { return [s] }
 58        var results: [String] = []
 59        var i = 0
 60        for (k, m) in matches.enumerated() {
 61            if k == 0, m.range.location == 0 {
 62                i = NSMaxRange(m.range)
 63                continue
 64            }
 65            results.append(ns.substring(with: NSRange(location: i, length: m.range.location - i)))
 66            i = NSMaxRange(m.range)
 67        }
 68        if i != ns.length { results.append(ns.substring(from: i)) }
 69        return results
 70    }
 71
 72    /// `org-table-get-stored-formulas` from the `#+TBLFM` text `line`.
 73    static func storedFormulas(_ line: String) throws -> [(lhs: String, rhs: String)] {
 74        var result: [(String, String)] = []
 75        var seen: Set<String> = []
 76        let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|\\$([_a-zA-Z0-9]+|[<>]+)) *= *(.*[^ \\t])")
 77        for part in splitFields(line, separator: " *:: *") {
 78            let ns = part as NSString
 79            guard let m = regex.firstMatch(in: part, range: NSRange(location: 0, length: ns.length)) else { continue }
 80            let whole = ns.substring(with: m.range(at: 1))
 81            var lhs = whole
 82            if m.range(at: 2).location != NSNotFound,
 83               whole.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) == nil {
 84                lhs = ns.substring(with: m.range(at: 2))
 85            }
 86            guard seen.insert(lhs).inserted else { throw UserError(message: "Double definition `\(lhs)=' in TBLFM line, please fix by hand") }
 87            result.append((lhs, ns.substring(with: m.range(at: 3))))
 88        }
 89        return result
 90    }
 91
 92    /// The first `#+TBLFM` line after the table, blank lines allowed between.
 93    func firstTblfm(after end: Int) -> String? {
 94        saveExcursion {
 95            point = end
 96            while !eobp {
 97                let line = substring(lineStart(point), lineEnd(point))
 98                if line.trimmingCharacters(in: .whitespaces).isEmpty {
 99                    if forwardLine(1) != 0 { return nil }
100                    continue
101                }
102                guard let r = line.range(of: Self.tblfmPattern, options: [.regularExpression, .caseInsensitive]) else { return nil }
103                let text = String(line[r])
104                return String(text[text.index(after: text.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
105            }
106            return nil
107        }
108    }
109
110    /// `org-table-formula-handle-first/last-rc`.
111    static func handleFirstLast(_ s: String, analysis: TableAnalysis) throws -> String {
112        var result = s
113        var start = 0
114        let regex = try! NSRegularExpression(pattern: "([@$])(<+|>+)|(remote\\([^)]+\\))")
115        while let m = regex.firstMatch(in: result, range: NSRange(location: start, length: (result as NSString).length - start)) {
116            let ns = result as NSString
117            if m.range(at: 3).location != NSNotFound {
118                start = NSMaxRange(m.range(at: 3))
119                continue
120            }
121            let kind = ns.substring(with: m.range(at: 1))
122            let nmax = kind == "@" ? analysis.dlines.count - 1 : analysis.ncol
123            let marks = ns.substring(with: m.range(at: 2))
124            let n = marks.first == "<" ? marks.count : nmax - marks.count + 1
125            if n < 1 || n > nmax { throw UserError(message: "Reference \"\(ns.substring(with: m.range))\" in expression \"\(result)\" points outside table") }
126            start = m.range.location
127            result = ns.replacingCharacters(in: m.range, with: kind + String(n))
128        }
129        return result
130    }
131
132    /// `org-table--row-type`.
133    static func rowType(hline: Bool, _ n: Int, _ start: Int, backwards: Bool, relative: Bool, analysis: TableAnalysis, desc: String) throws -> Int {
134        var i = start
135        let l = analysis.types.count
136        for _ in 0..<n {
137            while true {
138                i += backwards ? -1 : 1
139                guard i >= 0, i < l, analysis.types[i] != hline else { break }
140            }
141        }
142        if i < 0 || i >= l { throw UserError(message: "Row descriptor \(desc) leads outside table") }
143        return i == l - 1 ? i - 1 : i
144    }
145
146    /// `org-table--descriptor-line`.
147    static func descriptorLine(_ desc: String, _ cline: Int, analysis: TableAnalysis) throws -> Int {
148        if let n = Int(desc), desc.allSatisfy(\.isNumber) {
149            guard n < analysis.dlines.count else { throw Calc.Unsupported("row out of range") }
150            return analysis.dlines[n]
151        }
152        let ns = desc as NSString
153        let regex = try! NSRegularExpression(pattern: "^(([-+])?(I+))?(([-+])?([0-9]+))?")
154        let m = regex.firstMatch(in: desc, range: NSRange(location: 0, length: ns.length))!
155        func has(_ i: Int) -> Bool { m.range(at: i).location != NSNotFound }
156        if (!has(3) && !has(6)) || (has(3) && has(6) && !has(5)) { throw UserError(message: "Invalid row descriptor `\(desc)'") }
157        var hn = has(3) ? m.range(at: 3).length : nil
158        var hdir = has(2) ? ns.substring(with: m.range(at: 2)) : nil
159        let odir = has(5) ? ns.substring(with: m.range(at: 5)) : nil
160        let on = has(6) ? Int(ns.substring(with: m.range(at: 6))) : nil
161        let rel = has(6) && ((has(1) && !has(3)) || has(5))
162        var cline = cline
163        if hn != nil, hdir == nil {
164            cline = 0
165            hdir = "+"
166            if analysis.types[0] { hn! -= 1 }
167        }
168        if hn == nil, on != nil, odir == nil { throw UserError(message: "Should never happen") }
169        if let hn { cline = try rowType(hline: true, hn, cline, backwards: hdir == "-", relative: false, analysis: analysis, desc: desc) }
170        if let on { cline = try rowType(hline: false, on, cline, backwards: odir == "-", relative: rel, analysis: analysis, desc: desc) }
171        return cline
172    }
173
174    /// `org-table-get-field` on the line at point.
175    func tableField(_ column: Int) -> String {
176        saveExcursion {
177            tableGotoColumn(column)
178            skipBackwardNot([124, 10])
179            if bolp || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { return "" }
180            let start = point
181            while let c = character(at: point), c != 124, c != 10, c != 13 { point += 1 }
182            return substring(start, point)
183        }
184    }
185
186    func isDataLine() -> Bool {
187        looking("^[ \\t]*\\|[^-]", caseInsensitive: false, setsMatch: false) != nil
188            || substring(lineStart(point), lineEnd(point)).range(of: "^[ \\t]*\\|[^-]", options: .regularExpression) != nil
189    }
190
191    func gotoTableLine(_ line: Int, _ analysis: TableAnalysis) {
192        point = analysis.begin
193        forwardLine(line)
194    }
195
196    /// `org-table-get-range`: one field's text, or the fields of a rectangle.
197    func tableRange(_ desc: String, thisline: Int, col: Int, analysis: TableAnalysis) throws -> TableRangeValue {
198        var desc = desc
199        if desc.range(of: "^\\$[0-9]+\\.\\.\\$[0-9]+$", options: .regularExpression) != nil {
200            desc = desc.replacingOccurrences(of: "$", with: "@0$")
201        }
202        let ns = desc as NSString
203        guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
204            throw UserError(message: "Invalid table range specifier `\(desc)'")
205        }
206        func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
207        let isRange = group(3) != nil
208        func row(_ r: String?) throws -> Int {
209            guard let r, r.contains(where: { !$0.isWhitespace }) else { return thisline }
210            return try Self.descriptorLine(r, thisline, analysis: analysis)
211        }
212        func column(_ c: String?) -> Int {
213            guard let c else { return col }
214            let body = String(c.dropFirst())
215            let n = Int(body) ?? 0
216            if n == 0 { return col }
217            return n + (body.first == "-" || body.first == "+" ? col : 0)
218        }
219        let r1 = try row(group(1))
220        let r2 = try row(group(4))
221        let c1 = column(group(2))
222        let c2 = column(group(5))
223        return try saveExcursion {
224            if !isRange || (r1 == r2 && c1 == c2) {
225                gotoTableLine(r1, analysis)
226                while !isDataLine() {
227                    if forwardLine(1) != 0 { throw Calc.Unsupported("reference outside table") }
228                }
229                return .field(tableField(c1).trimmingCharacters(in: .whitespaces))
230            }
231            var firstRow = min(r1, r2)
232            let lastRow = max(r1, r2)
233            let firstColumn = min(c1, c2)
234            let lastColumn = max(c1, c2)
235            gotoTableLine(firstRow, analysis)
236            while !isDataLine() {
237                if forwardLine(1) != 0 { throw Calc.Unsupported("reference outside table") }
238                firstRow += 1
239            }
240            let startLine = lineStart(point)
241            forwardLine(lastRow - firstRow)
242            while !isDataLine() { forwardLine(-1) }
243            let endLine = lineStart(point)
244            var fields: [String] = []
245            point = startLine
246            while point <= endLine {
247                if !atTableHline {
248                    for c in firstColumn...lastColumn { fields.append(tableField(c).trimmingCharacters(in: .whitespaces)) }
249                }
250                if forwardLine(1) != 0 { break }
251            }
252            return .list(fields)
253        }
254    }
255
256    enum TableRangeValue {
257        case field(String)
258        case list([String])
259    }
260
261    static let calcNumber = "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?$"
262
263    /// `org-table-make-reference` for Calc, refusing what isn't a number.
264    static func reference(_ value: TableRangeValue) throws -> String {
265        func number(_ s: String) throws -> String {
266            guard s.range(of: calcNumber, options: .regularExpression) != nil else { throw Calc.Unsupported("non-numeric field \(s)") }
267            return s
268        }
269        switch value {
270        case .field(let s):
271            return s.contains(where: { !$0.isWhitespace }) ? "(" + (try number(s)) + ")" : "(0)"
272        case .list(let items):
273            return "[" + (try items.filter { $0.contains(where: { !$0.isWhitespace }) }.map(number)).joined(separator: ",") + "]"
274        }
275    }
276
277    /// `org-table-eval-formula` with the equation given, at point.
278    func tableEvalFormula(_ formula: String, analysis: TableAnalysis) throws {
279        var formula = formula
280        var modes = Calc.Modes()
281        var fmt: String?
282        if let semicolon = formula.lastIndex(of: ";") {
283            var flags = String(formula[formula.index(after: semicolon)...])
284            formula = String(formula[..<semicolon])
285            let numeric = try! NSRegularExpression(pattern: "([pnfse])(-?[0-9]+)")
286            while let m = numeric.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
287                let ns = flags as NSString
288                let n = Int(ns.substring(with: m.range(at: 2)))!
289                switch ns.substring(with: m.range(at: 1)) {
290                case "p": modes.precision = n
291                case "n": modes.format = .float(n)
292                case "f": modes.format = .fix(n)
293                case "s": modes.format = .sci(n)
294                default: modes.format = .eng(n)
295                }
296                flags = ns.replacingCharacters(in: m.range, with: "")
297            }
298            let letters = try! NSRegularExpression(pattern: "[tTUNLEDRFSu]")
299            while let m = letters.firstMatch(in: flags, range: NSRange(location: 0, length: (flags as NSString).length)) {
300                let ns = flags as NSString
301                switch ns.substring(with: m.range) {
302                case "D": modes.degrees = true
303                case "R": modes.degrees = false
304                default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))")
305                }
306                flags = ns.replacingCharacters(in: m.range, with: "")
307            }
308            if flags.contains(where: { !$0.isWhitespace }) {
309                guard flags.range(of: "^%[-+ #0]*[0-9]*(\\.[0-9]+)?[fgeE]$", options: .regularExpression) != nil else {
310                    throw Calc.Unsupported("format \(flags)")
311                }
312                fmt = flags
313            }
314        }
315        if formula.hasPrefix("'(") { throw Calc.Unsupported("Lisp formula") }
316        formula = substituteConstants(formula)
317        if formula.range(of: "\\$[a-zA-Z_]", options: .regularExpression) != nil || formula.contains("remote(")
318            || formula.range(of: "[<\\[][0-9]{4}-", options: .regularExpression) != nil || formula.contains("&") {
319            throw Calc.Unsupported("names, constants, remote references or dates")
320        }
321        let line = substring(lineStart(point), lineEnd(point)).trimmingCharacters(in: .whitespaces)
322        let fields = Self.splitFields(line, separator: " *\\| *")
323        let n0 = tableCurrentColumn()
324        let thisline = try saveExcursion { () -> Int in
325            let here = lineStart(point)
326            point = analysis.begin
327            var count = 0
328            while point < here {
329                if forwardLine(1) != 0 { throw Calc.Unsupported("table position") }
330                count += 1
331            }
332            return count
333        }
334        var form = formula
335        form = form.replacingOccurrences(of: "@#", with: String(tableCurrentDataLine()))
336        form = form.replacingOccurrences(of: "$#", with: String(n0))
337        let range = try! NSRegularExpression(pattern: Self.rangePattern)
338        while let m = range.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)), m.range.length > 1 {
339            let ns = form as NSString
340            let replacement = try Self.reference(try tableRange(ns.substring(with: m.range), thisline: thisline, col: n0, analysis: analysis))
341            form = ns.replacingCharacters(in: m.range, with: replacement)
342        }
343        let rowRange = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)\\.\\.\\$(([-+])?[0-9]+)")
344        while let m = rowRange.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
345            let ns = form as NSString
346            let a = Int(ns.substring(with: m.range(at: 1)))! + (m.range(at: 2).location != NSNotFound ? n0 : 0)
347            let b = Int(ns.substring(with: m.range(at: 3)))! + (m.range(at: 4).location != NSNotFound ? n0 : 0)
348            guard a >= 1, b <= fields.count, a - 1 <= b else { throw Calc.Unsupported("range outside row") }
349            form = ns.replacingCharacters(in: m.range, with: try Self.reference(.list(Array(fields[(a - 1)..<b]))))
350        }
351        let single = try! NSRegularExpression(pattern: "\\$(([-+])?[0-9]+)")
352        while let m = single.firstMatch(in: form, range: NSRange(location: 0, length: (form as NSString).length)) {
353            let ns = form as NSString
354            let n = Int(ns.substring(with: m.range(at: 1)))! + (m.range(at: 2).location != NSNotFound ? n0 : 0)
355            let index = (n == 0 ? n0 : max(n, 1)) - 1
356            guard index < fields.count else { throw UserError(message: "Invalid field specifier \"\(ns.substring(with: m.range))\"") }
357            form = ns.replacingCharacters(in: m.range, with: try Self.reference(.field(fields[index])))
358        }
359        var result = try Calc.evaluate(form, modes: modes)
360        if let fmt {
361            result = String(format: fmt, Self.stringToNumber(result))
362        }
363        tableSetField(result)
364    }
365
366    /// `org-table-formula-substitute-names` for constants: `$name` from `#+CONSTANTS`, or
367    /// `$PROP_name` from the entry's property, in parentheses; unknown names become
368    /// `#UNDEFINED_NAME`.
369    func substituteConstants(_ formula: String) -> String {
370        guard formula.range(of: "\\$[a-zA-Z]", options: .regularExpression) != nil else { return formula }
371        var constants: [String: String] = [:]
372        for m in string.matches(of: #/(?mi)^[ \t]*#\+CONSTANTS:(.*)$/#) {
373            for pair in m.1.split(whereSeparator: \.isWhitespace) {
374                let parts = pair.split(separator: "=", maxSplits: 1)
375                if parts.count == 2, constants[String(parts[0])] == nil { constants[String(parts[0])] = String(parts[1]) }
376            }
377        }
378        let regex = try! NSRegularExpression(pattern: "\\$([a-zA-Z][_a-zA-Z0-9]*)")
379        var out = formula
380        while let m = regex.firstMatch(in: out, range: NSRange(location: 0, length: (out as NSString).length)) {
381            let ns = out as NSString
382            let name = ns.substring(with: m.range(at: 1))
383            var value = constants[name]
384            if value == nil, name.hasPrefix("PROP_") {
385                value = inheritedProperty(String(name.dropFirst(5)))?.value
386            }
387            out = ns.replacingCharacters(in: m.range, with: "(" + (value ?? "#UNDEFINED_NAME") + ")")
388        }
389        return out
390    }
391
392    /// `string-to-number`.
393    static func stringToNumber(_ s: String) -> Double {
394        guard let r = s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return 0 }
395        return Double(s[r]) ?? 0
396    }
397
398    /// `org-table-justify-field-maybe` while the table needs realigning: the field becomes
399    /// ` NEW |`.
400    func tableSetField(_ value: String) {
401        let pos = point
402        guard tableCurrentColumn() > 0 else { return }
403        skipBackwardNot([124])
404        let start = point
405        var end = point
406        while let c = character(at: end), c != 124, c != 10 { end += 1 }
407        let closed = character(at: end) == 124
408        replaceRange(start, closed ? end + 1 : end, with: " \(value) |")
409        point = min(pos, length)
410    }
411
412    func replaceRange(_ start: Int, _ end: Int, with text: String) {
413        let saved = point
414        deleteRegion(start, end)
415        point = start
416        insert(text)
417        point = saved
418    }
419
420    /// `org-table-recalculate`: `all` for every row, otherwise the line at point; `tblfm`
421    /// replaces the stored formulas, as C-c C-c on a `#+TBLFM` line does.
422    func tableRecalculate(all: Bool, tblfm: String? = nil) throws {
423        guard atTable else { throw UserError(message: "Not at a table") }
424        let analysis = try tableAnalyze()
425        let end = tableEnd()
426        guard let line = tblfm ?? firstTblfm(after: end) else { return }
427        let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
428        guard !stored.isEmpty else { return }
429        var columnEquations: [(Int, String)] = []
430        var fieldEquations: [(String, String)] = []
431        for (oldLHS, rawRHS) in stored {
432            let rhs = try Self.handleFirstLast(rawRHS, analysis: analysis)
433            if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
434            let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
435            if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil {
436                columnEquations.append((Int(lhs.dropFirst())!, rhs))
437            } else {
438                fieldEquations.append((lhs, rhs))
439            }
440        }
441        // `org-table-expand-lhs-ranges`.
442        var fields: [(row: Int, column: Int, rhs: String)] = []
443        for (lhs, rhs) in fieldEquations {
444            if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) {
445                fields.append((Int(m.1)!, Int(m.2)!, rhs))
446            } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil || lhs.range(of: "^[a-zA-Z]", options: .regularExpression) != nil {
447                throw Calc.Unsupported("relative or named field formula")
448            } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
449                for c in 1...analysis.ncol { fields.append((Int(m.1)!, c, rhs)) }
450            } else {
451                let corners = try rangeCorners(lhs, analysis: analysis)
452                guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
453                    throw Calc.Unsupported("formula range")
454                }
455                for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs)) } }
456            }
457        }
458        let savedLine = lineStart(point)
459        let savedColumn = tableCurrentColumn()
460        let lineMarker = marker(savedLine)
461        defer { release(lineMarker) }
462
463        let endMarker = marker(end)
464        defer { release(endMarker) }
465        var beg: Int
466        if all {
467            beg = analysis.begin
468            point = beg
469            if searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) != nil,
470               searchForward("^[ \\t]*\\|-", bound: end, caseInsensitive: false) != nil,
471               let body = searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
472                beg = body[0]!.lowerBound
473            }
474        } else {
475            beg = lineStart(point)
476            endMarker.position = min(length, lineEnd(point) + 1)
477        }
478
479        let currentLine = savedLine - 0
480        var seen: Set<String> = []
481        var untouchable: Set<String> = []
482        for field in fields {
483            let reference = "@\(field.row)$\(field.column)"
484            guard seen.insert(reference).inserted else { throw UserError(message: "Several field/range formulas try to set \(reference)") }
485            guard field.row < analysis.dlines.count else { throw UserError(message: "Invalid row number in \(reference)") }
486            let lineStartOffset = saveExcursion { () -> Int in
487                gotoTableLine(analysis.dlines[field.row], analysis)
488                return lineStart(point)
489            }
490            if all || lineStartOffset == currentLine { untouchable.insert(reference) }
491        }
492
493        point = beg
494        let rowMarker = marker(beg)
495        defer { release(rowMarker) }
496        while let match = searchForward("^[ \\t]*\\|[^-]", bound: endMarker.position, caseInsensitive: false) {
497            _ = match
498            let rowStart = lineStart(point)
499            rowMarker.position = rowStart
500            let first = saveExcursion { () -> String in
501                point = rowStart
502                return tableField(1)
503            }
504            if first.range(of: "^ *[_^!$/] *$", options: .regularExpression) == nil {
505                let dline = saveExcursion { () -> Int in
506                    point = rowStart
507                    return tableCurrentDataLine()
508                }
509                for (column, rhs) in columnEquations {
510                    point = rowMarker.position
511                    tableGotoColumn(column, force: true)
512                    if untouchable.contains("@\(dline)$\(column)") { continue }
513                    try tableEvalFormula(rhs, analysis: analysis)
514                }
515            }
516            point = rowMarker.position
517            if forwardLine(1) != 0 || point >= endMarker.position { break }
518        }
519        for field in fields {
520            gotoTableLine(analysis.dlines[field.row], analysis)
521            let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
522            if field.column > count { throw UserError(message: "Missing columns in the table.  Aborting") }
523            tableGotoColumn(field.column)
524            try tableEvalFormula(field.rhs, analysis: analysis)
525        }
526        tableAlign()
527        point = lineMarker.position
528        tableGotoColumn(savedColumn)
529    }
530
531    /// `org-table-get-range` with `corners-only`.
532    func rangeCorners(_ desc: String, analysis: TableAnalysis) throws -> (r1: Int, c1: Int, r2: Int, c2: Int) {
533        let ns = desc as NSString
534        guard let m = try! NSRegularExpression(pattern: Self.rangePattern).firstMatch(in: desc, range: NSRange(location: 0, length: ns.length)) else {
535            throw UserError(message: "Invalid table range specifier `\(desc)'")
536        }
537        func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
538        let thisline = 0
539        func row(_ r: String?) throws -> Int {
540            guard let r, !r.isEmpty else { return thisline }
541            return try Self.descriptorLine(r, thisline, analysis: analysis)
542        }
543        func column(_ c: String?) -> Int {
544            guard let c, let n = Int(c.dropFirst()), n != 0 else { return 1 }
545            return n + (c.dropFirst().first == "-" || c.dropFirst().first == "+" ? 1 : 0)
546        }
547        let r1 = try row(group(1))
548        let r2 = try row(group(4))
549        let c1 = column(group(2))
550        let c2 = column(group(5))
551        return (min(r1, r2), min(c1, c2), max(r1, r2), max(c1, c2))
552    }
553
554    /// `org-table-line-to-dline`.
555    static func lineToDline(_ line: Int, _ analysis: TableAnalysis, above: Bool = false) -> Int? {
556        let dlines = analysis.dlines
557        var low = 1
558        var high = dlines.count - 1
559        if dlines[low] > line || dlines[high] < line { return nil }
560        if line == dlines[high] { return high }
561        while high - low > 1 {
562            let mean = (high + low) / 2
563            if dlines[mean] == line { return mean }
564            if dlines[mean] > line { high = mean } else { low = mean }
565        }
566        if line == dlines[high] { return high }
567        if line == dlines[low] { return low }
568        return above ? low : high
569    }
570}
571
572/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the
573/// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app
574/// recalculates them in Emacs.
575public struct TableRecalculate: OrgCommand {
576    public let all: Bool
577    public init(all: Bool) { self.all = all }
578    public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" }
579    public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" }
580
581    public static let emacsMessage = "needs Emacs: "
582
583    public func applies(in context: EditContext) -> Bool {
584        KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil
585    }
586
587    static func tblfmLine(in context: EditContext) -> String? {
588        let buffer = EmacsBuffer(context.text, point: context.caret)
589        let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
590        guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
591        return line
592    }
593
594    public func run(in context: EditContext) -> CommandStep {
595        let step = commitBuffer(context) { buffer in
596            do {
597                if let line = Self.tblfmLine(in: context) {
598                    // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
599                    // point at the end of the table.
600                    let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
601                    let saved = buffer.marker(buffer.point)
602                    defer { buffer.release(saved) }
603                    guard let tableEnd = buffer.saveExcursion({ () -> Int? in
604                        while buffer.forwardLine(-1) == 0 {
605                            if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
606                        }
607                        return nil
608                    }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
609                    buffer.point = tableEnd
610                    try buffer.tableRecalculate(all: true, tblfm: formulas)
611                    buffer.point = saved.position
612                } else {
613                    try buffer.tableRecalculate(all: all)
614                }
615            } catch let error as Calc.Unsupported {
616                throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason)
617            }
618        }
619        guard case .failed(let message) = step, message.hasPrefix(Self.emacsMessage) else { return step }
620        // Emacs recalculates the table; its text replaces the table here.
621        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
622        let onTblfm = Self.tblfmLine(in: context) != nil
623        if onTblfm {
624            while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {}
625        }
626        let table = buffer.tableBegin()..<buffer.tableEnd()
627        let tblfm = onTblfm ? Self.tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
628        let form = onTblfm ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
629        return .external(.emacsTable(
630            table: table, point: context.caret, form: form,
631            reason: String(message.dropFirst(Self.emacsMessage.count)), lisp: tblfm.contains("'(")
632        ))
633    }
634}
635
636// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
637extension EmacsBuffer {
638    /// `org-table-formula-make-cmp-string`.
639    static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
640        var a = lhs
641        if let arrow = a.firstMatch(of: /^\$([<>])/) {
642            a = (try? handleFirstLast(a, analysis: analysis)) ?? a
643            a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))"
644        }
645        guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil }
646        var key = ""
647        if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) }
648        if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) }
649        if let name = m.5 { key += "@@" + name }
650        return key
651    }
652
653    /// `sort` with `org-table-formula-less-p`.
654    static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] {
655        var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = []
656        // Stable insertion, as `sort` with a partial predicate.
657        for formula in formulas {
658            let key = formulaSortKey(formula.lhs, analysis: analysis)
659            var index = sorted.count
660            while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 }
661            sorted.insert((formula, key), at: index)
662        }
663        return sorted.map(\.formula)
664    }
665
666    /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`.
667    func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) {
668        let sorted = Self.sortFormulas(formulas, analysis: analysis)
669        saveExcursion {
670            point = tableEnd()
671            if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) {
672                deleteRegion(match[3]!.lowerBound, match[0]!.upperBound)
673                point = match[3]!.lowerBound
674            } else {
675                insert("#+TBLFM:")
676            }
677            insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n")
678        }
679    }
680
681    /// `org-table-get-formula` with EQUATION given: stores it for the current column, or with
682    /// `named` the current field, and returns it.
683    func tableGetFormula(_ equation: String, named: Bool, analysis: TableAnalysis) throws -> String {
684        var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "")
685        let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())"
686        let scol = named ? ref : "$\(tableCurrentColumn())"
687        let old = stored.first { $0.lhs == scol }?.rhs
688        var eq = old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation
689        guard eq.contains(where: { !$0.isWhitespace }) else {
690            stored.removeAll { $0.lhs == scol }
691            tableStoreFormulas(stored, analysis: analysis)
692            throw UserError(message: "Formula removed")
693        }
694        eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression)
695        eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression)
696        var mustSave = false
697        if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) {
698            stored.remove(at: index)
699            mustSave = true
700        }
701        if let index = stored.firstIndex(where: { $0.lhs == scol }) {
702            stored[index].rhs = eq
703        } else {
704            stored.insert((scol, eq), at: 0)
705        }
706        if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) }
707        return eq
708    }
709
710    /// `org-table-eval-formula` for the current field with EQUATION, which is stored first.
711    func tableEvalFormula(equation: String, named: Bool) throws {
712        try checkInsideDataField()
713        let analysis = try tableAnalyze()
714        let formula = try tableGetFormula(equation, named: named, analysis: analysis)
715        do {
716            try tableEvalFormula(try Self.handleFirstLast(formula, analysis: analysis), analysis: analysis)
717        } catch let error as Calc.Unsupported {
718            throw UserError(message: "The formula was stored; recalculating it needs Emacs: " + error.reason)
719        }
720        tableAlign()
721    }
722
723    /// `org-table-maybe-eval-formula`.
724    func tableMaybeEvalFormula() throws {
725        skipBackwardNot([124, 10])
726        guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return }
727        let start = point
728        var end = point
729        while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 }
730        point = min(lineEnd(point), start + 1)
731        let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
732        guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return }
733        try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":"))
734    }
735}
736
737/// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's
738/// formula, the stored one offered.
739public struct TableEvalFormula: OrgCommand {
740    let named: Bool
741    public init(named: Bool) { self.named = named }
742    public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" }
743    public var title: String { named ? "Set Field Formula" : "Set Column Formula" }
744    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
745    public func run(in context: EditContext) -> CommandStep {
746        guard let answer = context.answers["formula"] else {
747            let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
748            guard buffer.atTable else { return .failed("Not at a table") }
749            let column = buffer.tableCurrentColumn()
750            let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)"
751            let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs
752            return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? ""))
753        }
754        return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named) }
755    }
756}
757
758// The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor.
759extension BlockEdit {
760    static let formulasKind = "formulas"
761
762    /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as
763    /// org's editor lists them. The range runs from the table (or that line) to the formulas.
764    public static func formulas(at offset: Int, text: String) -> BlockEdit? {
765        let buffer = EmacsBuffer(text, point: offset)
766        let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset))
767        let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil
768        guard atTblfm || buffer.atTable else { return nil }
769        let start: Int
770        let end: Int
771        let formulas: [(lhs: String, rhs: String)]
772        if atTblfm {
773            start = buffer.lineStart(offset)
774            end = min(buffer.length, buffer.lineEnd(offset) + 1)
775            let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " "))
776            formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? []
777            guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil }
778        } else {
779            start = buffer.tableBegin()
780            let tableEnd = buffer.tableEnd()
781            end = buffer.saveExcursion {
782                buffer.point = tableEnd
783                return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd
784            }
785            formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? []
786        }
787        guard let analysis = try? buffer.tableAnalyze() else { return nil }
788        var content = ""
789        var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")]
790        for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) {
791            let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named"
792            if let index = titles.firstIndex(where: { $0.type == type }) {
793                if !content.isEmpty { content += "\n" }
794                content += titles[index].title
795                titles.remove(at: index)
796            }
797            content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n"
798        }
799        let ns = text as NSString
800        return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind)
801    }
802
803    /// `org-table-fedit-finish`'s reading of the editor's text.
804    static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] {
805        let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines)
806        let ns = content as NSString
807        var result: [(lhs: String, rhs: String)] = []
808        for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) {
809            let lhs = ns.substring(with: m.range(at: 1))
810            var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
811            guard !rhs.isEmpty else { continue }
812            rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
813            if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") }
814            result.insert((lhs, rhs), at: 0)
815        }
816        return result
817    }
818
819    /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument.
820    func installFormulas(_ content: String, in context: EditContext) -> CommandStep {
821        let step = commitBuffer(context) { buffer in
822            let formulas = try Self.parseFormulas(content)
823            buffer.point = range.lowerBound
824            let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in
825                if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) }
826                return try buffer.tableAnalyze()
827            }
828            buffer.tableStoreFormulas(formulas, analysis: analysis)
829        }
830        guard case .commit(let result) = step else { return step }
831        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection,
832                                  effects: result.effects + [.message("New formulas installed - press C-u C-c C-c to apply.")]))
833    }
834}