Sources/OrgCore/Compute/TableFormulaCommands.swift

381 lines · 20988 bytes

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