Sources/OrgCore/Commands/Table.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgCore/Commands/Table.swift history · blame · raw

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