Sources/OrgCore/Compute/TableFormulaCommands.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgCore/Compute/TableFormulaCommands.swift history · blame · raw

337 lines · 18731 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 let emacsMessage = "needs Emacs: "
 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// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
 73extension EmacsBuffer {
 74    /// `org-table-formula-make-cmp-string`.
 75    static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
 76        var a = lhs
 77        if let arrow = a.firstMatch(of: /^\$([<>])/) {
 78            a = (try? handleFirstLast(a, analysis: analysis)) ?? a
 79            a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))"
 80        }
 81        guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil }
 82        var key = ""
 83        if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) }
 84        if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) }
 85        if let name = m.5 { key += "@@" + name }
 86        return key
 87    }
 88
 89    /// `sort` with `org-table-formula-less-p`.
 90    static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] {
 91        var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = []
 92        // Stable insertion, as `sort` with a partial predicate.
 93        for formula in formulas {
 94            let key = formulaSortKey(formula.lhs, analysis: analysis)
 95            var index = sorted.count
 96            while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 }
 97            sorted.insert((formula, key), at: index)
 98        }
 99        return sorted.map(\.formula)
100    }
101
102    /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`.
103    func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) {
104        let sorted = Self.sortFormulas(formulas, analysis: analysis)
105        saveExcursion {
106            point = tableEnd()
107            if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) {
108                deleteRegion(match[3]!.lowerBound, match[0]!.upperBound)
109                point = match[3]!.lowerBound
110            } else {
111                insert("#+TBLFM:")
112            }
113            insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n")
114        }
115    }
116
117    /// `org-table-get-formula`: stores EQUATION for the current column, or with `named` the
118    /// current field, and returns it; nil when a blank EQUATION removed the formula. `read`
119    /// when EQUATION is the prompt's answer, which the stored formula never replaces.
120    func tableGetFormula(_ equation: String, named: Bool, read: Bool = false, analysis: TableAnalysis) throws -> String? {
121        var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "")
122        let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())"
123        let scol = named ? ref : "$\(tableCurrentColumn())"
124        let old = stored.first { $0.lhs == scol }?.rhs
125        var eq = !read && old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation
126        guard eq.contains(where: { !$0.isWhitespace }) else {
127            stored.removeAll { $0.lhs == scol }
128            tableStoreFormulas(stored, analysis: analysis)
129            // Org's user error, which keeps the stored formulas and stops the command.
130            message = "Formula removed"
131            return nil
132        }
133        eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression)
134        eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression)
135        var mustSave = false
136        if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) {
137            stored.remove(at: index)
138            mustSave = true
139        }
140        if let index = stored.firstIndex(where: { $0.lhs == scol }) {
141            stored[index].rhs = eq
142        } else {
143            stored.insert((scol, eq), at: 0)
144        }
145        if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) }
146        return eq
147    }
148
149    /// `org-table-eval-formula` for the current field with EQUATION, which is stored first.
150    /// A formula only Emacs can evaluate stays stored, the field unchanged.
151    func tableEvalFormula(equation: String, named: Bool, read: Bool = false) throws {
152        try checkInsideDataField()
153        let analysis = try tableAnalyze()
154        guard let formula = try tableGetFormula(equation, named: named, read: read, analysis: analysis) else { return }
155        do {
156            try tableEvalFormula(formula, analysis: analysis, substituted: false)
157        } catch let error as Calc.Unsupported {
158            message = "The formula was stored; recalculating it needs Emacs: " + error.reason
159        }
160        tableAlign()
161    }
162
163    /// `org-table-maybe-eval-formula`.
164    func tableMaybeEvalFormula() throws {
165        skipBackwardNot([124, 10])
166        guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return }
167        let start = point
168        var end = point
169        while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 }
170        point = min(lineEnd(point), start + 1)
171        let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
172        guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return }
173        try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":"))
174    }
175}
176
177/// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's
178/// formula, the stored one offered.
179public struct TableEvalFormula: OrgCommand {
180    let named: Bool
181    public init(named: Bool) { self.named = named }
182    public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" }
183    public var title: String { named ? "Set Field Formula" : "Set Column Formula" }
184    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
185    public func run(in context: EditContext) -> CommandStep {
186        guard let answer = context.answers["formula"] else {
187            let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
188            guard buffer.atTable else { return .failed("Not at a table") }
189            let column = buffer.tableCurrentColumn()
190            let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)"
191            let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs
192            return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? ""))
193        }
194        return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named, read: true) }
195    }
196}
197
198// The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor.
199extension BlockEdit {
200    static let formulasKind = "formulas"
201
202    /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as
203    /// org's editor lists them. The range runs from the table (or that line) to the formulas.
204    public static func formulas(at offset: Int, text: String) -> BlockEdit? {
205        let buffer = EmacsBuffer(text, point: offset)
206        let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset))
207        let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil
208        guard atTblfm || buffer.atTable else { return nil }
209        let start: Int
210        let end: Int
211        let formulas: [(lhs: String, rhs: String)]
212        if atTblfm {
213            start = buffer.lineStart(offset)
214            end = min(buffer.length, buffer.lineEnd(offset) + 1)
215            let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " "))
216            formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? []
217            guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil }
218        } else {
219            start = buffer.tableBegin()
220            let tableEnd = buffer.tableEnd()
221            end = buffer.saveExcursion {
222                buffer.point = tableEnd
223                return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd
224            }
225            formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? []
226        }
227        guard let analysis = try? buffer.tableAnalyze() else { return nil }
228        var content = ""
229        var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")]
230        for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) {
231            let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named"
232            if let index = titles.firstIndex(where: { $0.type == type }) {
233                if !content.isEmpty { content += "\n" }
234                content += titles[index].title
235                titles.remove(at: index)
236            }
237            content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n"
238        }
239        let ns = text as NSString
240        return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind)
241    }
242
243    /// `org-table-fedit-finish`'s reading of the editor's text.
244    static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] {
245        let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines)
246        let ns = content as NSString
247        var result: [(lhs: String, rhs: String)] = []
248        for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) {
249            let lhs = ns.substring(with: m.range(at: 1))
250            var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
251            guard !rhs.isEmpty else { continue }
252            rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
253            if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") }
254            result.insert((lhs, rhs), at: 0)
255        }
256        return result
257    }
258
259    /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument.
260    func installFormulas(_ content: String, in context: EditContext) -> CommandStep {
261        let step = commitBuffer(context) { buffer in
262            let formulas = try Self.parseFormulas(content)
263            buffer.point = range.lowerBound
264            let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in
265                if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) }
266                return try buffer.tableAnalyze()
267            }
268            buffer.tableStoreFormulas(formulas, analysis: analysis)
269        }
270        guard case .commit(let result) = step else { return step }
271        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection,
272                                  effects: result.effects + [.message("New formulas installed - Recalculate Table (C-c C-c on the #+TBLFM line) applies them.")]))
273    }
274}
275
276// `org-table-edit-field` (C-c `): a field's text edited apart, then put back.
277extension BlockEdit {
278    static let fieldKind = "field"
279
280    /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged.
281    public static func field(at offset: Int, text: String) -> BlockEdit? {
282        let buffer = EmacsBuffer(text, point: offset)
283        guard buffer.insideDataField else { return nil }
284        let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())"
285        let field = buffer.saveExcursion { () -> String in
286            buffer.skipBackwardNot([124, 10])
287            return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound)
288        }
289        let start = buffer.lineStart(offset)
290        let end = buffer.lineEnd(offset)
291        return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines),
292                         language: nil, kind: fieldKind, point: offset, coordinate: coordinate)
293    }
294
295    /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the
296    /// table is aligned.
297    func installField(_ content: String, in context: EditContext) -> CommandStep {
298        var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression)
299        text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression)
300        text = text.trimmingCharacters(in: .whitespacesAndNewlines)
301        return commitBuffer(context) { buffer in
302            buffer.point = point ?? range.lowerBound
303            guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") }
304            buffer.skipBackwardNot([124, 10])
305            let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound
306            buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text)
307            buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1)
308            buffer.tableAlign()
309        }
310    }
311}
312
313extension EmacsBuffer {
314    /// `org-table-check-inside-data-field` with NOERROR.
315    var insideDataField: Bool {
316        atTable && !atTableHline
317            && !saveExcursion { () -> Bool in
318                while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 }
319                return bolp
320            }
321            && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil
322    }
323}
324
325/// C-c `: `org-table-edit-field`, in the block editor.
326public struct TableEditField: OrgCommand {
327    public init() {}
328    public var id: String { "org.table.edit-field" }
329    public var title: String { "Edit Table Field" }
330    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
331    public func run(in context: EditContext) -> CommandStep {
332        guard let edit = BlockEdit.field(at: context.caret, text: context.text) else {
333            return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table")
334        }
335        return .external(.editBlock(edit))
336    }
337}