Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/EditorTables.swift3// Description: Table editing: rows, columns, merging and splitting cells, cell formatting, sorting and cell formulas.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public extension DocumentEditor {10 /// The table the selection is in, with the selected rows and grid columns.11 var tableSelection: (block: Int, rows: ClosedRange<Int>, columns: ClosedRange<Int>)? {12 let b = blocks13 switch target {14 case .cells(let bi, let rows, let cols): return (bi, rows, cols)15 case .caret(let p), .range(let p, _):16 guard let c = p.path.cell, let t = b[p.path.block].table else { return nil }17 let g = DocumentEditor.gridStart(t.rows[c.row], cell: c.cell)18 return (p.path.block, c.row...c.row, g...(g + t.rows[c.row].cells[c.cell].colSpan - 1))19 }20 }2122 var currentTable: Table? { tableSelection.flatMap { blocks[$0.block].table } }2324 mutating func insertTable(rows: Int, columns: Int, width: Points, style: TableStyle = .grid) {25 insertBlock(.table(Table(rows: rows, columns: columns, width: width, style: style)))26 }2728 /// Applies a change to the table under the selection and keeps the selection valid.29 mutating func mutateTable(_ change: (inout Table) -> Void) {30 guard let sel = tableSelection else { return }31 var b = blocks32 guard var t = b[sel.block].table else { return }33 change(&t)34 if t.rows.isEmpty || t.columnWidths.isEmpty {35 b.remove(at: sel.block)36 if b.isEmpty || b.last?.paragraph == nil { b.append(.paragraph(Paragraph())) }37 } else {38 b[sel.block] = .table(t)39 }40 blocks = b41 sanitizeSelection()42 }4344 private static func emptyCell(like c: TableCell) -> TableCell {45 var n = TableCell(paragraphs: [Paragraph(style: c.paragraphs.first?.style ?? StyleID.tableText, props: c.paragraphs.first?.props ?? .none)], colSpan: c.colSpan, vAlign: c.vAlign)46 n.borderTop = c.borderTop; n.borderBottom = c.borderBottom; n.borderLeft = c.borderLeft; n.borderRight = c.borderRight47 return n48 }4950 mutating func insertRow(below: Bool) {51 guard let sel = tableSelection else { return }52 let ref = below ? sel.rows.upperBound : sel.rows.lowerBound53 mutateTable { t in54 var row = TableRow(cells: t.rows[ref].cells.map { DocumentEditor.emptyCell(like: $0) })55 // A new row inside a vertical merge continues it.56 let at = below ? ref + 1 : ref57 if at < t.rows.count, at > 0 {58 for (i, c) in t.rows[at].cells.enumerated() where c.vMerge == .continue && i < row.cells.count { row.cells[i].vMerge = .continue }59 }60 t.rows.insert(row, at: at)61 }62 if below, var c = selection.head.path.cell {63 c = CellPath(row: ref + 1, cell: min(c.cell, (currentTable?.rows[ref + 1].cells.count ?? 1) - 1))64 selection = Selection(story: selection.story, caret: Position(path: ParaPath(block: sel.block, cell: c), offset: 0))65 }66 sanitizeSelection()67 }6869 mutating func insertColumn(after: Bool) {70 guard let sel = tableSelection else { return }71 let g = after ? sel.columns.upperBound + 1 : sel.columns.lowerBound // new grid column index72 mutateTable { t in73 let total = t.totalWidth74 let refWidth = t.columnWidths[max(0, min(t.columnWidths.count - 1, after ? g - 1 : g))]75 t.columnWidths.insert(refWidth, at: min(g, t.columnWidths.count))76 let scale = total / t.totalWidth77 t.columnWidths = t.columnWidths.map { $0 * scale }78 for r in t.rows.indices {79 var grid = 080 var inserted = false81 for ci in t.rows[r].cells.indices {82 let span = t.rows[r].cells[ci].colSpan83 if g > grid && g < grid + span {84 t.rows[r].cells[ci].colSpan += 1 // the new column falls inside a merged cell85 inserted = true86 break87 }88 if g == grid {89 var n = DocumentEditor.emptyCell(like: t.rows[r].cells[ci])90 n.colSpan = 191 n.vMerge = .none92 t.rows[r].cells.insert(n, at: ci)93 inserted = true94 break95 }96 grid += span97 }98 if !inserted {99 var n = t.rows[r].cells.last.map { DocumentEditor.emptyCell(like: $0) } ?? TableCell()100 n.colSpan = 1101 t.rows[r].cells.append(n)102 }103 }104 }105 }106107 mutating func deleteRows() {108 guard let sel = tableSelection else { return }109 mutateTable { t in110 // A vertical merge whose first row disappears restarts on the next remaining row.111 let next = sel.rows.upperBound + 1112 if next < t.rows.count {113 for ci in t.rows[next].cells.indices where t.rows[next].cells[ci].vMerge == .continue {114 let g = DocumentEditor.gridStart(t.rows[next], cell: ci)115 let startsInRemoved = sel.rows.contains { r in116 DocumentEditor.cells(in: t.rows[r], columns: g...g).contains { t.rows[r].cells[$0].vMerge == .restart }117 }118 if startsInRemoved {119 let continues = next + 1 < t.rows.count && DocumentEditor.cells(in: t.rows[next + 1], columns: g...g).contains { t.rows[next + 1].cells[$0].vMerge == .continue }120 t.rows[next].cells[ci].vMerge = continues ? .restart : .none121 }122 }123 }124 t.rows.removeSubrange(sel.rows)125 }126 }127128 mutating func deleteColumns() {129 guard let sel = tableSelection else { return }130 mutateTable { t in131 for g in sel.columns.reversed() where g < t.columnWidths.count {132 for r in t.rows.indices {133 var grid = 0134 for ci in t.rows[r].cells.indices {135 let span = t.rows[r].cells[ci].colSpan136 if g >= grid && g < grid + span {137 if span > 1 { t.rows[r].cells[ci].colSpan -= 1 } else { t.rows[r].cells.remove(at: ci) }138 break139 }140 grid += span141 }142 }143 t.columnWidths.remove(at: g)144 }145 t.rows.removeAll { $0.cells.isEmpty }146 }147 }148149 mutating func deleteTable() {150 guard let sel = tableSelection else { return }151 var b = blocks152 b.remove(at: sel.block)153 if b.isEmpty || b.last?.paragraph == nil { b.append(.paragraph(Paragraph())) }154 blocks = b155 selection = Selection(story: selection.story, caret: DocumentEditor.firstPosition(inBlock: min(sel.block, b.count - 1), b))156 }157158 /// Merges the selected rectangle of cells into one. Returns false when there is nothing to merge.159 @discardableResult160 mutating func mergeCells() -> Bool {161 guard let sel = tableSelection, case .cells = target else { return false }162 var merged = false163 mutateTable { t in164 var gathered: [Paragraph] = []165 var topCell: Int?166 for r in sel.rows {167 let idx = DocumentEditor.cells(in: t.rows[r], columns: sel.columns)168 guard let first = idx.first else { continue }169 var cell = t.rows[r].cells[first]170 cell.colSpan = idx.reduce(0) { $0 + t.rows[r].cells[$1].colSpan }171 for i in idx { gathered.append(contentsOf: t.rows[r].cells[i].paragraphs.filter { !$0.isEmpty }) }172 cell.formula = nil173 if r == sel.rows.lowerBound {174 topCell = first175 cell.vMerge = sel.rows.count > 1 ? .restart : cell.vMerge176 } else {177 cell.vMerge = .continue178 cell.paragraphs = [Paragraph(style: cell.paragraphs.first?.style ?? StyleID.tableText)]179 }180 t.rows[r].cells.replaceSubrange(first...(idx.last ?? first), with: [cell])181 merged = true182 }183 if let tc = topCell {184 let style = t.rows[sel.rows.lowerBound].cells[tc].paragraphs.first?.style ?? StyleID.tableText185 t.rows[sel.rows.lowerBound].cells[tc].paragraphs = gathered.isEmpty ? [Paragraph(style: style)] : gathered186 }187 }188 if merged {189 let t = currentTable190 let ci = t.map { DocumentEditor.cells(in: $0.rows[sel.rows.lowerBound], columns: sel.columns.lowerBound...sel.columns.lowerBound).first ?? 0 } ?? 0191 selection = Selection(story: selection.story, caret: Position(path: ParaPath(block: sel.block, cell: CellPath(row: sel.rows.lowerBound, cell: ci)), offset: 0))192 sanitizeSelection()193 }194 return merged195 }196197 /// Splits the cell under the caret: undoes its merges, or cuts an unmerged cell into two columns.198 mutating func splitCell() {199 guard let sel = tableSelection, let c = selection.start.path.cell else { return }200 mutateTable { t in201 let cell = t.rows[c.row].cells[c.cell]202 let g = DocumentEditor.gridStart(t.rows[c.row], cell: c.cell)203 if cell.colSpan > 1 || cell.vMerge == .restart {204 // Undo the vertical merge below, then the horizontal one.205 if cell.vMerge == .restart {206 t.rows[c.row].cells[c.cell].vMerge = .none207 var r = c.row + 1208 while r < t.rows.count, let ci = DocumentEditor.cells(in: t.rows[r], columns: g...g).first, t.rows[r].cells[ci].vMerge == .continue {209 t.rows[r].cells[ci].vMerge = .none210 r += 1211 }212 }213 if cell.colSpan > 1 {214 var first = t.rows[c.row].cells[c.cell]215 first.colSpan = 1216 let extra = (1..<cell.colSpan).map { _ -> TableCell in var n = DocumentEditor.emptyCell(like: first); n.colSpan = 1; return n }217 t.rows[c.row].cells.replaceSubrange(c.cell...c.cell, with: [first] + extra)218 }219 return220 }221 // Plain cell: add a grid column; the other rows span it.222 let w = t.columnWidths[g] / 2223 t.columnWidths[g] = w224 t.columnWidths.insert(w, at: g + 1)225 for r in t.rows.indices {226 guard let ci = DocumentEditor.cells(in: t.rows[r], columns: g...g).first else { continue }227 if r == c.row {228 var n = DocumentEditor.emptyCell(like: t.rows[r].cells[ci]); n.colSpan = 1229 t.rows[r].cells.insert(n, at: ci + 1)230 } else {231 t.rows[r].cells[ci].colSpan += 1232 }233 }234 }235 }236237 /// Applies a change to every selected cell (shading, borders, vertical alignment).238 mutating func formatCells(_ change: (inout TableCell) -> Void) {239 guard let sel = tableSelection else { return }240 mutateTable { t in241 for r in sel.rows { for ci in DocumentEditor.cells(in: t.rows[r], columns: sel.columns) { change(&t.rows[r].cells[ci]) } }242 }243 }244245 /// Drags the boundary after grid column `column`: that column takes `width` and its right neighbour absorbs the difference.246 mutating func resizeColumn(block: Int, column: Int, width: Points) {247 var b = blocks248 guard var t = b[block].table, t.columnWidths.indices.contains(column) else { return }249 let minW: Points = 18250 if column + 1 < t.columnWidths.count {251 let pair = t.columnWidths[column] + t.columnWidths[column + 1]252 let w = max(minW, min(pair - minW, width))253 t.columnWidths[column] = w254 t.columnWidths[column + 1] = pair - w255 } else {256 t.columnWidths[column] = max(minW, width)257 }258 b[block] = .table(t)259 blocks = b260 }261262 /// Tab in a table: next cell (a new row is added after the last cell). Returns false outside tables.263 @discardableResult264 mutating func moveToAdjacentCell(backward: Bool) -> Bool {265 guard let c = selection.head.path.cell, let t = blocks[selection.head.path.block].table else { return false }266 let bi = selection.head.path.block267 var row = c.row, cell = c.cell268 if backward {269 if cell > 0 { cell -= 1 } else if row > 0 { row -= 1; cell = t.rows[row].cells.count - 1 } else { return true }270 } else {271 if cell + 1 < t.rows[row].cells.count { cell += 1 } else if row + 1 < t.rows.count { row += 1; cell = 0 } else {272 insertRow(below: true)273 row += 1; cell = 0274 }275 }276 guard let nt = blocks[bi].table else { return true }277 let paras = nt.rows[row].cells[cell].paragraphs278 // Select the content of the destination cell, as word processors do.279 selection = Selection(story: selection.story,280 anchor: Position(path: ParaPath(block: bi, cell: CellPath(row: row, cell: cell, paragraph: 0)), offset: 0),281 head: Position(path: ParaPath(block: bi, cell: CellPath(row: row, cell: cell, paragraph: paras.count - 1)), offset: paras[paras.count - 1].length))282 return true283 }284285 /// Sorts the body rows by the text (or numeric value) of a grid column. Refused (false) when the table has vertical merges.286 @discardableResult287 mutating func sortRows(byGridColumn g: Int, ascending: Bool, numeric: Bool) -> Bool {288 guard let t = currentTable, !t.rows.contains(where: { $0.cells.contains { $0.vMerge != .none } }) else { return false }289 let locale = Locale(identifier: doc.meta.language)290 mutateTable { t in291 let headers = t.rows.filter(\.isHeader)292 let body = t.rows.filter { !$0.isHeader }293 func key(_ row: TableRow) -> String { DocumentEditor.cells(in: row, columns: g...g).first.map { row.cells[$0].plainText } ?? "" }294 let sorted = body.enumerated().sorted { a, b in295 let ka = key(a.element), kb = key(b.element)296 if numeric {297 let na = TableFormula.number(from: ka), nb = TableFormula.number(from: kb)298 switch (na, nb) {299 case let (x?, y?) where x != y: return ascending ? x < y : x > y300 case (_?, nil): return true301 case (nil, _?): return false302 default: break303 }304 } else {305 let cmp = ka.compare(kb, options: [.caseInsensitive, .diacriticInsensitive, .numeric], locale: locale)306 if cmp != .orderedSame { return ascending ? cmp == .orderedAscending : cmp == .orderedDescending }307 }308 return a.offset < b.offset // stable309 }.map(\.element)310 t.rows = headers + sorted311 }312 return true313 }314315 /// Sets (or clears) the formula of the cell under the caret and recalculates the table.316 mutating func setCellFormula(_ formula: String?) {317 guard let c = selection.start.path.cell else { return }318 mutateTable { t in319 t.rows[c.row].cells[c.cell].formula = (formula?.isEmpty ?? true) ? nil : formula320 TableFormula.recalculate(&t)321 }322 }323324 mutating func recalculateTable() { mutateTable { TableFormula.recalculate(&$0) } }325326 /// Recalculates the formulas of every table in the document.327 mutating func recalculateAllTables() {328 for i in doc.body.indices {329 if case .table(var t) = doc.body[i], t.rows.contains(where: { $0.cells.contains { $0.formula != nil } }) {330 TableFormula.recalculate(&t)331 doc.body[i] = .table(t)332 }333 }334 }335}336337/// Cell formulas: `=SUM(ABOVE)`, `=AVERAGE(LEFT)`, `=B2*C2`, `=SUM(A1:A4)/2`. Functions: SUM, AVERAGE, MIN, MAX, COUNT, PRODUCT.338/// Columns are grid columns (A = first), rows are 1-based.339public enum TableFormula {340 /// Parses a number as people type it: "1,234.50", "1 234,50", "(120)", "$45", "12 %".341 public static func number(from text: String) -> Double? {342 var s = text.trimmingCharacters(in: .whitespacesAndNewlines)343 guard !s.isEmpty else { return nil }344 var negative = false345 if s.hasPrefix("("), s.hasSuffix(")") { negative = true; s = String(s.dropFirst().dropLast()) }346 s = s.replacingOccurrences(of: "\u{00A0}", with: "").replacingOccurrences(of: "\u{202F}", with: "").replacingOccurrences(of: " ", with: "")347 for sym in ["$", "€", "£", "¥", "%", "CAD", "USD", "EUR"] { s = s.replacingOccurrences(of: sym, with: "") }348 s = s.replacingOccurrences(of: "−", with: "-")349 if s.hasPrefix("-") { negative.toggle(); s.removeFirst() }350 guard !s.isEmpty, s.allSatisfy({ $0.isNumber || $0 == "." || $0 == "," }) else { return nil }351 let commas = s.filter { $0 == "," }.count, dots = s.filter { $0 == "." }.count352 if commas > 0 && dots > 0 {353 if s.lastIndex(of: ",")! > s.lastIndex(of: ".")! { s = s.replacingOccurrences(of: ".", with: "").replacingOccurrences(of: ",", with: ".") }354 else { s = s.replacingOccurrences(of: ",", with: "") }355 } else if commas == 1 {356 let frac = s[s.index(after: s.firstIndex(of: ",")!)...]357 s = frac.count == 3 && s.count > 4 ? s.replacingOccurrences(of: ",", with: "") : s.replacingOccurrences(of: ",", with: ".")358 } else if commas > 1 {359 s = s.replacingOccurrences(of: ",", with: "")360 } else if dots > 1 {361 s = s.replacingOccurrences(of: ".", with: "")362 }363 guard let v = Double(s) else { return nil }364 return negative ? -v : v365 }366367 static func decimals(in text: String) -> Int {368 let s = text.trimmingCharacters(in: CharacterSet(charactersIn: " \u{00A0}%$€£)"))369 guard let i = s.lastIndex(where: { $0 == "." || $0 == "," }) else { return 0 }370 let frac = s[s.index(after: i)...]371 return frac.allSatisfy(\.isNumber) && frac.count != 3 ? frac.count : (frac.count == 3 && s.filter({ $0 == "," || $0 == "." }).count == 1 && s.count <= 5 ? 3 : 0)372 }373374 /// Values of the grid cells in a rectangle, skipping non-numeric and merged-continuation cells.375 static func values(_ t: Table, rows: ClosedRange<Int>, columns: ClosedRange<Int>, stats: inout Stats) -> [Double] {376 var out: [Double] = []377 for r in rows where t.rows.indices.contains(r) {378 for ci in DocumentEditor.cells(in: t.rows[r], columns: columns) where t.rows[r].cells[ci].vMerge != .continue {379 let text = t.rows[r].cells[ci].plainText380 if let v = number(from: text) {381 out.append(v)382 stats.decimals = max(stats.decimals, decimals(in: text))383 if text.contains(",") && !text.contains(".") && decimals(in: text) > 0 { stats.commaDecimal = true }384 }385 }386 }387 return out388 }389390 struct Stats { var decimals = 0; var commaDecimal = false; var divided = false }391392 /// Evaluates the formula of the cell at (`row`, `cell`). nil when it cannot be evaluated.393 public static func evaluate(_ formula: String, in t: Table, row: Int, cell: Int) -> String? {394 var stats = Stats()395 var parser = Parser(text: formula.hasPrefix("=") ? String(formula.dropFirst()) : formula, table: t, row: row, grid: DocumentEditor.gridStart(t.rows[row], cell: cell))396 guard let v = parser.parseExpression(), parser.atEnd, v.isFinite else { return nil }397 stats = parser.stats398 let decimals = stats.divided && stats.decimals == 0 ? 2 : min(6, stats.decimals)399 let f = NumberFormatter()400 f.numberStyle = .decimal401 f.minimumFractionDigits = decimals402 f.maximumFractionDigits = decimals403 f.usesGroupingSeparator = abs(v) >= 10_000404 f.decimalSeparator = stats.commaDecimal ? "," : "."405 f.groupingSeparator = stats.commaDecimal ? "\u{00A0}" : ","406 return f.string(from: NSNumber(value: v))407 }408409 /// Recomputes every formula cell (two passes so a total of totals settles) and writes the result as the cell text.410 public static func recalculate(_ t: inout Table) {411 for _ in 0..<2 {412 for r in t.rows.indices {413 for ci in t.rows[r].cells.indices {414 guard let f = t.rows[r].cells[ci].formula else { continue }415 let result = evaluate(f, in: t, row: r, cell: ci) ?? "#ERR"416 var p = t.rows[r].cells[ci].paragraphs.first ?? Paragraph(style: StyleID.tableText)417 let props = p.runs.first?.props ?? .none418 p.runs = [Run(result, props: props)]419 t.rows[r].cells[ci].paragraphs = [p]420 }421 }422 }423 }424425 struct Parser {426 let chars: [Character]427 var i = 0428 let table: Table429 let row: Int430 let grid: Int431 var stats = Stats()432433 init(text: String, table: Table, row: Int, grid: Int) { chars = Array(text.uppercased()); self.table = table; self.row = row; self.grid = grid }434435 var atEnd: Bool { mutating get { skipSpaces(); return i >= chars.count } }436 mutating func skipSpaces() { while i < chars.count, chars[i] == " " { i += 1 } }437 mutating func eat(_ c: Character) -> Bool { skipSpaces(); if i < chars.count, chars[i] == c { i += 1; return true }; return false }438439 mutating func parseExpression() -> Double? {440 guard var v = parseTerm() else { return nil }441 while true {442 if eat("+") { guard let r = parseTerm() else { return nil }; v += r }443 else if eat("-") { guard let r = parseTerm() else { return nil }; v -= r }444 else { return v }445 }446 }447448 mutating func parseTerm() -> Double? {449 guard var v = parseFactor() else { return nil }450 while true {451 if eat("*") { guard let r = parseFactor() else { return nil }; v *= r }452 else if eat("/") { guard let r = parseFactor(), r != 0 else { return nil }; v /= r; stats.divided = true }453 else { return v }454 }455 }456457 mutating func parseFactor() -> Double? {458 skipSpaces()459 if eat("-") { return parseFactor().map { -$0 } }460 if eat("(") { let v = parseExpression(); return eat(")") ? v : nil }461 guard i < chars.count else { return nil }462 if chars[i].isNumber || chars[i] == "." {463 var s = ""464 while i < chars.count, chars[i].isNumber || chars[i] == "." { s.append(chars[i]); i += 1 }465 if let dot = s.firstIndex(of: ".") { stats.decimals = max(stats.decimals, s.distance(from: dot, to: s.endIndex) - 1) }466 return Double(s)467 }468 var word = ""469 while i < chars.count, chars[i].isLetter { word.append(chars[i]); i += 1 }470 guard !word.isEmpty else { return nil }471 if eat("(") {472 var values: [Double] = []473 repeat {474 guard let part = parseArgument() else { return nil }475 values.append(contentsOf: part)476 } while eat(",") || eat(";")477 guard eat(")") else { return nil }478 switch word {479 case "SUM": return values.reduce(0, +)480 case "PRODUCT": return values.isEmpty ? 0 : values.reduce(1, *)481 case "AVERAGE", "MOYENNE": stats.divided = true; return values.isEmpty ? nil : values.reduce(0, +) / Double(values.count)482 case "MIN": return values.min()483 case "MAX": return values.max()484 case "COUNT": stats.decimals = 0; return Double(values.count)485 default: return nil486 }487 }488 // Cell reference like B12.489 var digits = ""490 while i < chars.count, chars[i].isNumber { digits.append(chars[i]); i += 1 }491 guard let r = Int(digits), let col = column(word) else { return nil }492 return TableFormula.values(table, rows: (r - 1)...(r - 1), columns: col...col, stats: &stats).first ?? 0493 }494495 func column(_ letters: String) -> Int? {496 guard !letters.isEmpty, letters.count <= 2 else { return nil }497 var n = 0498 for ch in letters.unicodeScalars { guard ch.value >= 65, ch.value <= 90 else { return nil }; n = n * 26 + Int(ch.value - 64) }499 return n - 1500 }501502 /// A function argument: a direction keyword, a range A1:B3, or any expression.503 mutating func parseArgument() -> [Double]? {504 skipSpaces()505 let save = i506 var word = ""507 while i < chars.count, chars[i].isLetter { word.append(chars[i]); i += 1 }508 let lastCol = max(0, table.columnCount - 1)509 switch word {510 case "ABOVE", "DESSUS": return row > 0 ? TableFormula.values(table, rows: 0...(row - 1), columns: grid...grid, stats: &stats) : []511 case "BELOW", "DESSOUS": return row + 1 < table.rows.count ? TableFormula.values(table, rows: (row + 1)...(table.rows.count - 1), columns: grid...grid, stats: &stats) : []512 case "LEFT", "GAUCHE": return grid > 0 ? TableFormula.values(table, rows: row...row, columns: 0...(grid - 1), stats: &stats) : []513 case "RIGHT", "DROITE": return grid < lastCol ? TableFormula.values(table, rows: row...row, columns: (grid + 1)...lastCol, stats: &stats) : []514 default: break515 }516 // Range?517 var digits = ""518 while i < chars.count, chars[i].isNumber { digits.append(chars[i]); i += 1 }519 if let r1 = Int(digits), let c1 = column(word), eat(":") {520 var w2 = "", d2 = ""521 while i < chars.count, chars[i].isLetter { w2.append(chars[i]); i += 1 }522 while i < chars.count, chars[i].isNumber { d2.append(chars[i]); i += 1 }523 guard let r2 = Int(d2), let c2 = column(w2) else { return nil }524 return TableFormula.values(table, rows: (min(r1, r2) - 1)...(max(r1, r2) - 1), columns: min(c1, c2)...max(c1, c2), stats: &stats)525 }526 i = save527 return parseExpression().map { [$0] }528 }529 }530}531