Sources/OrgCore/Compute/TableFormulaCommands.swift

394 lines · 21816 bytes

28 symbols in this file
  1import Foundation
  2
  3/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the
  4/// native evaluator can't do become a request to recalculate them in Emacs.
  5public struct TableRecalculate: OrgCommand {
  6    public let all: Bool
  7    public init(all: Bool) { self.all = all }
  8    public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" }
  9    public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" }
 10
 11    public static var emacsMessage: String { EmacsFallback.wording("needs Emacs: ", "can't be calculated here: ") }
 12
 13    public func applies(in context: EditContext) -> Bool {
 14        KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil
 15    }
 16
 17    static func tblfmLine(in context: EditContext) -> String? {
 18        let buffer = EmacsBuffer(context.text, point: context.caret)
 19        let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
 20        guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
 21        return line
 22    }
 23
 24    public func run(in context: EditContext) -> CommandStep {
 25        let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
 26        return Self.recalculating(context, form: form) { buffer in
 27            if let line = Self.tblfmLine(in: context) {
 28                // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
 29                // point at the end of the table, then back where it was, even after an error.
 30                let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
 31                let saved = buffer.marker(buffer.point)
 32                defer {
 33                    buffer.point = saved.position
 34                    buffer.release(saved)
 35                }
 36                guard let tableEnd = buffer.saveExcursion({ () -> Int? in
 37                    while buffer.forwardLine(-1) == 0 {
 38                        if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
 39                    }
 40                    return nil
 41                }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
 42                buffer.point = tableEnd
 43                try buffer.tableRecalculate(all: true, tblfm: formulas)
 44            } else {
 45                try buffer.tableRecalculate(all: all)
 46            }
 47        }
 48    }
 49
 50    /// `commitBuffer` for a recalculation. On an error the fields written before it stay, as
 51    /// in Emacs, with the error as the message. A formula the native evaluator can't do makes
 52    /// a request to run `form` in Emacs, which carries those fields for builds without Emacs.
 53    static func recalculating(_ context: EditContext, form: String, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
 54        var failure: String?
 55        var unsupported: Calc.Unsupported?
 56        let step = commitBuffer(context) { buffer in
 57            do {
 58                try body(buffer)
 59            } catch let error as EmacsBuffer.UserError {
 60                failure = error.message
 61            } catch let error as Calc.Unsupported {
 62                unsupported = error
 63            }
 64        }
 65        guard case .commit(let result) = step else { return step }
 66        if let unsupported {
 67            let wrote = !result.edits.isEmpty
 68            return request(form: form, reason: unsupported.reason, formula: wrote ? unsupported.formula : nil, partial: wrote ? result : nil, in: context)
 69        }
 70        guard let failure else { return step }
 71        // `org-table-save-field` moves point to the field's start even when nothing was written.
 72        guard !result.edits.isEmpty || result.selection != [context.caret..<context.caret] else { return .failed(failure) }
 73        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(failure)]))
 74    }
 75
 76    static func request(form: String, reason: String, formula: String?, partial: EditResult?, in context: EditContext) -> CommandStep {
 77        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
 78        let onTblfm = tblfmLine(in: context) != nil
 79        if onTblfm {
 80            while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {}
 81        }
 82        let table = buffer.tableBegin()..<buffer.tableEnd()
 83        let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
 84        return .external(.emacsTable(
 85            table: table, point: context.caret, form: form,
 86            reason: reason, lisp: tblfm.contains("'("), formula: formula, partial: partial
 87        ))
 88    }
 89}
 90
 91/// C-u C-u C-c *: `org-table-iterate`, the whole table recalculated until it stops changing,
 92/// at most ten times.
 93public struct TableIterate: OrgCommand {
 94    public init() {}
 95    public var id: String { "org.table.iterate" }
 96    public var title: String { "Iterate Table Formulas" }
 97    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
 98
 99    public func run(in context: EditContext) -> CommandStep {
100        var message = ""
101        let step = TableRecalculate.recalculating(context, form: "(org-table-iterate)") { buffer in
102            guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
103            func table() -> String { buffer.substring(buffer.tableBegin(), buffer.tableEnd()) }
104            var last = table()
105            for iteration in 1...10 {
106                try buffer.tableRecalculate(all: true)
107                let this = table()
108                if this == last {
109                    message = iteration > 1 ? "Convergence after \(iteration) iterations" : "Table was already stable"
110                    return
111                }
112                last = this
113            }
114            // The recalculations stay, as Emacs leaves them before its error.
115            message = "No convergence after 10 iterations"
116        }
117        guard case .commit(let result) = step, !message.isEmpty else { return step }
118        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(message)]))
119    }
120}
121
122// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
123extension EmacsBuffer {
124    /// `org-table-maybe-recalculate-line`: a row whose first field is `#` recalculated, as
125    /// TAB, S-TAB and RET in a table do first.
126    func tableMaybeRecalculateLine() throws {
127        guard lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else { return }
128        try tableRecalculate(all: false)
129    }
130
131    /// `org-table-formula-make-cmp-string`.
132    static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
133        var a = lhs
134        if let arrow = a.firstMatch(of: /^\$([<>])/) {
135            a = (try? handleFirstLast(a, analysis: analysis)) ?? a
136            a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))"
137        }
138        guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil }
139        var key = ""
140        if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) }
141        if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) }
142        if let name = m.5 { key += "@@" + name }
143        return key
144    }
145
146    /// `sort` with `org-table-formula-less-p`.
147    static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] {
148        var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = []
149        // Stable insertion, as `sort` with a partial predicate.
150        for formula in formulas {
151            let key = formulaSortKey(formula.lhs, analysis: analysis)
152            var index = sorted.count
153            while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 }
154            sorted.insert((formula, key), at: index)
155        }
156        return sorted.map(\.formula)
157    }
158
159    /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`.
160    func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) {
161        let sorted = Self.sortFormulas(formulas, analysis: analysis)
162        saveExcursion {
163            point = tableEnd()
164            if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) {
165                deleteRegion(match[3]!.lowerBound, match[0]!.upperBound)
166                point = match[3]!.lowerBound
167            } else {
168                insert("#+TBLFM:")
169            }
170            insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n")
171        }
172    }
173
174    /// `org-table-get-formula`: stores EQUATION for the current column, or with `named` the
175    /// current field, and returns it; nil when a blank EQUATION removed the formula. `read`
176    /// when EQUATION is the prompt's answer, which the stored formula never replaces.
177    func tableGetFormula(_ equation: String, named: Bool, read: Bool = false, analysis: TableAnalysis) throws -> String? {
178        var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "")
179        let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())"
180        let scol = named ? ref : "$\(tableCurrentColumn())"
181        let old = stored.first { $0.lhs == scol }?.rhs
182        var eq = !read && old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation
183        guard eq.contains(where: { !$0.isWhitespace }) else {
184            stored.removeAll { $0.lhs == scol }
185            tableStoreFormulas(stored, analysis: analysis)
186            // Org's user error, which keeps the stored formulas and stops the command.
187            message = "Formula removed"
188            return nil
189        }
190        eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression)
191        eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression)
192        var mustSave = false
193        if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) {
194            stored.remove(at: index)
195            mustSave = true
196        }
197        if let index = stored.firstIndex(where: { $0.lhs == scol }) {
198            stored[index].rhs = eq
199        } else {
200            stored.insert((scol, eq), at: 0)
201        }
202        if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) }
203        return eq
204    }
205
206    /// `org-table-eval-formula` for the current field with EQUATION, which is stored first.
207    /// A formula only Emacs can evaluate stays stored, the field unchanged.
208    func tableEvalFormula(equation: String, named: Bool, read: Bool = false) throws {
209        try checkInsideDataField()
210        let analysis = try tableAnalyze()
211        guard let formula = try tableGetFormula(equation, named: named, read: read, analysis: analysis) else { return }
212        do {
213            try tableEvalFormula(formula, analysis: analysis, substituted: false)
214        } catch let error as Calc.Unsupported {
215            message = EmacsFallback.wording("The formula was stored; recalculating it needs Emacs: ", "The formula was stored; it can't be calculated here: ") + error.reason
216        }
217        tableAlign()
218    }
219
220    /// `org-table-maybe-eval-formula`.
221    func tableMaybeEvalFormula() throws {
222        skipBackwardNot([124, 10])
223        guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return }
224        let start = point
225        var end = point
226        while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 }
227        point = min(lineEnd(point), start + 1)
228        let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
229        guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return }
230        try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":"))
231    }
232}
233
234/// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's
235/// formula, the stored one offered.
236public struct TableEvalFormula: OrgCommand {
237    let named: Bool
238    public init(named: Bool) { self.named = named }
239    public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" }
240    public var title: String { named ? "Set Field Formula" : "Set Column Formula" }
241    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
242    public func run(in context: EditContext) -> CommandStep {
243        guard let answer = context.answers["formula"] else {
244            let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
245            guard buffer.atTable else { return .failed("Not at a table") }
246            let column = buffer.tableCurrentColumn()
247            let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)"
248            let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs
249            return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? ""))
250        }
251        return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named, read: true) }
252    }
253}
254
255// The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor.
256extension BlockEdit {
257    static let formulasKind = "formulas"
258
259    /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as
260    /// org's editor lists them. The range runs from the table (or that line) to the formulas.
261    public static func formulas(at offset: Int, text: String) -> BlockEdit? {
262        let buffer = EmacsBuffer(text, point: offset)
263        let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset))
264        let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil
265        guard atTblfm || buffer.atTable else { return nil }
266        let start: Int
267        let end: Int
268        let formulas: [(lhs: String, rhs: String)]
269        if atTblfm {
270            start = buffer.lineStart(offset)
271            end = min(buffer.length, buffer.lineEnd(offset) + 1)
272            let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " "))
273            formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? []
274            guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil }
275        } else {
276            start = buffer.tableBegin()
277            let tableEnd = buffer.tableEnd()
278            end = buffer.saveExcursion {
279                buffer.point = tableEnd
280                return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd
281            }
282            formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? []
283        }
284        guard let analysis = try? buffer.tableAnalyze() else { return nil }
285        var content = ""
286        var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")]
287        for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) {
288            let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named"
289            if let index = titles.firstIndex(where: { $0.type == type }) {
290                if !content.isEmpty { content += "\n" }
291                content += titles[index].title
292                titles.remove(at: index)
293            }
294            content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n"
295        }
296        let ns = text as NSString
297        return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind)
298    }
299
300    /// `org-table-fedit-finish`'s reading of the editor's text.
301    static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] {
302        let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines)
303        let ns = content as NSString
304        var result: [(lhs: String, rhs: String)] = []
305        for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) {
306            let lhs = ns.substring(with: m.range(at: 1))
307            var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
308            guard !rhs.isEmpty else { continue }
309            rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
310            if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") }
311            result.insert((lhs, rhs), at: 0)
312        }
313        return result
314    }
315
316    /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument.
317    func installFormulas(_ content: String, in context: EditContext) -> CommandStep {
318        let step = commitBuffer(context) { buffer in
319            let formulas = try Self.parseFormulas(content)
320            buffer.point = range.lowerBound
321            let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in
322                if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) }
323                return try buffer.tableAnalyze()
324            }
325            buffer.tableStoreFormulas(formulas, analysis: analysis)
326        }
327        guard case .commit(let result) = step else { return step }
328        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection,
329                                  effects: result.effects + [.message("New formulas installed - Recalculate Table (C-c C-c on the #+TBLFM line) applies them.")]))
330    }
331}
332
333// `org-table-edit-field` (C-c `): a field's text edited apart, then put back.
334extension BlockEdit {
335    static let fieldKind = "field"
336
337    /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged.
338    public static func field(at offset: Int, text: String) -> BlockEdit? {
339        let buffer = EmacsBuffer(text, point: offset)
340        guard buffer.insideDataField else { return nil }
341        let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())"
342        let field = buffer.saveExcursion { () -> String in
343            buffer.skipBackwardNot([124, 10])
344            return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound)
345        }
346        let start = buffer.lineStart(offset)
347        let end = buffer.lineEnd(offset)
348        return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines),
349                         language: nil, kind: fieldKind, point: offset, coordinate: coordinate)
350    }
351
352    /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the
353    /// table is aligned.
354    func installField(_ content: String, in context: EditContext) -> CommandStep {
355        var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression)
356        text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression)
357        text = text.trimmingCharacters(in: .whitespacesAndNewlines)
358        return commitBuffer(context) { buffer in
359            buffer.point = point ?? range.lowerBound
360            guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") }
361            buffer.skipBackwardNot([124, 10])
362            let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound
363            buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text)
364            buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1)
365            buffer.tableAlign()
366        }
367    }
368}
369
370extension EmacsBuffer {
371    /// `org-table-check-inside-data-field` with NOERROR.
372    var insideDataField: Bool {
373        atTable && !atTableHline
374            && !saveExcursion { () -> Bool in
375                while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 }
376                return bolp
377            }
378            && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil
379    }
380}
381
382/// C-c `: `org-table-edit-field`, in the block editor.
383public struct TableEditField: OrgCommand {
384    public init() {}
385    public var id: String { "org.table.edit-field" }
386    public var title: String { "Edit Table Field" }
387    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
388    public func run(in context: EditContext) -> CommandStep {
389        guard let edit = BlockEdit.field(at: context.caret, text: context.text) else {
390            return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table")
391        }
392        return .external(.editBlock(edit))
393    }
394}