Sources/OrgCore/Commands/Table.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Commands/Table.swift history · blame · raw

757 lines · 32483 bytes

46 symbols in this file
  1import Foundation
  2
  3// Org tables (org-table.el, Org 9.8.7): alignment and the editing commands, with
  4// `org-table-automatic-realign` t, `org-table-tab-jumps-over-hlines` t,
  5// `org-table-fix-formulas-confirm` nil (formulas are fixed silently). Shrunk columns are only
  6// drawn (`TableShrink`); these commands see the full text.
  7
  8extension EmacsBuffer {
  9    static let numberPattern = "^([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$"
 10
 11    /// `org-at-table-p`: an org table line outside blocks.
 12    var atTable: Bool {
 13        guard lookingAtLine("^[ \\t]*\\|") else { return false }
 14        // Dynamic blocks hold elements in Org; their tables count.
 15        let kind = element(at: lineStart(point))?.kind
 16        return kind == .table || kind == .tableRow || kind == .dynamicBlock
 17    }
 18
 19    var atTableHline: Bool { lookingAtLine("^[ \\t]*\\|-") }
 20
 21    func lookingAtLine(_ pattern: String) -> Bool {
 22        saveExcursion {
 23            beginningOfLine()
 24            return looking(pattern, caseInsensitive: false, setsMatch: false) != nil
 25        }
 26    }
 27
 28    /// `org-table-begin`.
 29    func tableBegin() -> Int {
 30        saveExcursion {
 31            searchBackward("^[ \\t]*[^| \\t]", caseInsensitive: false).map { _ in lineEnd(point) + 1 } ?? 0
 32        }
 33    }
 34
 35    /// `org-table-end`.
 36    func tableEnd() -> Int {
 37        saveExcursion {
 38            if let match = searchForward("^[ \\t]*[^| \\t]", caseInsensitive: false) { return match[0]!.lowerBound }
 39            point = length
 40            skipBackward(Self.blanks)
 41            return bolp ? point : lineEnd(point)
 42        }
 43    }
 44
 45    /// `org-table-to-lisp`: rows of trimmed fields, nil for rules.
 46    func tableToLisp() -> [[String]?] {
 47        saveExcursion {
 48            point = tableBegin()
 49            var table: [[String]?] = []
 50            while true {
 51                skipForward(Self.blanks)
 52                guard character(at: point) == 124 else { break }
 53                point += 1
 54                if character(at: point) == 45 {
 55                    table.append(nil)
 56                } else {
 57                    var row: [String] = []
 58                    while true {
 59                        skipForward(Self.blanks)
 60                        if eolp { break }
 61                        let start = point
 62                        while let c = character(at: point), c != 124, c != 10 { point += 1 }
 63                        let next = eolp ? point : point + 1
 64                        skipBackward(Self.blanks, bound: start)
 65                        row.append(substring(start, point))
 66                        point = next
 67                    }
 68                    table.append(row)
 69                }
 70                if forwardLine(1) != 0 { break }
 71            }
 72            return table
 73        }
 74    }
 75
 76    /// `org-string-width` of a cell as Emacs shows it.
 77    func cellWidth(_ cell: String) -> Int {
 78        VisibleLine(cell, options: options, settings: settings).width
 79    }
 80
 81    /// `org-table--align-field`.
 82    func alignField(_ field: String, width: Int, alignment: Character, fieldWidth: Int) -> String {
 83        let spaces = width - fieldWidth
 84        let prefix: Int
 85        switch alignment {
 86        case "r": prefix = spaces
 87        case "c": prefix = spaces / 2
 88        default: prefix = 0
 89        }
 90        return " " + String(repeating: " ", count: prefix) + field + String(repeating: " ", count: spaces - prefix) + " "
 91    }
 92
 93    /// `org-table-align`, keeping point in the same field.
 94    func tableAlign() {
 95        let begin = tableBegin()
 96        let end = marker(tableEnd())
 97        defer { release(end) }
 98        let line = marker(lineStart(point))
 99        defer { release(line) }
100        let column = tableCurrentColumn()
101        point = begin
102        let table = tableToLisp()
103        let rows = table.compactMap { $0 }
104        var widths: [Int] = []
105        var alignments: [Character] = []
106        var widthCache: [String: Int] = [:]
107        func width(_ cell: String) -> Int {
108            if let cached = widthCache[cell] { return cached }
109            let value = cellWidth(cell)
110            widthCache[cell] = value
111            return value
112        }
113        let numberRegex = Self.regex(Self.numberPattern, caseInsensitive: false)
114        var columns = 1
115        if rows.isEmpty {
116            let lineEndOffset = lineEnd(point)
117            columns += substring(point, lineEndOffset).filter { $0 == "+" }.count
118            widths = Array(repeating: 1, count: columns)
119            alignments = Array(repeating: "l", count: columns)
120        } else {
121            columns = rows.map(\.count).max() ?? 1
122            for i in 0..<columns {
123                var maxWidth = 1
124                var fixed: Character?
125                var numbers = 0, nonEmpty = 0
126                for row in rows {
127                    let cell = i < row.count ? row[i] : ""
128                    maxWidth = max(maxWidth, width(cell))
129                    if fixed != nil || cell.isEmpty { continue }
130                    if let cookie = cell.firstMatch(of: /^<([lrc])[0-9]*>$/) {
131                        fixed = cookie.1.first
132                    } else {
133                        nonEmpty += 1
134                        // `$` doesn't match before a CR in Emacs.
135                        if !cell.unicodeScalars.contains("\r"), numberRegex.firstMatch(in: cell, range: NSRange(location: 0, length: (cell as NSString).length)) != nil { numbers += 1 }
136                    }
137                }
138                widths.append(maxWidth)
139                alignments.append(fixed ?? (Double(numbers) >= 0.5 * Double(nonEmpty) ? "r" : "l"))
140            }
141        }
142        let rule = widths.map { String(repeating: "-", count: $0 + 2) }.joined(separator: "+")
143        let indent = looking("[ \\t]*\\|", setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) } ?? "|"
144        for row in table {
145            let previous = substring(point, lineEnd(point))
146            let new: String
147            if let row {
148                let fields = row + Array(repeating: "", count: max(0, columns - row.count))
149                new = indent + zip(fields, zip(widths, alignments)).map { field, spec in
150                    alignField(field, width: spec.0, alignment: spec.1, fieldWidth: width(field))
151                }.joined(separator: "|") + "|"
152            } else {
153                new = indent + rule + "|"
154            }
155            if new == previous {
156                forwardLine(1)
157            } else {
158                insert(new + "\n")
159                deleteRegion(point, min(length, lineEnd(point) + 1))
160            }
161        }
162        point = line.position
163        tableGotoColumn(column)
164    }
165
166    /// `org-table-current-column`.
167    func tableCurrentColumn() -> Int {
168        saveExcursion {
169            let pos = point
170            beginningOfLine()
171            let text = substring(point, pos)
172            guard let first = text.firstIndex(of: "|") else { return 0 }
173            let separators: Set<Character> = atTableHline ? ["+", "|"] : ["|"]
174            return 1 + text[text.index(after: first)...].filter { separators.contains($0) }.count
175        }
176    }
177
178    /// `org-table-goto-column`.
179    func tableGotoColumn(_ n: Int, onDelim: Bool = false, force: Bool = false) {
180        beginningOfLine()
181        guard n > 0 else { return }
182        var remaining = n
183        while remaining > 0 {
184            remaining -= 1
185            if let match = searchForward("\\|", bound: lineEnd(point), caseInsensitive: false) {
186                _ = match
187            } else if force {
188                endOfLine()
189                skipBackwardNot([124])
190                insert(" | ")
191            } else {
192                break
193            }
194        }
195        if force, looking(".*\\|", caseInsensitive: false, setsMatch: false) == nil {
196            saveExcursion {
197                endOfLine()
198                insert(" | ")
199            }
200        }
201        if onDelim {
202            point -= 1
203        } else if character(at: point) == 32 {
204            point += 1
205        }
206    }
207
208    /// `skip-chars-backward "^|"`.
209    func skipBackwardNot(_ set: Set<unichar>) {
210        while point > lineStart(point), let c = character(at: point - 1), !set.contains(c) { point -= 1 }
211    }
212
213    /// `org-table-current-dline`.
214    func tableCurrentDataLine() -> Int {
215        saveExcursion {
216            let pos = lineStart(point)
217            point = tableBegin()
218            var count = 0
219            while point <= pos {
220                if looking("^[ \\t]*\\|[^-]", caseInsensitive: false, setsMatch: false) != nil { count += 1 }
221                if forwardLine(1) != 0 { break }
222            }
223            return count
224        }
225    }
226
227    /// `org-table-clean-line`.
228    func cleanTableLine(_ line: String) -> String {
229        if line.range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil {
230            return String(line.map { $0 == "|" || $0 == "+" ? "|" : " " })
231        }
232        var result = line
233        let regex = try! NSRegularExpression(pattern: "\\|([ \\t]*?[^ \\t\\r\\n|][^\\r\\n|]*)\\|")
234        while let match = regex.firstMatch(in: result, range: NSRange(location: 0, length: (result as NSString).length)) {
235            let cell = (result as NSString).substring(with: match.range(at: 1))
236            result = (result as NSString).replacingCharacters(in: match.range, with: "|" + String(repeating: " ", count: cellWidth(cell)) + "|")
237        }
238        return result
239    }
240
241    /// `org-table-insert-row`; `below` as with a prefix argument.
242    func tableInsertRow(below: Bool) throws {
243        guard atTable else { throw UserError(message: "Not at a table") }
244        if eobp { saveExcursion { insert("\n") } }
245        if substring(lineStart(point), lineEnd(point)).range(of: "\\|[ \\t]*$", options: .regularExpression) == nil { tableAlign() }
246        let line = substring(lineStart(point), lineEnd(point))
247        var new = cleanTableLine(line)
248        if let match = line.range(of: "^[ \\t]*\\| *[#*$] *\\|", options: .regularExpression), let target = new.range(of: "^[ \\t]*\\| *[#*$] *\\|", options: .regularExpression) ?? new.range(of: "^[ \\t]*\\|[^|]*\\|", options: .regularExpression) {
249            new.replaceSubrange(target, with: line[match])
250        }
251        forwardLine(below ? 1 : 0)
252        if !bolp { insert("\n") }
253        insertBeforeMarkers(new + "\n")
254        forwardLine(-1)
255        searchForward("\\| ?", bound: lineEnd(point), caseInsensitive: false)
256        // `org-table-may-need-update' is set by any edit to a table, so org realigns here.
257        tableAlign()
258        fixFormulas("@", replace: [:], limit: tableCurrentDataLine() - 1, delta: 1)
259    }
260
261    /// `org-table-insert-hline`; `above` as with a prefix argument.
262    func tableInsertHline(above: Bool) throws {
263        guard atTable else { throw UserError(message: "Not at a table") }
264        if eobp { saveExcursion { insert("\n") } }
265        if substring(lineStart(point), lineEnd(point)).range(of: "\\|[ \\t]*$", options: .regularExpression) == nil { tableAlign() }
266        var line = cleanTableLine(substring(lineStart(point), lineEnd(point)))
267        let column = currentColumn
268        let regex = try! NSRegularExpression(pattern: "\\|( +)\\|")
269        while let match = regex.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) {
270            line = (line as NSString).replacingCharacters(in: match.range, with: "+" + String(repeating: "-", count: match.range(at: 1).length) + "|")
271        }
272        if let plus = line.firstIndex(of: "+") { line.replaceSubrange(plus...plus, with: "|") }
273        forwardLine(above ? 0 : 1)
274        insert(line + "\n")
275        forwardLine(above ? 0 : -2)
276        moveToColumn(column)
277    }
278
279    /// What `org-table-maybe-eval-formula` does to point: `org-table-get-field` leaves it one
280    /// character into the field.
281    func moveIntoField() {
282        skipBackwardNot([124, 10])
283        if bolp || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { return }
284        let start = point
285        point = min(lineEnd(point), start + 1)
286    }
287
288    /// Display columns of the bars of the table line at `start`, and of the `+` in a rule; nil
289    /// unless the line has the form `org-table-align` gives it: a bar at the end, a space on
290    /// each side of every field, and only dashes between the bars of a rule.
291    func tableSeparatorColumns(_ start: Int) -> [Int]? {
292        let line = substring(start, lineEnd(start))
293        guard line.hasSuffix("|") else { return nil }
294        let rule = line.drop { $0 == " " || $0 == "\t" }.hasPrefix("|-")
295        var columns: [Int] = []
296        var column = 0
297        var segment = ""
298        for c in line {
299            if c == "|" || rule && c == "+" {
300                if !columns.isEmpty {
301                    if rule {
302                        guard !segment.isEmpty, segment.allSatisfy({ $0 == "-" }) else { return nil }
303                    } else {
304                        guard segment.count >= 3, segment.first == " ", segment.last == " " else { return nil }
305                    }
306                }
307                column += cellWidth(segment)
308                columns.append(column)
309                column += 1
310                segment = ""
311            } else {
312                segment.append(c)
313            }
314        }
315        return columns
316    }
317
318    /// Whether the table line at point is aligned and its bars line up with the line above
319    /// (below, on the first line): no field of it changed width since the table was aligned.
320    /// A field at point that lost characters but still ends in two spaces gets its width back
321    /// first, as `org-delete-char` keeps it, leaving `org-table-may-need-update` alone.
322    func tableLineLinesUp() -> Bool {
323        let start = lineStart(point)
324        func isTableLine(_ offset: Int) -> Bool {
325            substring(offset, lineEnd(offset)).drop { $0 == " " || $0 == "\t" }.hasPrefix("|")
326        }
327        let reference: Int
328        if start > 0, isTableLine(lineStart(start - 1)) {
329            reference = lineStart(start - 1)
330        } else if lineEnd(start) < length, isTableLine(lineEnd(start) + 1) {
331            reference = lineEnd(start) + 1
332        } else {
333            return false
334        }
335        guard let mine = tableSeparatorColumns(start), let theirs = tableSeparatorColumns(reference), mine.count == theirs.count else { return false }
336        if mine == theirs { return true }
337        // The field at point lies between bars `column - 1` and `column`.
338        let column = tableCurrentColumn()
339        guard !atTableHline, column > 0, column < mine.count, mine[..<column] == theirs[..<column] else { return false }
340        let shift = mine[column] - theirs[column]
341        guard shift < 0, (column..<mine.count).allSatisfy({ mine[$0] - theirs[$0] == shift }) else { return false }
342        var bar = start
343        var bars = 0
344        while bar < lineEnd(start) {
345            if character(at: bar) == 124 {
346                if bars == column { break }
347                bars += 1
348            }
349            bar += 1
350        }
351        guard character(at: bar - 1) == 32, character(at: bar - 2) == 32 else { return false }
352        saveExcursion {
353            point = bar
354            insert(String(repeating: " ", count: -shift))
355        }
356        return true
357    }
358
359    /// `org-table-next-field`.
360    func tableNextField() throws {
361        let unchanged = (unchangedPrefix, unchangedSuffix)
362        try tableMaybeEvalFormula()
363        try tableMaybeRecalculateLine()
364        moveIntoField()
365        // `org-table-may-need-update`: Org realigns only after the buffer changed since the last
366        // alignment. Without that history, a line that still lines up stands for no change; a
367        // formula's result is a change.
368        if unchanged != (unchangedPrefix, unchangedSuffix) || !tableLineLinesUp() { tableAlign() }
369        let end = tableEnd()
370        if atTableHline { endOfLine() }
371        func toNextBar() -> Bool { searchForward("\\|", bound: end, caseInsensitive: false) != nil }
372        var ok = toNextBar()
373        if ok, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { ok = toNextBar() }
374        guard ok else {
375            try tableInsertRow(below: true)
376            return
377        }
378        if looking("-", caseInsensitive: false, setsMatch: false) != nil, let match = searchForward("^[ \\t]*\\|([^-])", bound: end, caseInsensitive: false) {
379            point = match[1]!.lowerBound
380        }
381        if looking("-", caseInsensitive: false, setsMatch: false) != nil {
382            forwardLine(-1)
383            try tableInsertRow(below: true)
384        } else if character(at: point) == 32 {
385            point += 1
386        }
387    }
388
389    /// `org-table-previous-field`.
390    func tablePreviousField() throws {
391        try tableMaybeRecalculateLine()
392        tableAlign()
393        if atTableHline { endOfLine() }
394        let start = tableBegin()
395        let origin = point
396        func back() -> Bool {
397            guard let match = searchBackward("\\|", bound: start, caseInsensitive: false) else { return false }
398            point = match[0]!.lowerBound
399            return true
400        }
401        var ok = back() && back()
402        while ok, looking("\\|(?:-|[ \\t]*$)", caseInsensitive: false, setsMatch: false) != nil { ok = back() }
403        guard ok else {
404            point = origin
405            throw UserError(message: "Cannot move to previous table field")
406        }
407        if let bar = looking("\\| ?", caseInsensitive: false, setsMatch: false) { point = bar[0]!.upperBound }
408    }
409
410    /// `org-table-next-row`.
411    func tableNextRow() throws {
412        try tableMaybeEvalFormula()
413        try tableMaybeRecalculateLine()
414        moveIntoField()
415        tableAlign()
416        let column = tableCurrentColumn()
417        forwardLine(1)
418        if !bolp { insert("\n") }
419        if !atTable || atTableHline {
420            forwardLine(-1)
421            try tableInsertRow(below: true)
422        }
423        tableGotoColumn(column)
424        skipBackwardNot([124, 10, 13])
425        if character(at: point) == 32 { point += 1 }
426    }
427
428    /// `org-table-move-row`.
429    func tableMoveRow(up: Bool) throws {
430        let column = currentColumn
431        let pos = point
432        let hline1 = atTableHline
433        let dline1 = tableCurrentDataLine()
434        let dline2 = dline1 + (up ? -1 : 1)
435        if up, lineStart(point) == 0 { throw UserError(message: "Cannot move row further") }
436        forwardLine(up ? -1 : 1)
437        if (!up && eobp) || !atTable {
438            point = pos
439            throw UserError(message: "Cannot move row further")
440        }
441        let hline2 = atTableHline
442        point = pos
443        let rowStart = lineStart(point)
444        let rowEnd = min(length, lineEnd(point) + 1)
445        let row = substring(rowStart, rowEnd)
446        deleteRegion(rowStart, rowEnd)
447        forwardLine(up ? -1 : 1)
448        if !bolp { insert("\n") }
449        insert(row)
450        if !bolp { insert("\n") }
451        forwardLine(-1)
452        moveToColumn(column)
453        if !hline1, !hline2 {
454            fixFormulas("@", replace: [String(dline1): String(dline2), String(dline2): String(dline1)])
455        }
456    }
457
458    /// `org-table-move-column`.
459    func tableMoveColumn(left: Bool) throws {
460        guard atTable else { throw UserError(message: "Not at a table") }
461        try findDataLine()
462        try checkInsideDataField()
463        let column = tableCurrentColumn()
464        let first = left ? column - 1 : column
465        let target = left ? column - 1 : column + 1
466        let begin = tableBegin()
467        let end = marker(tableEnd())
468        defer { release(end) }
469        if left, column == 1 { throw UserError(message: "Cannot move column further left") }
470        if !left, looking("[^|\\n]*\\|[^|\\n]*$", caseInsensitive: false, setsMatch: false) != nil { throw UserError(message: "Cannot move column further right") }
471        let line = marker(lineStart(point))
472        point = begin
473        while point < end.position {
474            if !atTableHline {
475                tableGotoColumn(first, onDelim: true)
476                if let match = looking("\\|([^|\\n]+)\\|([^|\\n]+)\\|", caseInsensitive: false, setsMatch: false) {
477                    let a = substring(match[1]!.lowerBound, match[1]!.upperBound)
478                    let b = substring(match[2]!.lowerBound, match[2]!.upperBound)
479                    replace(match[1]!.lowerBound..<match[2]!.upperBound, with: b + "|" + a)
480                }
481            }
482            if forwardLine(1) != 0 { break }
483        }
484        point = line.position
485        release(line)
486        tableGotoColumn(column)
487        tableGotoColumn(target)
488        tableAlign()
489        fixFormulas("$", replace: [String(column): String(target), String(target): String(column)])
490    }
491
492    /// `org-table-insert-column`.
493    func tableInsertColumn() throws {
494        guard atTable else { throw UserError(message: "Not at a table") }
495        if eobp { saveExcursion { insert("\n") } }
496        if substring(lineStart(point), lineEnd(point)).range(of: "\\|[ \\t]*$", options: .regularExpression) == nil { tableAlign() }
497        try findDataLine()
498        let column = max(1, tableCurrentColumn())
499        let begin = tableBegin()
500        let end = marker(tableEnd())
501        defer { release(end) }
502        saveExcursion {
503            point = begin
504            while point < end.position {
505                if !atTableHline {
506                    tableGotoColumn(column, onDelim: true)
507                    insert("|")
508                }
509                if forwardLine(1) != 0 { break }
510            }
511        }
512        tableGotoColumn(column)
513        tableAlign()
514        fixFormulas("$", replace: [:], limit: column - 1, delta: 1)
515    }
516
517    /// `org-table-delete-column`.
518    func tableDeleteColumn() throws {
519        guard atTable else { throw UserError(message: "Not at a table") }
520        try findDataLine()
521        if saveExcursion({ () -> Bool in skipForward(Self.blanks); return eolp }) {
522            if let match = searchBackward("\\|", caseInsensitive: false) { point = match[0]!.lowerBound }
523        }
524        try checkInsideDataField()
525        let column = tableCurrentColumn()
526        let begin = tableBegin()
527        let end = marker(tableEnd())
528        defer { release(end) }
529        let line = marker(lineStart(point))
530        point = begin
531        while point < end.position {
532            if !atTableHline {
533                tableGotoColumn(column, onDelim: true)
534                if let match = looking("\\|[^|\\n]+\\|", caseInsensitive: false, setsMatch: false) { replace(match[0]!, with: "|") }
535            }
536            if forwardLine(1) != 0 { break }
537        }
538        point = line.position
539        release(line)
540        tableGotoColumn(column)
541        tableAlign()
542        fixFormulas("$", replace: [String(column): "INVALID"], limit: column, delta: -1, remove: column)
543    }
544
545    /// `org-table-kill-row`.
546    func tableKillRow() throws {
547        guard atTable else { throw UserError(message: "Not at a table") }
548        let column = currentColumn
549        let dline = atTableHline ? nil : tableCurrentDataLine()
550        deleteRegion(lineStart(point), min(lineEnd(point) + 1, length))
551        if !atTable { forwardLine(-1) }
552        moveToColumn(column)
553        if let dline { fixFormulas("@", replace: [String(dline): "INVALID"], limit: dline, delta: -1, remove: dline) }
554    }
555
556    /// `org-table-find-dataline`.
557    func findDataLine() throws {
558        guard atTableHline else { return }
559        let column = currentColumn
560        let end = tableEnd()
561        forwardLine(1)
562        while point < end, atTableHline { forwardLine(1) }
563        if point >= end { throw UserError(message: "Cannot find data row for column operation") }
564        moveToColumn(column)
565    }
566
567    /// `org-table-check-inside-data-field`.
568    func checkInsideDataField() throws {
569        let atLineStart = saveExcursion { () -> Bool in skipBackward(Self.blanks); return bolp }
570        if atLineStart || atTableHline || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil {
571            throw UserError(message: "Not in table data field")
572        }
573    }
574
575    /// `org-table-fix-formulas`.
576    func fixFormulas(_ key: String, replace replacements: [String: String], limit: Int? = nil, delta: Int = 0, remove: Int? = nil) {
577        saveExcursion {
578            point = tableEnd()
579            while looking("[ \\t]*#\\+tblfm:", setsMatch: false) != nil {
580                if let remove {
581                    let pattern = key == "$" ? "(@[0-9]+)?\\$\(remove)=.*?(::|$)" : "@\(remove)\\$[0-9]+=.*?(::|$)"
582                    saveExcursion {
583                        while let match = searchForward(pattern, bound: lineEnd(point), caseInsensitive: false) {
584                            replace(match[0]!, with: "")
585                            point = match[0]!.lowerBound
586                        }
587                    }
588                }
589                let lineStartOffset = point
590                let pattern = NSRegularExpression.escapedPattern(for: key) + "([0-9]+)"
591                while let match = searchForward(pattern, bound: lineEnd(point), caseInsensitive: false) {
592                    let number = substring(match[1]!.lowerBound, match[1]!.upperBound)
593                    if let new = replacements[number] {
594                        replace(match[0]!, with: key + new)
595                    } else if let limit, let n = Int(number), n > limit {
596                        replace(match[0]!, with: key + String(n + delta))
597                    }
598                }
599                _ = lineStartOffset
600                if forwardLine(1) != 0 { break }
601            }
602        }
603    }
604
605    /// `org-table-create` with a size like `3x2`.
606    func tableCreate(_ size: String) throws {
607        let parts = size.split(separator: "x").map { $0.trimmingCharacters(in: .whitespaces) }
608        guard parts.count == 2, let columns = Int(parts[0]), let rows = Int(parts[1]) else { throw UserError(message: "Size must be like 5x2") }
609        let pos = point
610        let indent = String(repeating: " ", count: currentColumn)
611        let line = indent + "|" + String(repeating: "  |", count: columns) + "\n"
612        if substring(lineStart(point), point).allSatisfy({ $0 == " " || $0 == "\t" }) {
613            beginningOfLine()
614        } else {
615            insert("\n")
616        }
617        for _ in 0..<rows { insert(line) }
618        point = pos
619        if rows > 1 {
620            endOfLine()
621            insert("\n|-")
622            point = pos
623        }
624        tableAlign()
625    }
626}
627
628
629private func tableCommand(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
630    commitBuffer(context, body)
631}
632
633/// A table command that needs the caret in an org table.
634public struct TableCommand: OrgCommand {
635    public enum Action: String, Sendable, CaseIterable {
636        case align, nextField, previousField, nextRow, moveRowUp, moveRowDown, moveColumnLeft, moveColumnRight
637        case insertColumn, deleteColumn, killRow, insertRowAbove, insertHline
638    }
639
640    public let action: Action
641    public init(_ action: Action) { self.action = action }
642
643    public var id: String {
644        switch action {
645        case .align: "org.table.align"
646        case .nextField: "org.table.next-field"
647        case .previousField: "org.table.previous-field"
648        case .nextRow: "org.table.next-row"
649        case .moveRowUp: "org.table.row-up"
650        case .moveRowDown: "org.table.row-down"
651        case .moveColumnLeft: "org.table.column-left"
652        case .moveColumnRight: "org.table.column-right"
653        case .insertColumn: "org.table.insert-column"
654        case .deleteColumn: "org.table.delete-column"
655        case .killRow: "org.table.kill-row"
656        case .insertRowAbove: "org.table.insert-row"
657        case .insertHline: "org.table.insert-hline"
658        }
659    }
660
661    public var title: String {
662        switch action {
663        case .align: "Align Table"
664        case .nextField: "Next Table Field"
665        case .previousField: "Previous Table Field"
666        case .nextRow: "Next Table Row"
667        case .moveRowUp: "Move Table Row Up"
668        case .moveRowDown: "Move Table Row Down"
669        case .moveColumnLeft: "Move Table Column Left"
670        case .moveColumnRight: "Move Table Column Right"
671        case .insertColumn: "Insert Table Column"
672        case .deleteColumn: "Delete Table Column"
673        case .killRow: "Delete Table Row"
674        case .insertRowAbove: "Insert Table Row"
675        case .insertHline: "Insert Table Rule"
676        }
677    }
678
679    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
680
681    public func run(in context: EditContext) -> CommandStep {
682        let body = { (buffer: EmacsBuffer) throws in
683            guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
684            try perform(buffer)
685        }
686        // These recalculate a row marked `#` first, whose written fields stay after an error.
687        let forms: [Action: String] = [.nextField: "(org-table-next-field)", .previousField: "(org-table-previous-field)", .nextRow: "(org-table-next-row)"]
688        guard let form = forms[action], EmacsBuffer(context.text, point: context.caret).lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else {
689            return tableCommand(context, body)
690        }
691        return TableRecalculate.recalculating(context, form: form, body)
692    }
693
694    private func perform(_ buffer: EmacsBuffer) throws {
695            switch action {
696            case .align: buffer.tableAlign()
697            case .nextField: try buffer.tableNextField()
698            case .previousField: try buffer.tablePreviousField()
699            case .nextRow: try buffer.tableNextRow()
700            case .moveRowUp: try buffer.tableMoveRow(up: true)
701            case .moveRowDown: try buffer.tableMoveRow(up: false)
702            case .moveColumnLeft: try buffer.tableMoveColumn(left: true)
703            case .moveColumnRight: try buffer.tableMoveColumn(left: false)
704            case .insertColumn: try buffer.tableInsertColumn()
705            case .deleteColumn: try buffer.tableDeleteColumn()
706            case .killRow: try buffer.tableKillRow()
707            case .insertRowAbove: try buffer.tableInsertRow(below: false)
708            case .insertHline: try buffer.tableInsertHline(above: false)
709            }
710    }
711}
712
713/// `#+STARTUP: align` (`org-startup-align-all-tables`): every table aligned.
714public struct AlignAllTables: OrgCommand {
715    public init() {}
716    public var id: String { "org.table.align-all" }
717    public var title: String { "Align All Tables" }
718    public func applies(in context: EditContext) -> Bool { true }
719    public func run(in context: EditContext) -> CommandStep {
720        let starts = context.tree.root.descendants().filter { $0.kind == .table }.map(\.range.lowerBound)
721        guard !starts.isEmpty else { return .commit(EditResult(baseRevision: context.revision, edits: [])) }
722        return commitBuffer(context) { buffer in
723            let caret = buffer.marker(buffer.point)
724            defer {
725                buffer.point = caret.position
726                buffer.release(caret)
727            }
728            for start in starts.reversed() {
729                buffer.point = start
730                buffer.skipForward([32, 9])
731                buffer.point += 1
732                buffer.tableAlign()
733            }
734        }
735    }
736}
737
738/// C-c |: `org-table-create` with a size prompt.
739public struct CreateTable: OrgCommand {
740    public init() {}
741    public var id: String { "org.table.create" }
742    public var title: String { "Create Table" }
743    public func applies(in context: EditContext) -> Bool { !KeyContext.holds("table", in: context) }
744    public func run(in context: EditContext) -> CommandStep {
745        if let converted = convert(context) { return converted }
746        guard let size = context.answers["size"] else {
747            return .prompt(Prompt(key: "size", message: "Table size Columns x Rows [e.g. 5x2]:", initial: ""))
748        }
749        return tableCommand(context) { try $0.tableCreate(size.isEmpty ? "5x2" : size) }
750    }
751
752    /// `org-table-create-or-convert-from-region`.
753    private func convert(_ context: EditContext) -> CommandStep? {
754        guard let region = context.selection.first, !region.isEmpty else { return nil }
755        return commitBuffer(context) { $0.tableConvertRegion(region.lowerBound, region.upperBound) }
756    }
757}