Sources/OrgCore/Commands/Table.swift

682 lines · 28880 bytes

  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    /// `org-table-next-field`.
289    func tableNextField() throws {
290        try tableMaybeEvalFormula()
291        try tableMaybeRecalculateLine()
292        moveIntoField()
293        tableAlign()
294        let end = tableEnd()
295        if atTableHline { endOfLine() }
296        func toNextBar() -> Bool { searchForward("\\|", bound: end, caseInsensitive: false) != nil }
297        var ok = toNextBar()
298        if ok, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { ok = toNextBar() }
299        guard ok else {
300            try tableInsertRow(below: true)
301            return
302        }
303        if looking("-", caseInsensitive: false, setsMatch: false) != nil, let match = searchForward("^[ \\t]*\\|([^-])", bound: end, caseInsensitive: false) {
304            point = match[1]!.lowerBound
305        }
306        if looking("-", caseInsensitive: false, setsMatch: false) != nil {
307            forwardLine(-1)
308            try tableInsertRow(below: true)
309        } else if character(at: point) == 32 {
310            point += 1
311        }
312    }
313
314    /// `org-table-previous-field`.
315    func tablePreviousField() throws {
316        try tableMaybeRecalculateLine()
317        tableAlign()
318        if atTableHline { endOfLine() }
319        let start = tableBegin()
320        let origin = point
321        func back() -> Bool {
322            guard let match = searchBackward("\\|", bound: start, caseInsensitive: false) else { return false }
323            point = match[0]!.lowerBound
324            return true
325        }
326        var ok = back() && back()
327        while ok, looking("\\|(?:-|[ \\t]*$)", caseInsensitive: false, setsMatch: false) != nil { ok = back() }
328        guard ok else {
329            point = origin
330            throw UserError(message: "Cannot move to previous table field")
331        }
332        if let bar = looking("\\| ?", caseInsensitive: false, setsMatch: false) { point = bar[0]!.upperBound }
333    }
334
335    /// `org-table-next-row`.
336    func tableNextRow() throws {
337        try tableMaybeEvalFormula()
338        try tableMaybeRecalculateLine()
339        moveIntoField()
340        tableAlign()
341        let column = tableCurrentColumn()
342        forwardLine(1)
343        if !bolp { insert("\n") }
344        if !atTable || atTableHline {
345            forwardLine(-1)
346            try tableInsertRow(below: true)
347        }
348        tableGotoColumn(column)
349        skipBackwardNot([124, 10, 13])
350        if character(at: point) == 32 { point += 1 }
351    }
352
353    /// `org-table-move-row`.
354    func tableMoveRow(up: Bool) throws {
355        let column = currentColumn
356        let pos = point
357        let hline1 = atTableHline
358        let dline1 = tableCurrentDataLine()
359        let dline2 = dline1 + (up ? -1 : 1)
360        if up, lineStart(point) == 0 { throw UserError(message: "Cannot move row further") }
361        forwardLine(up ? -1 : 1)
362        if (!up && eobp) || !atTable {
363            point = pos
364            throw UserError(message: "Cannot move row further")
365        }
366        let hline2 = atTableHline
367        point = pos
368        let rowStart = lineStart(point)
369        let rowEnd = min(length, lineEnd(point) + 1)
370        let row = substring(rowStart, rowEnd)
371        deleteRegion(rowStart, rowEnd)
372        forwardLine(up ? -1 : 1)
373        if !bolp { insert("\n") }
374        insert(row)
375        if !bolp { insert("\n") }
376        forwardLine(-1)
377        moveToColumn(column)
378        if !hline1, !hline2 {
379            fixFormulas("@", replace: [String(dline1): String(dline2), String(dline2): String(dline1)])
380        }
381    }
382
383    /// `org-table-move-column`.
384    func tableMoveColumn(left: Bool) throws {
385        guard atTable else { throw UserError(message: "Not at a table") }
386        try findDataLine()
387        try checkInsideDataField()
388        let column = tableCurrentColumn()
389        let first = left ? column - 1 : column
390        let target = left ? column - 1 : column + 1
391        let begin = tableBegin()
392        let end = marker(tableEnd())
393        defer { release(end) }
394        if left, column == 1 { throw UserError(message: "Cannot move column further left") }
395        if !left, looking("[^|\\n]*\\|[^|\\n]*$", caseInsensitive: false, setsMatch: false) != nil { throw UserError(message: "Cannot move column further right") }
396        let line = marker(lineStart(point))
397        point = begin
398        while point < end.position {
399            if !atTableHline {
400                tableGotoColumn(first, onDelim: true)
401                if let match = looking("\\|([^|\\n]+)\\|([^|\\n]+)\\|", caseInsensitive: false, setsMatch: false) {
402                    let a = substring(match[1]!.lowerBound, match[1]!.upperBound)
403                    let b = substring(match[2]!.lowerBound, match[2]!.upperBound)
404                    replace(match[1]!.lowerBound..<match[2]!.upperBound, with: b + "|" + a)
405                }
406            }
407            if forwardLine(1) != 0 { break }
408        }
409        point = line.position
410        release(line)
411        tableGotoColumn(column)
412        tableGotoColumn(target)
413        tableAlign()
414        fixFormulas("$", replace: [String(column): String(target), String(target): String(column)])
415    }
416
417    /// `org-table-insert-column`.
418    func tableInsertColumn() throws {
419        guard atTable else { throw UserError(message: "Not at a table") }
420        if eobp { saveExcursion { insert("\n") } }
421        if substring(lineStart(point), lineEnd(point)).range(of: "\\|[ \\t]*$", options: .regularExpression) == nil { tableAlign() }
422        try findDataLine()
423        let column = max(1, tableCurrentColumn())
424        let begin = tableBegin()
425        let end = marker(tableEnd())
426        defer { release(end) }
427        saveExcursion {
428            point = begin
429            while point < end.position {
430                if !atTableHline {
431                    tableGotoColumn(column, onDelim: true)
432                    insert("|")
433                }
434                if forwardLine(1) != 0 { break }
435            }
436        }
437        tableGotoColumn(column)
438        tableAlign()
439        fixFormulas("$", replace: [:], limit: column - 1, delta: 1)
440    }
441
442    /// `org-table-delete-column`.
443    func tableDeleteColumn() throws {
444        guard atTable else { throw UserError(message: "Not at a table") }
445        try findDataLine()
446        if saveExcursion({ () -> Bool in skipForward(Self.blanks); return eolp }) {
447            if let match = searchBackward("\\|", caseInsensitive: false) { point = match[0]!.lowerBound }
448        }
449        try checkInsideDataField()
450        let column = tableCurrentColumn()
451        let begin = tableBegin()
452        let end = marker(tableEnd())
453        defer { release(end) }
454        let line = marker(lineStart(point))
455        point = begin
456        while point < end.position {
457            if !atTableHline {
458                tableGotoColumn(column, onDelim: true)
459                if let match = looking("\\|[^|\\n]+\\|", caseInsensitive: false, setsMatch: false) { replace(match[0]!, with: "|") }
460            }
461            if forwardLine(1) != 0 { break }
462        }
463        point = line.position
464        release(line)
465        tableGotoColumn(column)
466        tableAlign()
467        fixFormulas("$", replace: [String(column): "INVALID"], limit: column, delta: -1, remove: column)
468    }
469
470    /// `org-table-kill-row`.
471    func tableKillRow() throws {
472        guard atTable else { throw UserError(message: "Not at a table") }
473        let column = currentColumn
474        let dline = atTableHline ? nil : tableCurrentDataLine()
475        deleteRegion(lineStart(point), min(lineEnd(point) + 1, length))
476        if !atTable { forwardLine(-1) }
477        moveToColumn(column)
478        if let dline { fixFormulas("@", replace: [String(dline): "INVALID"], limit: dline, delta: -1, remove: dline) }
479    }
480
481    /// `org-table-find-dataline`.
482    func findDataLine() throws {
483        guard atTableHline else { return }
484        let column = currentColumn
485        let end = tableEnd()
486        forwardLine(1)
487        while point < end, atTableHline { forwardLine(1) }
488        if point >= end { throw UserError(message: "Cannot find data row for column operation") }
489        moveToColumn(column)
490    }
491
492    /// `org-table-check-inside-data-field`.
493    func checkInsideDataField() throws {
494        let atLineStart = saveExcursion { () -> Bool in skipBackward(Self.blanks); return bolp }
495        if atLineStart || atTableHline || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil {
496            throw UserError(message: "Not in table data field")
497        }
498    }
499
500    /// `org-table-fix-formulas`.
501    func fixFormulas(_ key: String, replace replacements: [String: String], limit: Int? = nil, delta: Int = 0, remove: Int? = nil) {
502        saveExcursion {
503            point = tableEnd()
504            while looking("[ \\t]*#\\+tblfm:", setsMatch: false) != nil {
505                if let remove {
506                    let pattern = key == "$" ? "(@[0-9]+)?\\$\(remove)=.*?(::|$)" : "@\(remove)\\$[0-9]+=.*?(::|$)"
507                    saveExcursion {
508                        while let match = searchForward(pattern, bound: lineEnd(point), caseInsensitive: false) {
509                            replace(match[0]!, with: "")
510                            point = match[0]!.lowerBound
511                        }
512                    }
513                }
514                let lineStartOffset = point
515                let pattern = NSRegularExpression.escapedPattern(for: key) + "([0-9]+)"
516                while let match = searchForward(pattern, bound: lineEnd(point), caseInsensitive: false) {
517                    let number = substring(match[1]!.lowerBound, match[1]!.upperBound)
518                    if let new = replacements[number] {
519                        replace(match[0]!, with: key + new)
520                    } else if let limit, let n = Int(number), n > limit {
521                        replace(match[0]!, with: key + String(n + delta))
522                    }
523                }
524                _ = lineStartOffset
525                if forwardLine(1) != 0 { break }
526            }
527        }
528    }
529
530    /// `org-table-create` with a size like `3x2`.
531    func tableCreate(_ size: String) throws {
532        let parts = size.split(separator: "x").map { $0.trimmingCharacters(in: .whitespaces) }
533        guard parts.count == 2, let columns = Int(parts[0]), let rows = Int(parts[1]) else { throw UserError(message: "Size must be like 5x2") }
534        let pos = point
535        let indent = String(repeating: " ", count: currentColumn)
536        let line = indent + "|" + String(repeating: "  |", count: columns) + "\n"
537        if substring(lineStart(point), point).allSatisfy({ $0 == " " || $0 == "\t" }) {
538            beginningOfLine()
539        } else {
540            insert("\n")
541        }
542        for _ in 0..<rows { insert(line) }
543        point = pos
544        if rows > 1 {
545            endOfLine()
546            insert("\n|-")
547            point = pos
548        }
549        tableAlign()
550    }
551}
552
553
554private func tableCommand(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
555    commitBuffer(context, body)
556}
557
558/// A table command that needs the caret in an org table.
559public struct TableCommand: OrgCommand {
560    public enum Action: String, Sendable, CaseIterable {
561        case align, nextField, previousField, nextRow, moveRowUp, moveRowDown, moveColumnLeft, moveColumnRight
562        case insertColumn, deleteColumn, killRow, insertRowAbove, insertHline
563    }
564
565    public let action: Action
566    public init(_ action: Action) { self.action = action }
567
568    public var id: String {
569        switch action {
570        case .align: "org.table.align"
571        case .nextField: "org.table.next-field"
572        case .previousField: "org.table.previous-field"
573        case .nextRow: "org.table.next-row"
574        case .moveRowUp: "org.table.row-up"
575        case .moveRowDown: "org.table.row-down"
576        case .moveColumnLeft: "org.table.column-left"
577        case .moveColumnRight: "org.table.column-right"
578        case .insertColumn: "org.table.insert-column"
579        case .deleteColumn: "org.table.delete-column"
580        case .killRow: "org.table.kill-row"
581        case .insertRowAbove: "org.table.insert-row"
582        case .insertHline: "org.table.insert-hline"
583        }
584    }
585
586    public var title: String {
587        switch action {
588        case .align: "Align Table"
589        case .nextField: "Next Table Field"
590        case .previousField: "Previous Table Field"
591        case .nextRow: "Next Table Row"
592        case .moveRowUp: "Move Table Row Up"
593        case .moveRowDown: "Move Table Row Down"
594        case .moveColumnLeft: "Move Table Column Left"
595        case .moveColumnRight: "Move Table Column Right"
596        case .insertColumn: "Insert Table Column"
597        case .deleteColumn: "Delete Table Column"
598        case .killRow: "Delete Table Row"
599        case .insertRowAbove: "Insert Table Row"
600        case .insertHline: "Insert Table Rule"
601        }
602    }
603
604    public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
605
606    public func run(in context: EditContext) -> CommandStep {
607        let body = { (buffer: EmacsBuffer) throws in
608            guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
609            try perform(buffer)
610        }
611        // These recalculate a row marked `#` first, whose written fields stay after an error.
612        let forms: [Action: String] = [.nextField: "(org-table-next-field)", .previousField: "(org-table-previous-field)", .nextRow: "(org-table-next-row)"]
613        guard let form = forms[action], EmacsBuffer(context.text, point: context.caret).lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else {
614            return tableCommand(context, body)
615        }
616        return TableRecalculate.recalculating(context, form: form, body)
617    }
618
619    private func perform(_ buffer: EmacsBuffer) throws {
620            switch action {
621            case .align: buffer.tableAlign()
622            case .nextField: try buffer.tableNextField()
623            case .previousField: try buffer.tablePreviousField()
624            case .nextRow: try buffer.tableNextRow()
625            case .moveRowUp: try buffer.tableMoveRow(up: true)
626            case .moveRowDown: try buffer.tableMoveRow(up: false)
627            case .moveColumnLeft: try buffer.tableMoveColumn(left: true)
628            case .moveColumnRight: try buffer.tableMoveColumn(left: false)
629            case .insertColumn: try buffer.tableInsertColumn()
630            case .deleteColumn: try buffer.tableDeleteColumn()
631            case .killRow: try buffer.tableKillRow()
632            case .insertRowAbove: try buffer.tableInsertRow(below: false)
633            case .insertHline: try buffer.tableInsertHline(above: false)
634            }
635    }
636}
637
638/// `#+STARTUP: align` (`org-startup-align-all-tables`): every table aligned.
639public struct AlignAllTables: OrgCommand {
640    public init() {}
641    public var id: String { "org.table.align-all" }
642    public var title: String { "Align All Tables" }
643    public func applies(in context: EditContext) -> Bool { true }
644    public func run(in context: EditContext) -> CommandStep {
645        let starts = context.tree.root.descendants().filter { $0.kind == .table }.map(\.range.lowerBound)
646        guard !starts.isEmpty else { return .commit(EditResult(baseRevision: context.revision, edits: [])) }
647        return commitBuffer(context) { buffer in
648            let caret = buffer.marker(buffer.point)
649            defer {
650                buffer.point = caret.position
651                buffer.release(caret)
652            }
653            for start in starts.reversed() {
654                buffer.point = start
655                buffer.skipForward([32, 9])
656                buffer.point += 1
657                buffer.tableAlign()
658            }
659        }
660    }
661}
662
663/// C-c |: `org-table-create` with a size prompt.
664public struct CreateTable: OrgCommand {
665    public init() {}
666    public var id: String { "org.table.create" }
667    public var title: String { "Create Table" }
668    public func applies(in context: EditContext) -> Bool { !KeyContext.holds("table", in: context) }
669    public func run(in context: EditContext) -> CommandStep {
670        if let converted = convert(context) { return converted }
671        guard let size = context.answers["size"] else {
672            return .prompt(Prompt(key: "size", message: "Table size Columns x Rows [e.g. 5x2]:", initial: ""))
673        }
674        return tableCommand(context) { try $0.tableCreate(size.isEmpty ? "5x2" : size) }
675    }
676
677    /// `org-table-create-or-convert-from-region`.
678    private func convert(_ context: EditContext) -> CommandStep? {
679        guard let region = context.selection.first, !region.isEmpty else { return nil }
680        return commitBuffer(context) { $0.tableConvertRegion(region.lowerBound, region.upperBound) }
681    }
682}