Table formula iteration and automatic recalculation !287

merged merged by cmc on 2026-10-11 15:07 UTC · krz/orgstar:issue-49 into main

7 files changed, +143 −10

Layout: unified · split

Sources/OrgCore/Commands/Command.swift +1 −1
@@ -333,7 +333,7 @@ public enum Commands {
333 TimerSetCountdown(), TimerShowRemaining(), TimerChangeTimes(), 333 TimerSetCountdown(), TimerShowRemaining(), TimerChangeTimes(),
334 InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true), 334 InsertTimestamp(), InsertTimestamp(inactive: true), SetPlanning(deadline: false), SetPlanning(deadline: true),
335 RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(), CreateTable(), 335 RemovePlanning(deadline: false), RemovePlanning(deadline: true), FillParagraph(), CreateTable(),
336 TableRecalculate(all: false), TableRecalculate(all: true), ExecuteSrcBlock(), OrgDwim(), 336 TableRecalculate(all: false), TableRecalculate(all: true), TableIterate(), ExecuteSrcBlock(), OrgDwim(),
337 ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false), 337 ShiftTimestamp(up: true), ShiftTimestamp(up: false), ShiftTimestampDay(later: true), ShiftTimestampDay(later: false),
338 OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(), 338 OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(),
339 CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target), 339 CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target),
Sources/OrgCore/Commands/Table.swift +16 −2
@@ -287,6 +287,7 @@ extension EmacsBuffer {
287 /// `org-table-next-field`. 287 /// `org-table-next-field`.
288 func tableNextField() throws { 288 func tableNextField() throws {
289 try tableMaybeEvalFormula() 289 try tableMaybeEvalFormula()
290 try tableMaybeRecalculateLine()
290 moveIntoField() 291 moveIntoField()
291 tableAlign() 292 tableAlign()
292 let end = tableEnd() 293 let end = tableEnd()
@@ -311,6 +312,7 @@ extension EmacsBuffer {
311 312
312 /// `org-table-previous-field`. 313 /// `org-table-previous-field`.
313 func tablePreviousField() throws { 314 func tablePreviousField() throws {
315 try tableMaybeRecalculateLine()
314 tableAlign() 316 tableAlign()
315 if atTableHline { endOfLine() } 317 if atTableHline { endOfLine() }
316 let start = tableBegin() 318 let start = tableBegin()
@@ -332,6 +334,7 @@ extension EmacsBuffer {
332 /// `org-table-next-row`. 334 /// `org-table-next-row`.
333 func tableNextRow() throws { 335 func tableNextRow() throws {
334 try tableMaybeEvalFormula() 336 try tableMaybeEvalFormula()
337 try tableMaybeRecalculateLine()
335 moveIntoField() 338 moveIntoField()
336 tableAlign() 339 tableAlign()
337 let column = tableCurrentColumn() 340 let column = tableCurrentColumn()
@@ -600,8 +603,20 @@ public struct TableCommand: OrgCommand {
600 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) } 603 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
601 604
602 public func run(in context: EditContext) -> CommandStep { 605 public func run(in context: EditContext) -> CommandStep {
603 tableCommand(context) { buffer in 606 let step = tableCommand(context) { buffer in
604 guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") } 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 {
605 switch action { 620 switch action {
606 case .align: buffer.tableAlign() 621 case .align: buffer.tableAlign()
607 case .nextField: try buffer.tableNextField() 622 case .nextField: try buffer.tableNextField()
@@ -617,7 +632,6 @@ public struct TableCommand: OrgCommand {
617 case .insertRowAbove: try buffer.tableInsertRow(below: false) 632 case .insertRowAbove: try buffer.tableInsertRow(below: false)
618 case .insertHline: try buffer.tableInsertHline(above: false) 633 case .insertHline: try buffer.tableInsertHline(above: false)
619 } 634 }
620 }
621 } 635 }
622} 636}
623 637
Sources/OrgCore/Compute/TableFormulaCommands.swift +44
@@ -69,8 +69,52 @@ public struct TableRecalculate: OrgCommand {
69 } 69 }
70} 70}
71 71
72/// C-u C-u C-c *: `org-table-iterate`, the whole table recalculated until it stops changing,
73/// at most ten times.
74public struct TableIterate: OrgCommand {
75 public init() {}
76 public var id: String { "org.table.iterate" }
77 public var title: String { "Iterate Table Formulas" }
78 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
79
80 public func run(in context: EditContext) -> CommandStep {
81 var message = ""
82 var step = commitBuffer(context) { buffer in
83 guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
84 func table() -> String { buffer.substring(buffer.tableBegin(), buffer.tableEnd()) }
85 var last = table()
86 do {
87 for iteration in 1...10 {
88 try buffer.tableRecalculate(all: true)
89 let this = table()
90 if this == last {
91 message = iteration > 1 ? "Convergence after \(iteration) iterations" : "Table was already stable"
92 return
93 }
94 last = this
95 }
96 } catch let error as Calc.Unsupported {
97 throw EmacsBuffer.UserError(message: TableRecalculate.emacsMessage + error.reason)
98 }
99 // The recalculations stay, as Emacs leaves them before its error.
100 message = "No convergence after 10 iterations"
101 }
102 if case .commit(let result) = step {
103 step = .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(message)]))
104 }
105 return TableRecalculate.inEmacs(step, form: "(org-table-iterate)", in: context)
106 }
107}
108
72// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`). 109// Formulas typed in a field (`org-table-maybe-eval-formula`) and C-c = (`org-table-eval-formula`).
73extension EmacsBuffer { 110extension EmacsBuffer {
111 /// `org-table-maybe-recalculate-line`: a row whose first field is `#` recalculated, as
112 /// TAB, S-TAB and RET in a table do first.
113 func tableMaybeRecalculateLine() throws {
114 guard lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else { return }
115 try tableRecalculate(all: false)
116 }
117
74 /// `org-table-formula-make-cmp-string`. 118 /// `org-table-formula-make-cmp-string`.
75 static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? { 119 static func formulaSortKey(_ lhs: String, analysis: TableAnalysis) -> String? {
76 var a = lhs 120 var a = lhs
Sources/OrgCore/Keymap/PresetEmacs.swift +8
@@ -653,6 +653,14 @@ extension KeymapPreset {
653 command = "org.table.recalc" 653 command = "org.table.recalc"
654 when = "table" 654 when = "table"
655 [[bind]] 655 [[bind]]
656 keys = "C-u C-c *"
657 command = "org.table.recalc-all"
658 when = "table"
659 [[bind]]
660 keys = "C-u C-u C-c *"
661 command = "org.table.iterate"
662 when = "table"
663 [[bind]]
656 keys = "C-c C-c" 664 keys = "C-c C-c"
657 command = "org.babel.execute" 665 command = "org.babel.execute"
658 when = "src" 666 when = "src"
Tests/OrgCoreTests/TableAutoRecalcTests.swift added +59
@@ -0,0 +1,59 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// Rows marked `#` recalculated by TAB, S-TAB and RET, and C-u C-u C-c * iterating, against
6/// Emacs.
7struct TableAutoRecalcTests {
8 static let marked = """
9 | # | 1 | 2 | |
10 | * | 3 | 4 | |
11 | | 5 | 6 | |
12 | # | 7 | 8 | |
13 #+TBLFM: $4=$2+$3
14
15 """
16
17 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
18 func navigationRecalculatesMarkedRows() throws {
19 let carets = EmacsOracle.positions(Self.marked).filter { $0 < (Self.marked as NSString).range(of: "#+TBLFM").location }
20 try compareWithEmacs([(Self.marked, carets)], [
21 (TableCommand(.nextField), "(org-table-next-field)", false),
22 (TableCommand(.previousField), "(org-table-previous-field)", false),
23 (TableCommand(.nextRow), "(org-table-next-row)", false),
24 ])
25 }
26
27 /// The table after iterating and the message, or the error.
28 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
29 func iteratingMatchesEmacs() throws {
30 let tables = [
31 // A chain each pass moves one step along.
32 "| 0 |\n| 0 |\n| 0 |\n#+TBLFM: @1$1=@2$1+1::@2$1=@3$1+1::@3$1=1\n",
33 "| 1 | 2 |\n#+TBLFM: $2=$1*2\n",
34 "| 0 |\n#+TBLFM: @1$1=@1$1+1\n",
35 ]
36 var cases: [EmacsOracle.Case] = []
37 var ours: [String] = []
38 for text in tables {
39 cases.append(EmacsOracle.Case(text: text, point: 3, form: """
40 (let ((msg "")) (cl-letf (((symbol-function 'message) (lambda (f &rest a) (setq msg (if f (apply #'format f a) "")))))
41 (condition-case e (org-table-iterate) (user-error (setq msg (error-message-string e)))))
42 (goto-char (point-max)) (insert msg))
43 """))
44 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
45 switch TableIterate().run(in: context) {
46 case .commit(let result):
47 let new = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
48 let message = result.effects.compactMap { if case .message(let m) = $0 { m } else { nil } }.last ?? ""
49 ours.append(new + message)
50 case .failed(let message): ours.append("failed: " + message)
51 default: ours.append("other")
52 }
53 }
54 let results = try EmacsOracle.run(cases)
55 for (mine, theirs) in zip(ours, results) {
56 #expect(mine == theirs.text, "\(theirs.error)")
57 }
58 }
59}
docs/manual/guide/03-keys.org +2 −1
@@ -930,7 +930,8 @@ When a key appears in several rows, it runs the command whose condition holds at
930| Delete Table Row (=org.table.kill-row=) | =M-S-<up>= | =⌃⌥⌘↑= | =M-K=, =SPC m b d r= (N) | In a table, deletes the row (=org-table-kill-row=). | 930| Delete Table Row (=org.table.kill-row=) | =M-S-<up>= | =⌃⌥⌘↑= | =M-K=, =SPC m b d r= (N) | In a table, deletes the row (=org-table-kill-row=). |
931| Insert Table Rule (=org.table.insert-hline=) | =C-c -= | =⌃⌘-= | =SPC m b -= (N), =SPC m b i h= (N) | In a table, inserts a horizontal rule (=org-table-insert-hline=). | 931| Insert Table Rule (=org.table.insert-hline=) | =C-c -= | =⌃⌘-= | =SPC m b -= (N), =SPC m b i h= (N) | In a table, inserts a horizontal rule (=org-table-insert-hline=). |
932| Recalculate Table Row (=org.table.recalc=) | =C-c *= | =⌃⌘*= | — | In a table, recalculates the current row (=org-table-recalculate=). On a US keyboard, =⌃⌘*= is typed =⌃⇧⌘8=. | 932| Recalculate Table Row (=org.table.recalc=) | =C-c *= | =⌃⌘*= | — | In a table, recalculates the current row (=org-table-recalculate=). On a US keyboard, =⌃⌘*= is typed =⌃⇧⌘8=. |
933| Recalculate Table (=org.table.recalc-all=) | =C-c C-c= | =⌃⌘X= | =SPC m b r= (N) | Recalculates the whole table; =C-c C-c= and =⌃⌘X= run it on a =#+TBLFM= line (=org-table-recalculate= with =C-u=). | 933| Recalculate Table (=org.table.recalc-all=) | =C-c C-c=, =C-u C-c *= | =⌃⌘X= | =SPC m b r= (N) | Recalculates the whole table; =C-c C-c= and =⌃⌘X= run it on a =#+TBLFM= line (=org-table-recalculate= with =C-u=). |
934| Iterate Table Formulas (=org.table.iterate=) | =C-u C-u C-c *= | — | — | Recalculates the whole table until it stops changing, at most ten times (=org-table-iterate=). |
934| Set Column Formula (=org.table.column-formula=) | ~C-c =~ | — | — | Asks for the column's formula, offering the stored one (=org-table-eval-formula=). | 935| Set Column Formula (=org.table.column-formula=) | ~C-c =~ | — | — | Asks for the column's formula, offering the stored one (=org-table-eval-formula=). |
935| Edit Table Field (=org.table.edit-field=) | =C-c `= | — | — | In a table, edits the field in a separate editor (=org-table-edit-field=). | 936| Edit Table Field (=org.table.edit-field=) | =C-c `= | — | — | In a table, edits the field in a separate editor (=org-table-edit-field=). |
936| Shrink or Expand Table Column (=org.table.toggle-column-width=) | =C-c TAB= | — | — | In a table, shrinks or expands the column (=org-table-toggle-column-width=). | 937| Shrink or Expand Table Column (=org.table.toggle-column-width=) | =C-c TAB= | — | — | In a table, shrinks or expands the column (=org-table-toggle-column-width=). |
docs/manual/guide/10-tables.org +13 −6
@@ -489,6 +489,7 @@ The formulas are stored sorted the way =org-table-formula-less-p= sorts them.
489|----------------------------------+-----------------------------------+-------------------------------+-----------------------------+-------------------------------------| 489|----------------------------------+-----------------------------------+-------------------------------+-----------------------------+-------------------------------------|
490| Recalculate Table | =org-table-recalculate= with =C-u= | =C-c C-c= on =#+TBLFM:= | =⌃⌘X= on =#+TBLFM:= | =SPC m b r=, =C-c C-c= on =#+TBLFM:= | 490| Recalculate Table | =org-table-recalculate= with =C-u= | =C-c C-c= on =#+TBLFM:= | =⌃⌘X= on =#+TBLFM:= | =SPC m b r=, =C-c C-c= on =#+TBLFM:= |
491| Recalculate Table Row | =org-table-recalculate= | =C-c *= | =⌃⌘*= (=⌃⇧⌘8= on a US keyboard) | =C-c *= | 491| Recalculate Table Row | =org-table-recalculate= | =C-c *= | =⌃⌘*= (=⌃⇧⌘8= on a US keyboard) | =C-c *= |
492| Iterate Table Formulas | =org-table-iterate= | =C-u C-u C-c *= | — | — |
492 493
493In Doom's normal state, =RET= in a table recalculates it when it has a =#+TBLFM:= 494In Doom's normal state, =RET= in a table recalculates it when it has a =#+TBLFM:=
494line and aligns it otherwise; on a =#+TBLFM:= line it recalculates. 495line and aligns it otherwise; on a =#+TBLFM:= line it recalculates.
@@ -497,12 +498,18 @@ When the table has a rule below its first data row, recalculating the whole tabl
497leaves the rows above that rule, the header, alone. With marked rows, the marks decide 498leaves the rows above that rule, the header, alone. With marked rows, the marks decide
498instead (see /Names, parameters and constants/). Each 499instead (see /Names, parameters and constants/). Each
499command evaluates the column formulas row by row, then the field formulas, then aligns 500command evaluates the column formulas row by row, then the field formulas, then aligns
500the table. Formulas are evaluated once; Org's iterate-until-stable recalculation 501the table. Each formula is evaluated once. Iterate Table Formulas recalculates the whole
501(=C-u C-u C-c *=) isn't available. 502table again and again until it stops changing, for formulas that depend on each other's
502 503results, at most ten times. The echo area says =Convergence after 3 iterations=, or
503Tables are not recalculated automatically. Rows marked =#= are not recalculated when 504=Table was already stable=; after ten passes that still change the table it says =No
504you press =TAB= or =RET= in them, as =org-table-maybe-recalculate-line= would do in 505convergence after 10 iterations=, and the ten passes stay. =C-u C-c *= also recalculates
505Emacs; recalculate with one of the commands above, or with =C-c C-c= (Mac =⌃⌘X=) in the row. 506the whole table in the Emacs preset.
507
508A row marked =#= is recalculated when you press =TAB=, =S-TAB= or =RET= in it, before
509the caret moves (=org-table-maybe-recalculate-line=), and with =C-c C-c= (Mac =⌃⌘X=).
510Other rows are recalculated only by the commands above. Emacs skips a second automatic
511recalculation of the same row by the same command in a row; orgstar recalculates each
512time, which gives the same result unless a formula depends on its own value.
506 513
507* When Emacs is needed 514* When Emacs is needed
508 515