Sources/OrgCore/Commands/Table.swift

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

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