Sources/OrgCore/Commands/Table.swift
682 lines · 28779 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 if numberRegex.firstMatch(in: cell, range: NSRange(location: 0, length: (cell as NSString).length)) != nil { numbers += 1 }
135 }
136 }
137 widths.append(maxWidth)
138 alignments.append(fixed ?? (Double(numbers) >= 0.5 * Double(nonEmpty) ? "r" : "l"))
139 }
140 }
141 let rule = widths.map { String(repeating: "-", count: $0 + 2) }.joined(separator: "+")
142 let indent = looking("[ \\t]*\\|", setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) } ?? "|"
143 for row in table {
144 let previous = substring(point, lineEnd(point))
145 let new: String
146 if let row {
147 let fields = row + Array(repeating: "", count: max(0, columns - row.count))
148 new = indent + zip(fields, zip(widths, alignments)).map { field, spec in
149 alignField(field, width: spec.0, alignment: spec.1, fieldWidth: width(field))
150 }.joined(separator: "|") + "|"
151 } else {
152 new = indent + rule + "|"
153 }
154 if new == previous {
155 forwardLine(1)
156 } else {
157 insert(new + "\n")
158 deleteRegion(point, min(length, lineEnd(point) + 1))
159 }
160 }
161 point = line.position
162 tableGotoColumn(column)
163 }
164
165 /// `org-table-current-column`.
166 func tableCurrentColumn() -> Int {
167 saveExcursion {
168 let pos = point
169 beginningOfLine()
170 let text = substring(point, pos)
171 guard let first = text.firstIndex(of: "|") else { return 0 }
172 let separators: Set<Character> = atTableHline ? ["+", "|"] : ["|"]
173 return 1 + text[text.index(after: first)...].filter { separators.contains($0) }.count
174 }
175 }
176
177 /// `org-table-goto-column`.
178 func tableGotoColumn(_ n: Int, onDelim: Bool = false, force: Bool = false) {
179 beginningOfLine()
180 guard n > 0 else { return }
181 var remaining = n
182 while remaining > 0 {
183 remaining -= 1
184 if let match = searchForward("\\|", bound: lineEnd(point), caseInsensitive: false) {
185 _ = match
186 } else if force {
187 endOfLine()
188 skipBackwardNot([124])
189 insert(" | ")
190 } else {
191 break
192 }
193 }
194 if force, looking(".*\\|", caseInsensitive: false, setsMatch: false) == nil {
195 saveExcursion {
196 endOfLine()
197 insert(" | ")
198 }
199 }
200 if onDelim {
201 point -= 1
202 } else if character(at: point) == 32 {
203 point += 1
204 }
205 }
206
207 /// `skip-chars-backward "^|"`.
208 func skipBackwardNot(_ set: Set<unichar>) {
209 while point > lineStart(point), let c = character(at: point - 1), !set.contains(c) { point -= 1 }
210 }
211
212 /// `org-table-current-dline`.
213 func tableCurrentDataLine() -> Int {
214 saveExcursion {
215 let pos = lineStart(point)
216 point = tableBegin()
217 var count = 0
218 while point <= pos {
219 if looking("^[ \\t]*\\|[^-]", caseInsensitive: false, setsMatch: false) != nil { count += 1 }
220 if forwardLine(1) != 0 { break }
221 }
222 return count
223 }
224 }
225
226 /// `org-table-clean-line`.
227 func cleanTableLine(_ line: String) -> String {
228 if line.range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil {
229 return String(line.map { $0 == "|" || $0 == "+" ? "|" : " " })
230 }
231 var result = line
232 let regex = try! NSRegularExpression(pattern: "\\|([ \\t]*?[^ \\t\\r\\n|][^\\r\\n|]*)\\|")
233 while let match = regex.firstMatch(in: result, range: NSRange(location: 0, length: (result as NSString).length)) {
234 let cell = (result as NSString).substring(with: match.range(at: 1))
235 result = (result as NSString).replacingCharacters(in: match.range, with: "|" + String(repeating: " ", count: cellWidth(cell)) + "|")
236 }
237 return result
238 }
239
240 /// `org-table-insert-row`; `below` as with a prefix argument.
241 func tableInsertRow(below: Bool) throws {
242 guard atTable else { throw UserError(message: "Not at a table") }
243 if eobp { saveExcursion { insert("\n") } }
244 if substring(lineStart(point), lineEnd(point)).range(of: "\\|[ \\t]*$", options: .regularExpression) == nil { tableAlign() }
245 let line = substring(lineStart(point), lineEnd(point))
246 var new = cleanTableLine(line)
247 if let match = line.range(of: "^[ \\t]*\\| *[#*$] *\\|", options: .regularExpression), let target = new.range(of: "^[ \\t]*\\| *[#*$] *\\|", options: .regularExpression) ?? new.range(of: "^[ \\t]*\\|[^|]*\\|", options: .regularExpression) {
248 new.replaceSubrange(target, with: line[match])
249 }
250 forwardLine(below ? 1 : 0)
251 if !bolp { insert("\n") }
252 insertBeforeMarkers(new + "\n")
253 forwardLine(-1)
254 searchForward("\\| ?", bound: lineEnd(point), caseInsensitive: false)
255 // `org-table-may-need-update' is set by any edit to a table, so org realigns here.
256 tableAlign()
257 fixFormulas("@", replace: [:], limit: tableCurrentDataLine() - 1, delta: 1)
258 }
259
260 /// `org-table-insert-hline`; `above` as with a prefix argument.
261 func tableInsertHline(above: Bool) throws {
262 guard atTable else { throw UserError(message: "Not at a table") }
263 if eobp { saveExcursion { insert("\n") } }
264 if substring(lineStart(point), lineEnd(point)).range(of: "\\|[ \\t]*$", options: .regularExpression) == nil { tableAlign() }
265 var line = cleanTableLine(substring(lineStart(point), lineEnd(point)))
266 let column = currentColumn
267 let regex = try! NSRegularExpression(pattern: "\\|( +)\\|")
268 while let match = regex.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) {
269 line = (line as NSString).replacingCharacters(in: match.range, with: "+" + String(repeating: "-", count: match.range(at: 1).length) + "|")
270 }
271 if let plus = line.firstIndex(of: "+") { line.replaceSubrange(plus...plus, with: "|") }
272 forwardLine(above ? 0 : 1)
273 insert(line + "\n")
274 forwardLine(above ? 0 : -2)
275 moveToColumn(column)
276 }
277
278 /// What `org-table-maybe-eval-formula` does to point: `org-table-get-field` leaves it one
279 /// character into the field.
280 func moveIntoField() {
281 skipBackwardNot([124, 10])
282 if bolp || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { return }
283 let start = point
284 point = min(lineEnd(point), start + 1)
285 }
286
287 /// `org-table-next-field`.
288 func tableNextField() throws {
289 try tableMaybeEvalFormula()
290 try tableMaybeRecalculateLine()
291 moveIntoField()
292 tableAlign()
293 let end = tableEnd()
294 if atTableHline { endOfLine() }
295 func toNextBar() -> Bool { searchForward("\\|", bound: end, caseInsensitive: false) != nil }
296 var ok = toNextBar()
297 if ok, looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil { ok = toNextBar() }
298 guard ok else {
299 try tableInsertRow(below: true)
300 return
301 }
302 if looking("-", caseInsensitive: false, setsMatch: false) != nil, let match = searchForward("^[ \\t]*\\|([^-])", bound: end, caseInsensitive: false) {
303 point = match[1]!.lowerBound
304 }
305 if looking("-", caseInsensitive: false, setsMatch: false) != nil {
306 forwardLine(-1)
307 try tableInsertRow(below: true)
308 } else if character(at: point) == 32 {
309 point += 1
310 }
311 }
312
313 /// `org-table-previous-field`.
314 func tablePreviousField() throws {
315 try tableMaybeRecalculateLine()
316 tableAlign()
317 if atTableHline { endOfLine() }
318 let start = tableBegin()
319 let origin = point
320 func back() -> Bool {
321 guard let match = searchBackward("\\|", bound: start, caseInsensitive: false) else { return false }
322 point = match[0]!.lowerBound
323 return true
324 }
325 var ok = back() && back()
326 while ok, looking("\\|(?:-|[ \\t]*$)", caseInsensitive: false, setsMatch: false) != nil { ok = back() }
327 guard ok else {
328 point = origin
329 throw UserError(message: "Cannot move to previous table field")
330 }
331 if let bar = looking("\\| ?", caseInsensitive: false, setsMatch: false) { point = bar[0]!.upperBound }
332 }
333
334 /// `org-table-next-row`.
335 func tableNextRow() throws {
336 try tableMaybeEvalFormula()
337 try tableMaybeRecalculateLine()
338 moveIntoField()
339 tableAlign()
340 let column = tableCurrentColumn()
341 forwardLine(1)
342 if !bolp { insert("\n") }
343 if !atTable || atTableHline {
344 forwardLine(-1)
345 try tableInsertRow(below: true)
346 }
347 tableGotoColumn(column)
348 skipBackwardNot([124, 10, 13])
349 if character(at: point) == 32 { point += 1 }
350 }
351
352 /// `org-table-move-row`.
353 func tableMoveRow(up: Bool) throws {
354 let column = currentColumn
355 let pos = point
356 let hline1 = atTableHline
357 let dline1 = tableCurrentDataLine()
358 let dline2 = dline1 + (up ? -1 : 1)
359 if up, lineStart(point) == 0 { throw UserError(message: "Cannot move row further") }
360 forwardLine(up ? -1 : 1)
361 if (!up && eobp) || !atTable {
362 point = pos
363 throw UserError(message: "Cannot move row further")
364 }
365 let hline2 = atTableHline
366 point = pos
367 let rowStart = lineStart(point)
368 let rowEnd = min(length, lineEnd(point) + 1)
369 let row = substring(rowStart, rowEnd)
370 deleteRegion(rowStart, rowEnd)
371 forwardLine(up ? -1 : 1)
372 if !bolp { insert("\n") }
373 insert(row)
374 if !bolp { insert("\n") }
375 forwardLine(-1)
376 moveToColumn(column)
377 if !hline1, !hline2 {
378 fixFormulas("@", replace: [String(dline1): String(dline2), String(dline2): String(dline1)])
379 }
380 }
381
382 /// `org-table-move-column`.
383 func tableMoveColumn(left: Bool) throws {
384 guard atTable else { throw UserError(message: "Not at a table") }
385 try findDataLine()
386 try checkInsideDataField()
387 let column = tableCurrentColumn()
388 let first = left ? column - 1 : column
389 let target = left ? column - 1 : column + 1
390 let begin = tableBegin()
391 let end = marker(tableEnd())
392 defer { release(end) }
393 if left, column == 1 { throw UserError(message: "Cannot move column further left") }
394 if !left, looking("[^|\\n]*\\|[^|\\n]*$", caseInsensitive: false, setsMatch: false) != nil { throw UserError(message: "Cannot move column further right") }
395 let line = marker(lineStart(point))
396 point = begin
397 while point < end.position {
398 if !atTableHline {
399 tableGotoColumn(first, onDelim: true)
400 if let match = looking("\\|([^|\\n]+)\\|([^|\\n]+)\\|", caseInsensitive: false, setsMatch: false) {
401 let a = substring(match[1]!.lowerBound, match[1]!.upperBound)
402 let b = substring(match[2]!.lowerBound, match[2]!.upperBound)
403 replace(match[1]!.lowerBound..<match[2]!.upperBound, with: b + "|" + a)
404 }
405 }
406 if forwardLine(1) != 0 { break }
407 }
408 point = line.position
409 release(line)
410 tableGotoColumn(column)
411 tableGotoColumn(target)
412 tableAlign()
413 fixFormulas("$", replace: [String(column): String(target), String(target): String(column)])
414 }
415
416 /// `org-table-insert-column`.
417 func tableInsertColumn() throws {
418 guard atTable else { throw UserError(message: "Not at a table") }
419 if eobp { saveExcursion { insert("\n") } }
420 if substring(lineStart(point), lineEnd(point)).range(of: "\\|[ \\t]*$", options: .regularExpression) == nil { tableAlign() }
421 try findDataLine()
422 let column = max(1, tableCurrentColumn())
423 let begin = tableBegin()
424 let end = marker(tableEnd())
425 defer { release(end) }
426 saveExcursion {
427 point = begin
428 while point < end.position {
429 if !atTableHline {
430 tableGotoColumn(column, onDelim: true)
431 insert("|")
432 }
433 if forwardLine(1) != 0 { break }
434 }
435 }
436 tableGotoColumn(column)
437 tableAlign()
438 fixFormulas("$", replace: [:], limit: column - 1, delta: 1)
439 }
440
441 /// `org-table-delete-column`.
442 func tableDeleteColumn() throws {
443 guard atTable else { throw UserError(message: "Not at a table") }
444 try findDataLine()
445 if saveExcursion({ () -> Bool in skipForward(Self.blanks); return eolp }) {
446 if let match = searchBackward("\\|", caseInsensitive: false) { point = match[0]!.lowerBound }
447 }
448 try checkInsideDataField()
449 let column = tableCurrentColumn()
450 let begin = tableBegin()
451 let end = marker(tableEnd())
452 defer { release(end) }
453 let line = marker(lineStart(point))
454 point = begin
455 while point < end.position {
456 if !atTableHline {
457 tableGotoColumn(column, onDelim: true)
458 if let match = looking("\\|[^|\\n]+\\|", caseInsensitive: false, setsMatch: false) { replace(match[0]!, with: "|") }
459 }
460 if forwardLine(1) != 0 { break }
461 }
462 point = line.position
463 release(line)
464 tableGotoColumn(column)
465 tableAlign()
466 fixFormulas("$", replace: [String(column): "INVALID"], limit: column, delta: -1, remove: column)
467 }
468
469 /// `org-table-kill-row`.
470 func tableKillRow() throws {
471 guard atTable else { throw UserError(message: "Not at a table") }
472 let column = currentColumn
473 let dline = atTableHline ? nil : tableCurrentDataLine()
474 deleteRegion(lineStart(point), min(lineEnd(point) + 1, length))
475 if !atTable { forwardLine(-1) }
476 moveToColumn(column)
477 if let dline { fixFormulas("@", replace: [String(dline): "INVALID"], limit: dline, delta: -1, remove: dline) }
478 }
479
480 /// `org-table-find-dataline`.
481 func findDataLine() throws {
482 guard atTableHline else { return }
483 let column = currentColumn
484 let end = tableEnd()
485 forwardLine(1)
486 while point < end, atTableHline { forwardLine(1) }
487 if point >= end { throw UserError(message: "Cannot find data row for column operation") }
488 moveToColumn(column)
489 }
490
491 /// `org-table-check-inside-data-field`.
492 func checkInsideDataField() throws {
493 let atLineStart = saveExcursion { () -> Bool in skipBackward(Self.blanks); return bolp }
494 if atLineStart || atTableHline || looking("[ \\t]*$", caseInsensitive: false, setsMatch: false) != nil {
495 throw UserError(message: "Not in table data field")
496 }
497 }
498
499 /// `org-table-fix-formulas`.
500 func fixFormulas(_ key: String, replace replacements: [String: String], limit: Int? = nil, delta: Int = 0, remove: Int? = nil) {
501 saveExcursion {
502 point = tableEnd()
503 while looking("[ \\t]*#\\+tblfm:", setsMatch: false) != nil {
504 if let remove {
505 let pattern = key == "$" ? "(@[0-9]+)?\\$\(remove)=.*?(::|$)" : "@\(remove)\\$[0-9]+=.*?(::|$)"
506 saveExcursion {
507 while let match = searchForward(pattern, bound: lineEnd(point), caseInsensitive: false) {
508 replace(match[0]!, with: "")
509 point = match[0]!.lowerBound
510 }
511 }
512 }
513 let lineStartOffset = point
514 let pattern = NSRegularExpression.escapedPattern(for: key) + "([0-9]+)"
515 while let match = searchForward(pattern, bound: lineEnd(point), caseInsensitive: false) {
516 let number = substring(match[1]!.lowerBound, match[1]!.upperBound)
517 if let new = replacements[number] {
518 replace(match[0]!, with: key + new)
519 } else if let limit, let n = Int(number), n > limit {
520 replace(match[0]!, with: key + String(n + delta))
521 }
522 }
523 _ = lineStartOffset
524 if forwardLine(1) != 0 { break }
525 }
526 }
527 }
528
529 /// `org-table-create` with a size like `3x2`.
530 func tableCreate(_ size: String) throws {
531 let parts = size.split(separator: "x").map { $0.trimmingCharacters(in: .whitespaces) }
532 guard parts.count == 2, let columns = Int(parts[0]), let rows = Int(parts[1]) else { throw UserError(message: "Size must be like 5x2") }
533 let pos = point
534 let indent = String(repeating: " ", count: currentColumn)
535 let line = indent + "|" + String(repeating: " |", count: columns) + "\n"
536 if substring(lineStart(point), point).allSatisfy({ $0 == " " || $0 == "\t" }) {
537 beginningOfLine()
538 } else {
539 insert("\n")
540 }
541 for _ in 0..<rows { insert(line) }
542 point = pos
543 if rows > 1 {
544 endOfLine()
545 insert("\n|-")
546 point = pos
547 }
548 tableAlign()
549 }
550}
551
552
553private func tableCommand(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
554 commitBuffer(context, body)
555}
556
557/// A table command that needs the caret in an org table.
558public struct TableCommand: OrgCommand {
559 public enum Action: String, Sendable, CaseIterable {
560 case align, nextField, previousField, nextRow, moveRowUp, moveRowDown, moveColumnLeft, moveColumnRight
561 case insertColumn, deleteColumn, killRow, insertRowAbove, insertHline
562 }
563
564 public let action: Action
565 public init(_ action: Action) { self.action = action }
566
567 public var id: String {
568 switch action {
569 case .align: "org.table.align"
570 case .nextField: "org.table.next-field"
571 case .previousField: "org.table.previous-field"
572 case .nextRow: "org.table.next-row"
573 case .moveRowUp: "org.table.row-up"
574 case .moveRowDown: "org.table.row-down"
575 case .moveColumnLeft: "org.table.column-left"
576 case .moveColumnRight: "org.table.column-right"
577 case .insertColumn: "org.table.insert-column"
578 case .deleteColumn: "org.table.delete-column"
579 case .killRow: "org.table.kill-row"
580 case .insertRowAbove: "org.table.insert-row"
581 case .insertHline: "org.table.insert-hline"
582 }
583 }
584
585 public var title: String {
586 switch action {
587 case .align: "Align Table"
588 case .nextField: "Next Table Field"
589 case .previousField: "Previous Table Field"
590 case .nextRow: "Next Table Row"
591 case .moveRowUp: "Move Table Row Up"
592 case .moveRowDown: "Move Table Row Down"
593 case .moveColumnLeft: "Move Table Column Left"
594 case .moveColumnRight: "Move Table Column Right"
595 case .insertColumn: "Insert Table Column"
596 case .deleteColumn: "Delete Table Column"
597 case .killRow: "Delete Table Row"
598 case .insertRowAbove: "Insert Table Row"
599 case .insertHline: "Insert Table Rule"
600 }
601 }
602
603 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
604
605 public func run(in context: EditContext) -> CommandStep {
606 let step = tableCommand(context) { buffer in
607 guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
608 do {
609 try perform(buffer)
610 } catch let error as Calc.Unsupported {
611 throw EmacsBuffer.UserError(message: TableRecalculate.emacsMessage + error.reason)
612 }
613 }
614 // A row marked `#` that recalculates with formulas only Emacs can do.
615 let forms: [Action: String] = [.nextField: "(org-table-next-field)", .previousField: "(org-table-previous-field)", .nextRow: "(org-table-next-row)"]
616 return forms[action].map { TableRecalculate.inEmacs(step, form: $0, in: context) } ?? step
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}