Commit 30363f6b17
Verified · cmc
Layout: unified · split
Sources/OrgCore/Compute/TableFormulaCommands.swift added +337
| @@ -0,0 +1,337 @@ | ||
| 1 | import 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. | |
| 6 | public 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`). | |
| 73 | extension 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. | |
| 179 | public 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. | |
| 199 | extension 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. | |
| 277 | extension 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 | ||
| 313 | extension 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. | |
| 326 | public 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 | } | |
Sources/OrgCore/Compute/TableFormulas.swift −336
| @@ -903,339 +903,3 @@ extension EmacsBuffer { | ||
| 903 | 903 | return above ? low : high |
| 904 | 904 | } |
| 905 | 905 | } |
| 906 | ||
| 907 | /// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the | |
| 908 | /// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app | |
| 909 | /// recalculates them in Emacs. | |
| 910 | public struct TableRecalculate: OrgCommand { | |
| 911 | public let all: Bool | |
| 912 | public init(all: Bool) { self.all = all } | |
| 913 | public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" } | |
| 914 | public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" } | |
| 915 | ||
| 916 | public static let emacsMessage = "needs Emacs: " | |
| 917 | ||
| 918 | public func applies(in context: EditContext) -> Bool { | |
| 919 | KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil | |
| 920 | } | |
| 921 | ||
| 922 | static func tblfmLine(in context: EditContext) -> String? { | |
| 923 | let buffer = EmacsBuffer(context.text, point: context.caret) | |
| 924 | let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point)) | |
| 925 | guard line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil else { return nil } | |
| 926 | return line | |
| 927 | } | |
| 928 | ||
| 929 | public func run(in context: EditContext) -> CommandStep { | |
| 930 | let step = commitBuffer(context) { buffer in | |
| 931 | do { | |
| 932 | if let line = Self.tblfmLine(in: context) { | |
| 933 | // `org-table-calc-current-TBLFM`: that line's formulas, every row, with | |
| 934 | // point at the end of the table. | |
| 935 | let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " ")) | |
| 936 | let saved = buffer.marker(buffer.point) | |
| 937 | defer { buffer.release(saved) } | |
| 938 | guard let tableEnd = buffer.saveExcursion({ () -> Int? in | |
| 939 | while buffer.forwardLine(-1) == 0 { | |
| 940 | if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) } | |
| 941 | } | |
| 942 | return nil | |
| 943 | }) else { throw EmacsBuffer.UserError(message: "Not at a table") } | |
| 944 | buffer.point = tableEnd | |
| 945 | try buffer.tableRecalculate(all: true, tblfm: formulas) | |
| 946 | buffer.point = saved.position | |
| 947 | } else { | |
| 948 | try buffer.tableRecalculate(all: all) | |
| 949 | } | |
| 950 | } catch let error as Calc.Unsupported { | |
| 951 | throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason) | |
| 952 | } | |
| 953 | } | |
| 954 | let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)" | |
| 955 | return Self.inEmacs(step, form: form, in: context) | |
| 956 | } | |
| 957 | ||
| 958 | /// A step that failed with `emacsMessage` as a request to run `form` on the table in | |
| 959 | /// Emacs, whose text then replaces the table here; other steps unchanged. | |
| 960 | static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep { | |
| 961 | guard case .failed(let message) = step, message.hasPrefix(emacsMessage) else { return step } | |
| 962 | let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options) | |
| 963 | let onTblfm = tblfmLine(in: context) != nil | |
| 964 | if onTblfm { | |
| 965 | while buffer.forwardLine(-1) == 0, !buffer.lookingAtLine("^[ \\t]*\\|") {} | |
| 966 | } | |
| 967 | let table = buffer.tableBegin()..<buffer.tableEnd() | |
| 968 | let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? "" | |
| 969 | return .external(.emacsTable( | |
| 970 | table: table, point: context.caret, form: form, | |
| 971 | reason: String(message.dropFirst(emacsMessage.count)), lisp: tblfm.contains("'(") | |
| 972 | )) | |
| 973 | } | |
| 974 | } | |
| 975 | ||
| 976 | // Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`). | |
| 977 | extension EmacsBuffer { | |
| 978 | /// `org-table-formula-make-cmp-string`. | |
| 979 | static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? { | |
| 980 | var a = lhs | |
| 981 | if let arrow = a.firstMatch(of: /^\$([<>])/) { | |
| 982 | a = (try? handleFirstLast(a, analysis: analysis)) ?? a | |
| 983 | a = "$\(10000 + (arrow.1 == "<" ? -1000 : 0) + Int(stringToNumber(String(a.dropFirst()))))" | |
| 984 | } | |
| 985 | guard let m = a.firstMatch(of: /^(@([0-9]+))?(\$?([0-9]+))?(\$?[a-zA-Z0-9]+)?/) else { return nil } | |
| 986 | var key = "" | |
| 987 | if let row = m.2 { key += String(format: "@%05d", Int(row) ?? 0) } | |
| 988 | if let column = m.4 { key += String(format: "$%05d", Int(column) ?? 0) } | |
| 989 | if let name = m.5 { key += "@@" + name } | |
| 990 | return key | |
| 991 | } | |
| 992 | ||
| 993 | /// `sort` with `org-table-formula-less-p`. | |
| 994 | static func sortFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) -> [(lhs: String, rhs: String)] { | |
| 995 | var sorted: [(formula: (lhs: String, rhs: String), key: String?)] = [] | |
| 996 | // Stable insertion, as `sort` with a partial predicate. | |
| 997 | for formula in formulas { | |
| 998 | let key = formulaSortKey(formula.lhs, analysis: analysis) | |
| 999 | var index = sorted.count | |
| 1000 | while index > 0, let a = key, let b = sorted[index - 1].key, a < b { index -= 1 } | |
| 1001 | sorted.insert((formula, key), at: index) | |
| 1002 | } | |
| 1003 | return sorted.map(\.formula) | |
| 1004 | } | |
| 1005 | ||
| 1006 | /// `org-table-store-formulas`, sorted by `org-table-formula-less-p`. | |
| 1007 | func tableStoreFormulas(_ formulas: [(lhs: String, rhs: String)], analysis: TableAnalysis) { | |
| 1008 | let sorted = Self.sortFormulas(formulas, analysis: analysis) | |
| 1009 | saveExcursion { | |
| 1010 | point = tableEnd() | |
| 1011 | if let match = looking("([ \\t]*\\n)*[ \\t]*(#\\+TBLFM:)(.*\\n?)", caseInsensitive: true, setsMatch: false) { | |
| 1012 | deleteRegion(match[3]!.lowerBound, match[0]!.upperBound) | |
| 1013 | point = match[3]!.lowerBound | |
| 1014 | } else { | |
| 1015 | insert("#+TBLFM:") | |
| 1016 | } | |
| 1017 | insert(" " + sorted.map { $0.lhs + "=" + $0.rhs }.joined(separator: "::") + "\n") | |
| 1018 | } | |
| 1019 | } | |
| 1020 | ||
| 1021 | /// `org-table-get-formula`: stores EQUATION for the current column, or with `named` the | |
| 1022 | /// current field, and returns it; nil when a blank EQUATION removed the formula. `read` | |
| 1023 | /// when EQUATION is the prompt's answer, which the stored formula never replaces. | |
| 1024 | func tableGetFormula(_ equation: String, named: Bool, read: Bool = false, analysis: TableAnalysis) throws -> String? { | |
| 1025 | var stored = try Self.storedFormulas(firstTblfm(after: tableEnd()) ?? "") | |
| 1026 | let ref = "@\(tableCurrentDataLine())$\(tableCurrentColumn())" | |
| 1027 | let scol = named ? ref : "$\(tableCurrentColumn())" | |
| 1028 | let old = stored.first { $0.lhs == scol }?.rhs | |
| 1029 | var eq = !read && old != nil && equation.range(of: "^ *=? *$", options: .regularExpression) != nil ? old! : equation | |
| 1030 | guard eq.contains(where: { !$0.isWhitespace }) else { | |
| 1031 | stored.removeAll { $0.lhs == scol } | |
| 1032 | tableStoreFormulas(stored, analysis: analysis) | |
| 1033 | // Org's user error, which keeps the stored formulas and stops the command. | |
| 1034 | message = "Formula removed" | |
| 1035 | return nil | |
| 1036 | } | |
| 1037 | eq = eq.replacingOccurrences(of: "^ *=?", with: "", options: .regularExpression) | |
| 1038 | eq = eq.replacingOccurrences(of: " *$", with: "", options: .regularExpression) | |
| 1039 | var mustSave = false | |
| 1040 | if !named, let index = stored.firstIndex(where: { $0.lhs == ref }) { | |
| 1041 | stored.remove(at: index) | |
| 1042 | mustSave = true | |
| 1043 | } | |
| 1044 | if let index = stored.firstIndex(where: { $0.lhs == scol }) { | |
| 1045 | stored[index].rhs = eq | |
| 1046 | } else { | |
| 1047 | stored.insert((scol, eq), at: 0) | |
| 1048 | } | |
| 1049 | if mustSave || old != eq { tableStoreFormulas(stored, analysis: analysis) } | |
| 1050 | return eq | |
| 1051 | } | |
| 1052 | ||
| 1053 | /// `org-table-eval-formula` for the current field with EQUATION, which is stored first. | |
| 1054 | /// A formula only Emacs can evaluate stays stored, the field unchanged. | |
| 1055 | func tableEvalFormula(equation: String, named: Bool, read: Bool = false) throws { | |
| 1056 | try checkInsideDataField() | |
| 1057 | let analysis = try tableAnalyze() | |
| 1058 | guard let formula = try tableGetFormula(equation, named: named, read: read, analysis: analysis) else { return } | |
| 1059 | do { | |
| 1060 | try tableEvalFormula(formula, analysis: analysis, substituted: false) | |
| 1061 | } catch let error as Calc.Unsupported { | |
| 1062 | message = "The formula was stored; recalculating it needs Emacs: " + error.reason | |
| 1063 | } | |
| 1064 | tableAlign() | |
| 1065 | } | |
| 1066 | ||
| 1067 | /// `org-table-maybe-eval-formula`. | |
| 1068 | func tableMaybeEvalFormula() throws { | |
| 1069 | skipBackwardNot([124, 10]) | |
| 1070 | guard !bolp, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil else { return } | |
| 1071 | let start = point | |
| 1072 | var end = point | |
| 1073 | while let c = character(at: end), c != 124, c != 10, c != 13 { end += 1 } | |
| 1074 | point = min(lineEnd(point), start + 1) | |
| 1075 | let field = substring(start, end).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | |
| 1076 | guard let m = field.firstMatch(of: /^:?=(.*[^=])$/) else { return } | |
| 1077 | try tableEvalFormula(equation: String(m.1), named: field.hasPrefix(":")) | |
| 1078 | } | |
| 1079 | } | |
| 1080 | ||
| 1081 | /// C-c = and C-u C-c =: `org-table-eval-formula`, asking for the column's or the field's | |
| 1082 | /// formula, the stored one offered. | |
| 1083 | public struct TableEvalFormula: OrgCommand { | |
| 1084 | let named: Bool | |
| 1085 | public init(named: Bool) { self.named = named } | |
| 1086 | public var id: String { named ? "org.table.field-formula" : "org.table.column-formula" } | |
| 1087 | public var title: String { named ? "Set Field Formula" : "Set Column Formula" } | |
| 1088 | public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) } | |
| 1089 | public func run(in context: EditContext) -> CommandStep { | |
| 1090 | guard let answer = context.answers["formula"] else { | |
| 1091 | let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options) | |
| 1092 | guard buffer.atTable else { return .failed("Not at a table") } | |
| 1093 | let column = buffer.tableCurrentColumn() | |
| 1094 | let scol = named ? "@\(buffer.tableCurrentDataLine())$\(column)" : "$\(column)" | |
| 1095 | let stored = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: buffer.tableEnd()) ?? ""))?.first { $0.lhs == scol }?.rhs | |
| 1096 | return .prompt(Prompt(key: "formula", message: "\(named ? "Field" : "Column") formula \(scol)=", initial: stored ?? "")) | |
| 1097 | } | |
| 1098 | return commitBuffer(context) { try $0.tableEvalFormula(equation: answer, named: named, read: true) } | |
| 1099 | } | |
| 1100 | } | |
| 1101 | ||
| 1102 | // The formula editor (`org-table-edit-formulas`, C-c ' in a table), in the block editor. | |
| 1103 | extension BlockEdit { | |
| 1104 | static let formulasKind = "formulas" | |
| 1105 | ||
| 1106 | /// The formulas of the table at `offset`, or of the `#+TBLFM` line there, one per line as | |
| 1107 | /// org's editor lists them. The range runs from the table (or that line) to the formulas. | |
| 1108 | public static func formulas(at offset: Int, text: String) -> BlockEdit? { | |
| 1109 | let buffer = EmacsBuffer(text, point: offset) | |
| 1110 | let line = buffer.substring(buffer.lineStart(offset), buffer.lineEnd(offset)) | |
| 1111 | let atTblfm = line.range(of: EmacsBuffer.tblfmPattern, options: [.regularExpression, .caseInsensitive]) != nil | |
| 1112 | guard atTblfm || buffer.atTable else { return nil } | |
| 1113 | let start: Int | |
| 1114 | let end: Int | |
| 1115 | let formulas: [(lhs: String, rhs: String)] | |
| 1116 | if atTblfm { | |
| 1117 | start = buffer.lineStart(offset) | |
| 1118 | end = min(buffer.length, buffer.lineEnd(offset) + 1) | |
| 1119 | let tblfm = String(line[line.range(of: ":")!.upperBound...]).trimmingCharacters(in: .init(charactersIn: " ")) | |
| 1120 | formulas = (try? EmacsBuffer.storedFormulas(tblfm)) ?? [] | |
| 1121 | guard buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) != nil else { return nil } | |
| 1122 | } else { | |
| 1123 | start = buffer.tableBegin() | |
| 1124 | let tableEnd = buffer.tableEnd() | |
| 1125 | end = buffer.saveExcursion { | |
| 1126 | buffer.point = tableEnd | |
| 1127 | return buffer.looking("([ \\t]*\\n)*[ \\t]*#\\+TBLFM:.*\\n?", caseInsensitive: true, setsMatch: false)?[0]?.upperBound ?? tableEnd | |
| 1128 | } | |
| 1129 | formulas = (try? EmacsBuffer.storedFormulas(buffer.firstTblfm(after: tableEnd) ?? "")) ?? [] | |
| 1130 | } | |
| 1131 | guard let analysis = try? buffer.tableAnalyze() else { return nil } | |
| 1132 | var content = "" | |
| 1133 | var titles: [(type: String, title: String)] = [("column", "# Column Formulas\n"), ("field", "# Field and Range Formulas\n"), ("named", "# Named Field Formulas\n")] | |
| 1134 | for (lhs, rhs) in EmacsBuffer.sortFormulas(formulas, analysis: analysis) { | |
| 1135 | let type = lhs.range(of: "^\\$([0-9]+|[<>]+)$", options: .regularExpression) != nil ? "column" : lhs.hasPrefix("@") ? "field" : "named" | |
| 1136 | if let index = titles.firstIndex(where: { $0.type == type }) { | |
| 1137 | if !content.isEmpty { content += "\n" } | |
| 1138 | content += titles[index].title | |
| 1139 | titles.remove(at: index) | |
| 1140 | } | |
| 1141 | content += (lhs.hasPrefix("@") || lhs.hasPrefix("$") ? "" : "$") + lhs + " = " + rhs + "\n" | |
| 1142 | } | |
| 1143 | let ns = text as NSString | |
| 1144 | return BlockEdit(range: start..<end, original: ns.substring(with: NSRange(location: start, length: end - start)), content: content, language: nil, kind: formulasKind) | |
| 1145 | } | |
| 1146 | ||
| 1147 | /// `org-table-fedit-finish`'s reading of the editor's text. | |
| 1148 | static func parseFormulas(_ content: String) throws -> [(lhs: String, rhs: String)] { | |
| 1149 | let regex = try! NSRegularExpression(pattern: "^(@[-+I<>0-9.$@]+|@?[0-9]+|\\$([a-zA-Z0-9]+|[<>]+)) *= *(.*(\\n[ \\t]+.*$)*)", options: .anchorsMatchLines) | |
| 1150 | let ns = content as NSString | |
| 1151 | var result: [(lhs: String, rhs: String)] = [] | |
| 1152 | for m in regex.matches(in: content, range: NSRange(location: 0, length: ns.length)) { | |
| 1153 | let lhs = ns.substring(with: m.range(at: 1)) | |
| 1154 | var rhs = ns.substring(with: m.range(at: 3)).trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | |
| 1155 | guard !rhs.isEmpty else { continue } | |
| 1156 | rhs = rhs.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression) | |
| 1157 | if result.contains(where: { $0.lhs == lhs }) { throw EmacsBuffer.UserError(message: "Double formulas for \(lhs)") } | |
| 1158 | result.insert((lhs, rhs), at: 0) | |
| 1159 | } | |
| 1160 | return result | |
| 1161 | } | |
| 1162 | ||
| 1163 | /// Installs edited formulas, as `org-table-fedit-finish` without a prefix argument. | |
| 1164 | func installFormulas(_ content: String, in context: EditContext) -> CommandStep { | |
| 1165 | let step = commitBuffer(context) { buffer in | |
| 1166 | let formulas = try Self.parseFormulas(content) | |
| 1167 | buffer.point = range.lowerBound | |
| 1168 | let analysis = try buffer.saveExcursion { () throws -> EmacsBuffer.TableAnalysis in | |
| 1169 | if !buffer.atTable { _ = buffer.searchBackward("^[ \\t]*\\|", caseInsensitive: false) } | |
| 1170 | return try buffer.tableAnalyze() | |
| 1171 | } | |
| 1172 | buffer.tableStoreFormulas(formulas, analysis: analysis) | |
| 1173 | } | |
| 1174 | guard case .commit(let result) = step else { return step } | |
| 1175 | return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, | |
| 1176 | effects: result.effects + [.message("New formulas installed - Recalculate Table (C-c C-c on the #+TBLFM line) applies them.")])) | |
| 1177 | } | |
| 1178 | } | |
| 1179 | ||
| 1180 | // `org-table-edit-field` (C-c `): a field's text edited apart, then put back. | |
| 1181 | extension BlockEdit { | |
| 1182 | static let fieldKind = "field" | |
| 1183 | ||
| 1184 | /// The data field at `offset`, trimmed. The range is its line, to check it's unchanged. | |
| 1185 | public static func field(at offset: Int, text: String) -> BlockEdit? { | |
| 1186 | let buffer = EmacsBuffer(text, point: offset) | |
| 1187 | guard buffer.insideDataField else { return nil } | |
| 1188 | let coordinate = "@\(buffer.tableCurrentDataLine())$\(buffer.tableCurrentColumn())" | |
| 1189 | let field = buffer.saveExcursion { () -> String in | |
| 1190 | buffer.skipBackwardNot([124, 10]) | |
| 1191 | return buffer.substring(buffer.point, buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound) | |
| 1192 | } | |
| 1193 | let start = buffer.lineStart(offset) | |
| 1194 | let end = buffer.lineEnd(offset) | |
| 1195 | return BlockEdit(range: start..<end, original: buffer.substring(start, end), content: field.trimmingCharacters(in: .whitespacesAndNewlines), | |
| 1196 | language: nil, kind: fieldKind, point: offset, coordinate: coordinate) | |
| 1197 | } | |
| 1198 | ||
| 1199 | /// `org-table-finish-edit-field`: comment lines go, line breaks become spaces, and the | |
| 1200 | /// table is aligned. | |
| 1201 | func installField(_ content: String, in context: EditContext) -> CommandStep { | |
| 1202 | var text = content.replacingOccurrences(of: "(?m)^#.*\n?", with: "", options: .regularExpression) | |
| 1203 | text = text.replacingOccurrences(of: "[ \t]*\n[ \t\n]*", with: " ", options: .regularExpression) | |
| 1204 | text = text.trimmingCharacters(in: .whitespacesAndNewlines) | |
| 1205 | return commitBuffer(context) { buffer in | |
| 1206 | buffer.point = point ?? range.lowerBound | |
| 1207 | guard buffer.insideDataField else { throw EmacsBuffer.UserError(message: "Not in table data field") } | |
| 1208 | buffer.skipBackwardNot([124, 10]) | |
| 1209 | let end = buffer.looking("[^|\\r\\n]*", caseInsensitive: false, setsMatch: false)![0]!.upperBound | |
| 1210 | buffer.replaceRange(buffer.point, end, with: text.isEmpty ? " " : text) | |
| 1211 | buffer.point = min(buffer.lineEnd(buffer.point), buffer.point + 1) | |
| 1212 | buffer.tableAlign() | |
| 1213 | } | |
| 1214 | } | |
| 1215 | } | |
| 1216 | ||
| 1217 | extension EmacsBuffer { | |
| 1218 | /// `org-table-check-inside-data-field` with NOERROR. | |
| 1219 | var insideDataField: Bool { | |
| 1220 | atTable && !atTableHline | |
| 1221 | && !saveExcursion { () -> Bool in | |
| 1222 | while let c = character(at: point - 1), c == 32 || c == 9 { point -= 1 } | |
| 1223 | return bolp | |
| 1224 | } | |
| 1225 | && looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil | |
| 1226 | } | |
| 1227 | } | |
| 1228 | ||
| 1229 | /// C-c `: `org-table-edit-field`, in the block editor. | |
| 1230 | public struct TableEditField: OrgCommand { | |
| 1231 | public init() {} | |
| 1232 | public var id: String { "org.table.edit-field" } | |
| 1233 | public var title: String { "Edit Table Field" } | |
| 1234 | public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) } | |
| 1235 | public func run(in context: EditContext) -> CommandStep { | |
| 1236 | guard let edit = BlockEdit.field(at: context.caret, text: context.text) else { | |
| 1237 | return .failed(EmacsBuffer(context.text, point: context.caret).atTable ? "Not in table data field" : "Not at a table") | |
| 1238 | } | |
| 1239 | return .external(.editBlock(edit)) | |
| 1240 | } | |
| 1241 | } | |