Commit 918b9bb6b0

918b9bb6b0c1158ef0b763a70206a0efbf56f091

parent: fa7dd01882

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 19:23 UTC

Keep table fields written before a formula that needs Emacs

The Mac App Store and iOS builds apply formulas up to the first one only Emacs can do and keep the fields written before it, as Emacs leaves a table whose formula fails. The Developer ID build still recalculates the whole table in Emacs. Errors partway through now leave the written fields in every build, and a field formula's one-space field gets its column formula first, as in Org.

Layout: unified · split

Sources/OrgCore/Commands/Command.swift +4 −1
@@ -301,7 +301,10 @@ public enum CommandStep: Sendable, Equatable {
301301public enum ExternalRequest: Sendable, Equatable {
302302 /// Recalculate the table whose text is at `table` in Emacs, running `form` with point at
303303 /// `point`, and put Emacs's table text in its place. `lisp` when its formulas run Lisp.
304 case emacsTable(table: Range<Int>, point: Int, form: String, reason: String, lisp: Bool)
304 /// `partial` is the fields written before `formula`, the one that needs Emacs, left as
305 /// Emacs leaves a table whose formula fails; builds without Emacs commit it. Both are nil
306 /// when nothing was written.
307 case emacsTable(table: Range<Int>, point: Int, form: String, reason: String, lisp: Bool, formula: String? = nil, partial: EditResult? = nil)
305308 /// Run a src block; `Babel.finish` turns its output into the result edit.
306309 case babel(BabelJob)
307310 /// Follow a link: the app opens URLs and files and searches headings.
Sources/OrgCore/Commands/CtrlCCtrlC.swift +2 −7
@@ -24,16 +24,11 @@ public struct CtrlCCtrlC: OrgCommand {
2424 if TableRecalculate.tblfmLine(in: context) != nil || atStart { return TableRecalculate(all: true).run(in: context) }
2525 // `org-table-maybe-eval-formula`, then `org-table-maybe-recalculate-line` on a row
2626 // marked `#`, which aligns, or else `org-table-align`.
27 let step = commitBuffer(context) { buffer in
27 return TableRecalculate.recalculating(context, form: "(org-ctrl-c-ctrl-c)") { buffer in
2828 try buffer.tableMaybeEvalFormula()
2929 guard buffer.lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else { return buffer.tableAlign() }
30 do {
31 try buffer.tableRecalculate(all: false)
32 } catch let error as Calc.Unsupported {
33 throw EmacsBuffer.UserError(message: TableRecalculate.emacsMessage + error.reason)
34 }
30 try buffer.tableRecalculate(all: false)
3531 }
36 return TableRecalculate.inEmacs(step, form: "(org-ctrl-c-ctrl-c)", in: context)
3732 }
3833 // Org says to edit table.el tables with C-c '; here their borders line up again.
3934 if KeyContext.holds("table-el", in: context) { return TableElAlign().run(in: context) }
Sources/OrgCore/Compute/Calc.swift +2
@@ -7,6 +7,8 @@ import Foundation
77public enum Calc {
88 public struct Unsupported: Error, Equatable, CustomStringConvertible {
99 public let reason: String
10 /// The left-hand side of the table formula that threw, once recalculation knows it.
11 public var formula: String?
1012 public var description: String { reason }
1113 init(_ reason: String) { self.reason = reason }
1214 }
Sources/OrgCore/Compute/TableFormulaCommands.swift +59 −40
@@ -1,8 +1,7 @@
11import Foundation
22
33/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the
4/// native evaluator can't do fail with `TableRecalculate.emacsMessage`, and the app
5/// recalculates them in Emacs.
4/// native evaluator can't do become a request to recalculate them in Emacs.
65public struct TableRecalculate: OrgCommand {
76 public let all: Bool
87 public init(all: Bool) { self.all = all }
@@ -23,38 +22,64 @@ public struct TableRecalculate: OrgCommand {
2322 }
2423
2524 public func run(in context: EditContext) -> CommandStep {
26 let step = commitBuffer(context) { buffer in
27 do {
28 if let line = Self.tblfmLine(in: context) {
29 // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
30 // point at the end of the table.
31 let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
32 let saved = buffer.marker(buffer.point)
33 defer { buffer.release(saved) }
34 guard let tableEnd = buffer.saveExcursion({ () -> Int? in
35 while buffer.forwardLine(-1) == 0 {
36 if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
37 }
38 return nil
39 }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
40 buffer.point = tableEnd
41 try buffer.tableRecalculate(all: true, tblfm: formulas)
25 let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
26 return Self.recalculating(context, form: form) { buffer in
27 if let line = Self.tblfmLine(in: context) {
28 // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
29 // point at the end of the table, then back where it was, even after an error.
30 let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
31 let saved = buffer.marker(buffer.point)
32 defer {
4233 buffer.point = saved.position
43 } else {
44 try buffer.tableRecalculate(all: all)
34 buffer.release(saved)
4535 }
36 guard let tableEnd = buffer.saveExcursion({ () -> Int? in
37 while buffer.forwardLine(-1) == 0 {
38 if buffer.lookingAtLine("^[ \\t]*\\|") { return buffer.lineEnd(buffer.point) }
39 }
40 return nil
41 }) else { throw EmacsBuffer.UserError(message: "Not at a table") }
42 buffer.point = tableEnd
43 try buffer.tableRecalculate(all: true, tblfm: formulas)
44 } else {
45 try buffer.tableRecalculate(all: all)
46 }
47 }
48 }
49
50 /// `commitBuffer` for a recalculation. On an error the fields written before it stay, as
51 /// in Emacs, with the error as the message. A formula the native evaluator can't do makes
52 /// a request to run `form` in Emacs, which carries those fields for builds without Emacs.
53 static func recalculating(_ context: EditContext, form: String, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
54 var failure: String?
55 var unsupported: Calc.Unsupported?
56 let step = commitBuffer(context) { buffer in
57 do {
58 try body(buffer)
59 } catch let error as EmacsBuffer.UserError {
60 failure = error.message
4661 } catch let error as Calc.Unsupported {
47 throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason)
62 unsupported = error
4863 }
4964 }
50 let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
51 return Self.inEmacs(step, form: form, in: context)
65 guard case .commit(let result) = step else { return step }
66 if let unsupported {
67 let wrote = !result.edits.isEmpty
68 return request(form: form, reason: unsupported.reason, formula: wrote ? unsupported.formula : nil, partial: wrote ? result : nil, in: context)
69 }
70 guard let failure else { return step }
71 guard !result.edits.isEmpty else { return .failed(failure) }
72 return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(failure)]))
5273 }
5374
5475 /// A step that failed with `emacsMessage` as a request to run `form` on the table in
5576 /// Emacs, whose text then replaces the table here; other steps unchanged.
5677 static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep {
5778 guard case .failed(let message) = step, message.hasPrefix(emacsMessage) else { return step }
79 return request(form: form, reason: String(message.dropFirst(emacsMessage.count)), formula: nil, partial: nil, in: context)
80 }
81
82 static func request(form: String, reason: String, formula: String?, partial: EditResult?, in context: EditContext) -> CommandStep {
5883 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
5984 let onTblfm = tblfmLine(in: context) != nil
6085 if onTblfm {
@@ -64,7 +89,7 @@ public struct TableRecalculate: OrgCommand {
6489 let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
6590 return .external(.emacsTable(
6691 table: table, point: context.caret, form: form,
67 reason: String(message.dropFirst(emacsMessage.count)), lisp: tblfm.contains("'(")
92 reason: reason, lisp: tblfm.contains("'("), formula: formula, partial: partial
6893 ))
6994 }
7095}
@@ -79,30 +104,24 @@ public struct TableIterate: OrgCommand {
79104
80105 public func run(in context: EditContext) -> CommandStep {
81106 var message = ""
82 var step = commitBuffer(context) { buffer in
107 let step = TableRecalculate.recalculating(context, form: "(org-table-iterate)") { buffer in
83108 guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
84109 func table() -> String { buffer.substring(buffer.tableBegin(), buffer.tableEnd()) }
85110 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
111 for iteration in 1...10 {
112 try buffer.tableRecalculate(all: true)
113 let this = table()
114 if this == last {
115 message = iteration > 1 ? "Convergence after \(iteration) iterations" : "Table was already stable"
116 return
95117 }
96 } catch let error as Calc.Unsupported {
97 throw EmacsBuffer.UserError(message: TableRecalculate.emacsMessage + error.reason)
118 last = this
98119 }
99120 // The recalculations stay, as Emacs leaves them before its error.
100121 message = "No convergence after 10 iterations"
101122 }
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)
123 guard case .commit(let result) = step, !message.isEmpty else { return step }
124 return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(message)]))
106125 }
107126}
108127
Sources/OrgCore/Compute/TableFormulas.swift +35 −21
@@ -752,47 +752,51 @@ extension EmacsBuffer {
752752 guard let line = tblfm ?? firstTblfm(after: end) else { return }
753753 let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
754754 guard !stored.isEmpty else { return }
755 var columnEquations: [(Int, String)] = []
756 var fieldEquations: [(String, String)] = []
755 // `org-table-save-field`: the field is restored even when a formula fails.
756 let savedLine = lineStart(point)
757 let savedColumn = tableCurrentColumn()
758 let lineMarker = marker(savedLine)
759 defer { release(lineMarker) }
760 defer {
761 point = lineMarker.position
762 tableGotoColumn(savedColumn)
763 }
764 var columnEquations: [(column: Int, rhs: String, lhs: String)] = []
765 var fieldEquations: [(String, String, String)] = []
757766 for (oldLHS, rawRHS) in stored {
758767 let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis)
759768 if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
760769 let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
761770 if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil {
762 columnEquations.append((try Self.integer(String(lhs.dropFirst())), rhs))
771 columnEquations.append((try Self.integer(String(lhs.dropFirst())), rhs, oldLHS))
763772 } else {
764 fieldEquations.append((lhs, rhs))
773 fieldEquations.append((lhs, rhs, oldLHS))
765774 }
766775 }
767776 // `org-table-expand-lhs-ranges`.
768 var fields: [(row: Int, column: Int, rhs: String)] = []
769 for (lhs, rhs) in fieldEquations {
777 var fields: [(row: Int, column: Int, rhs: String, lhs: String)] = []
778 for (lhs, rhs, oldLHS) in fieldEquations {
770779 if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) {
771 fields.append((try Self.integer(String(m.1)), try Self.integer(String(m.2)), rhs))
780 fields.append((try Self.integer(String(m.1)), try Self.integer(String(m.2)), rhs, oldLHS))
772781 } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil {
773782 guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else {
774783 throw UserError(message: "Unknown field: \(lhs)")
775784 }
776 fields.append((row, location.column, rhs))
785 fields.append((row, location.column, rhs, oldLHS))
777786 } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil {
778787 // `org-table-goto-field` knows only absolute fields and names.
779788 throw UserError(message: "Unknown field: \(lhs)")
780789 } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
781790 let row = try Self.integer(String(m.1))
782 for c in 1...analysis.ncol { fields.append((row, c, rhs)) }
791 for c in 1...analysis.ncol { fields.append((row, c, rhs, oldLHS)) }
783792 } else {
784793 let corners = try rangeCorners(lhs, analysis: analysis)
785794 guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
786795 throw Calc.Unsupported("formula range")
787796 }
788 for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs)) } }
797 for r in r1...r2 { for c in corners.c1...corners.c2 { fields.append((r, c, rhs, oldLHS)) } }
789798 }
790799 }
791 let savedLine = lineStart(point)
792 let savedColumn = tableCurrentColumn()
793 let lineMarker = marker(savedLine)
794 defer { release(lineMarker) }
795
796800 let endMarker = marker(end)
797801 defer { release(endMarker) }
798802 var beg: Int
@@ -843,11 +847,13 @@ extension EmacsBuffer {
843847 point = rowStart
844848 return tableCurrentDataLine()
845849 }
846 for (column, rhs) in columnEquations {
850 for (column, rhs, lhs) in columnEquations {
847851 point = rowMarker.position
848852 tableGotoColumn(column, force: true)
849 if untouchable.contains("@\(dline)$\(column)") { continue }
850 try tableEvalFormula(rhs, analysis: analysis)
853 // Org reads the mark at point, which in a field of one space is on the bar
854 // after it, so the column formula still runs there.
855 if untouchable.contains("@\(dline)$\(column)"), let c = character(at: point), c != 124, c != 10 { continue }
856 try Self.naming(lhs) { try tableEvalFormula(rhs, analysis: analysis) }
851857 }
852858 }
853859 point = rowMarker.position
@@ -858,11 +864,19 @@ extension EmacsBuffer {
858864 let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
859865 if field.column > count { throw UserError(message: "Missing columns in the table. Aborting") }
860866 tableGotoColumn(field.column)
861 try tableEvalFormula(field.rhs, analysis: analysis)
867 try Self.naming(field.lhs) { try tableEvalFormula(field.rhs, analysis: analysis) }
862868 }
863869 tableAlign()
864 point = lineMarker.position
865 tableGotoColumn(savedColumn)
870 }
871
872 /// `body`, with the formula `lhs` named in a `Calc.Unsupported` it throws.
873 static func naming(_ lhs: String, _ body: () throws -> Void) throws {
874 do {
875 try body()
876 } catch var error as Calc.Unsupported {
877 error.formula = lhs
878 throw error
879 }
866880 }
867881
868882 /// `org-table-get-range` with `corners-only`.
Sources/Orgstar/ContentView.swift +14 −3
@@ -1049,11 +1049,22 @@ struct ContentView: View {
10491049 case .columnView(let view):
10501050 panel = .columns(UUID(), view)
10511051 #if APPSTORE
1052 case .emacsTable(_, _, _, let reason, _):
1053 commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1052 case .emacsTable(_, _, _, let reason, _, let formula, let partial):
1053 // The fields written before the formula stay, as Emacs leaves them when a formula fails.
1054 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1055 if let formula {
1056 commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1057 } else {
1058 commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1059 }
10541060 #else
1055 case .emacsTable(let table, let point, let form, let reason, let lisp):
1061 case .emacsTable(let table, let point, let form, let reason, let lisp, let formula, let partial):
10561062 guard EmacsRunner.executable() != nil else {
1063 // Without Emacs this is the App Store build's case: keep the fields written so far.
1064 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1065 if let formula {
1066 return commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1067 }
10571068 return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
10581069 }
10591070 let run = {
Sources/OrgstarMobile/MobileEditor.swift +7 −1
@@ -334,6 +334,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
334334 case .external(.columnView(let view)) where onColumnView != nil:
335335 onColumnView?(view)
336336 case .external(let request):
337 // The fields written before a formula only Emacs can do stay, as Emacs leaves them
338 // when a formula fails.
339 if case .emacsTable(_, _, _, _, _, _, let partial?) = request { _ = perform(PrecomputedEdit(partial)) }
337340 onMessage?(Self.unavailable(request, title: command.title))
338341 }
339342 return step
@@ -341,7 +344,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
341344
342345 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
343346 static func unavailable(_ request: ExternalRequest, title: String) -> String {
344 if case .emacsTable(_, _, _, let reason, _) = request {
347 if case .emacsTable(_, _, _, let reason, _, let formula?, _) = request {
348 return String(localized: "The table was recalculated up to \(formula), which needs Emacs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas calculated up to one only Emacs can calculate")
349 }
350 if case .emacsTable(_, _, _, let reason, _, _, _) = request {
345351 return String(localized: "This table needs Emacs, which runs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas only Emacs can calculate")
346352 }
347353 return String(localized: "\(CommandTitle.localized(title)) isn't available on iPhone and iPad.", comment: "A command that runs only on the Mac")
Tests/OrgCoreTests/TableFormulaTests.swift +78 −7
@@ -26,6 +26,14 @@ struct TableFormulaTests {
2626 "| a |\n|---|\n| 1 |\n| 2 |\n|---|\n| |\n#+TBLFM: @>$1=vmax(@I..@II)-vmin(@I..@II)+vcount(@I..@II)+vmedian(@I..@II)\n",
2727 "#+CONSTANTS: c=10 k=2.5\n| a | b |\n|---+---|\n| 1 | |\n| 2 | |\n#+TBLFM: $2=$1*$c+$k\n",
2828 "* Rates\n:PROPERTIES:\n:Rate: 3\n:END:\n| h | pay |\n|---+-----|\n| 2 | |\n#+TBLFM: $2=$1*$PROP_Rate\n",
29 // Errors partway through: the fields written before them stay.
30 "| a | b | c |\n|---+---+---|\n| 1 | | |\n| 22 | | |\n| 3 | | |\n#+TBLFM: $2=$1*2::$3=@-2$1\n",
31 "| a | b | c |\n|---+---+---|\n| 1 | | |\n| 22 | | |\n| 3 | | |\n#+TBLFM: $2=$1*2::@3$3=@-5$1::@2$3=7\n",
32 "| a | b |\n|---+---|\n| 1 | |\n| 2 | |\n#+TBLFM: $2=$1::@I$1=3\n",
33 "| a | b |\n|---+---|\n| 1 | |\n| 2 | |\n#+TBLFM: $2=$1*3::@2$2=1::@2$1..@3$2=5\n",
34 // A field formula's field of one space still gets the column formula first.
35 "| a | b |\n|---+---|\n| # | |\n| 2 | |\n#+TBLFM: $2=@0$1+1::@3$2=$2*10\n",
36 "| a | b |\n|---+---|\n| # | |\n| 2 | |\n| 3 ||\n#+TBLFM: $2=@0$1+1::@3$2=$2*10::@4$2=$2*10\n",
2937 ]
3038
3139 /// Lisp formulas, names, parameters, marked rows, remote tables, durations, dates and
@@ -128,7 +136,7 @@ struct TableFormulaTests {
128136 : [(TableRecalculate(all: true), "(org-table-recalculate t)"), (TableRecalculate(all: false), "(org-table-recalculate nil)")]
129137 for (command, form) in commands {
130138 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: form))
131 ours.append(runCommand(command, text, caret: caret))
139 ours.append(Self.recalculate(command, text, caret: caret))
132140 }
133141 }
134142 }
@@ -143,12 +151,6 @@ struct TableFormulaTests {
143151 #expect(failure.contains("non-numeric field") || failure.contains("division by zero"), "\(failure)")
144152 continue
145153 }
146 if !theirs.error.isEmpty {
147 // Emacs keeps the fields written before the error; nothing changes here.
148 #expect(mine.failure == theirs.error && mine.text == cases[i].text,
149 "\(cases[i].form) at \(cases[i].point): ours \(mine.failure ?? "-"), emacs \(theirs.error)\n\(cases[i].text)")
150 continue
151 }
152154 let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error)
153155 #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2,
154156 "\(cases[i].form) at \(cases[i].point) in\n\(cases[i].text)\nours:\n\(mine.text)@\(mine.caret) \(mine.failure ?? "")\nemacs:\n\(theirs.text)@\(expected.1) \(theirs.error)")
@@ -156,6 +158,75 @@ struct TableFormulaTests {
156158 #expect(fallbacks < ours.count / 2, "\(fallbacks) fallbacks")
157159 }
158160
161 /// Two formulas, then one only Emacs can do: in row order, as Emacs applies them.
162 static let unsupported = "| a | b | c | d |\n|---+---+---+---|\n| 1 | | | |\n| 2 | | | |\n#+TBLFM: $2=$1*2::$3=$1+1::$4='(shell-command-to-string $1)\n"
163
164 @Test func keepsFieldsWrittenBeforeAFormulaOnlyEmacsCanDo() {
165 let text = Self.unsupported
166 let caret = (text as NSString).range(of: "#+TBLFM").location + 3
167 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
168 guard case .external(.emacsTable(_, _, _, let reason, let lisp, let formula, let partial?)) = TableRecalculate(all: true).run(in: context) else {
169 Issue.record("not a request")
170 return
171 }
172 #expect(reason == "Lisp function shell-command-to-string")
173 #expect(lisp)
174 #expect(formula == "$4")
175 let result = partial.edits.reduce(text) { $1.apply(to: $0) }
176 #expect(result == "| a | b | c | d |\n|---+---+---+---|\n| 1 | 2 | 2 | |\n| 2 | | | |\n#+TBLFM: $2=$1*2::$3=$1+1::$4='(shell-command-to-string $1)\n")
177 // Point stays on the #+TBLFM line, after the two digits written.
178 #expect(partial.selection == [(caret + 4)..<(caret + 4)])
179 }
180
181 /// The fields kept before a formula only Emacs can do are what Emacs leaves when that
182 /// formula fails instead.
183 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
184 func keptFieldsMatchEmacsAfterAnError() throws {
185 let failing = "@-9$1"
186 let lisp = "'(shell-command-to-string $1)"
187 let tables = [
188 Self.unsupported,
189 "| a | b | c |\n|---+---+---|\n| 1 | | |\n| 2 | | |\n| 3 | | |\n#+TBLFM: $2=$1*3::@3$3=\(lisp)::@2$3=7::@4$3=8\n",
190 "| a | b |\n|---+---|\n| # | |\n| 2 | |\n#+TBLFM: $2=@0$1+1::@3$2=\(lisp)\n",
191 ]
192 var cases: [EmacsOracle.Case] = []
193 var ours: [(text: String, caret: Int)] = []
194 for text in tables {
195 let emacsText = text.replacingOccurrences(of: lisp, with: failing)
196 for caret in Self.carets(text) {
197 let onTblfm = (text as NSString).substring(with: (text as NSString).lineRange(for: NSRange(location: caret, length: 0))).contains("#+TBLFM")
198 let commands: [(any OrgCommand, String)] = onTblfm
199 ? [(TableRecalculate(all: true), "(org-ctrl-c-ctrl-c)")]
200 : [(TableRecalculate(all: true), "(org-table-recalculate t)"), (TableRecalculate(all: false), "(org-table-recalculate nil)"), (TableIterate(), "(org-table-iterate)")]
201 for (command, form) in commands {
202 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
203 let step = command.run(in: context)
204 // Rows at point without the Lisp formula, and header rows Calc reads as symbols.
205 guard case .external(.emacsTable(_, _, _, let reason, _, _, let partial?)) = step, reason.hasPrefix("Lisp") else { continue }
206 cases.append(EmacsOracle.Case(text: emacsText, point: EmacsOracle.point(caret, in: emacsText), form: form))
207 let new = partial.edits.reduce(text) { $1.apply(to: $0) }
208 ours.append((new, partial.selection?.first?.lowerBound ?? caret))
209 }
210 }
211 }
212 #expect(cases.count >= 8)
213 for (i, (theirs, mine)) in zip(try EmacsOracle.run(cases), ours).enumerated() {
214 #expect(theirs.error.contains("leads outside table"), "\(theirs.error)")
215 let text = theirs.text.replacingOccurrences(of: failing, with: lisp)
216 let point = EmacsOracle.offset(theirs.point, in: theirs.text)
217 let shifted = point > (theirs.text as NSString).range(of: failing).location ? point + (text as NSString).length - (theirs.text as NSString).length : point
218 #expect(mine.text == text && mine.caret == shifted, "\(cases[i].form) at \(cases[i].point)\nours:\n\(mine.text)@\(mine.caret)\nemacs:\n\(text)@\(shifted)")
219 }
220 }
221
222 /// `runCommand`, with the message of an error that left fields written as the failure.
223 static func recalculate(_ command: any OrgCommand, _ text: String, caret: Int) -> (text: String, caret: Int, failure: String?) {
224 let result = runCommand(command, text, caret: caret)
225 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
226 guard case .commit(let commit) = command.run(in: context), case .message(let message) = commit.effects.last else { return result }
227 return (result.text, result.caret, message)
228 }
229
159230 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: C-c C-c on every `#+TBLFM` line below the folder.
160231 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
161232 func corpusMatchesEmacs() throws {
Tests/OrgProgramsTests/ProgramsTests.swift +2 −2
@@ -27,7 +27,7 @@ struct EmacsFallbackTests {
2727 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
2828 session.open(file.path)
2929 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
30 guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else {
30 guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp, _, _)) = step else {
3131 Issue.record("\(step)")
3232 return
3333 }
@@ -46,7 +46,7 @@ struct EmacsFallbackTests {
4646 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
4747 session.open(file.path)
4848 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil)
49 guard case .external(.emacsTable(let table, let point, let form, _, _)) = step else {
49 guard case .external(.emacsTable(let table, let point, let form, _, _, _, _)) = step else {
5050 Issue.record("\(step)")
5151 return
5252 }
docs/manual/guide/10-tables.org +11 −2
@@ -568,6 +568,10 @@ results, at most ten times. The echo area says =Convergence after 3 iterations=,
568568convergence after 10 iterations=, and the ten passes stay. =C-u C-c *= also recalculates
569569the whole table in the Emacs preset.
570570
571A formula that fails, such as one whose reference leads outside the table, stops the
572command there. As in Emacs, the fields written before it stay, the table isn't aligned,
573and the echo area shows the error.
574
571575A row marked =#= is recalculated when you press =TAB=, =S-TAB= or =RET= in it, before
572576the caret moves (=org-table-maybe-recalculate-line=), and with =C-c C-c= (Mac =⌃⌘X=).
573577Other rows are recalculated only by the commands above. Emacs skips a second automatic
@@ -606,8 +610,13 @@ Edit ▸ Cancel Running Task (=⌘.=) stops the recalculation; the echo area sho
606610export in Emacs cancels the one that is running.
607611
608612The [[file:../install.org][Mac App Store version]] doesn't run Emacs, so it recalculates
609only the tables orgstar computes itself. For any other table the echo area shows =This
610table's formulas can't be calculated here: (reason).=, and the table is unchanged.
613only the tables orgstar computes itself. In any other table it applies the formulas in
614Emacs's order up to the first one it can't compute and stops there, as Emacs does when a
615formula fails: the fields written before it stay, unaligned, and the rest are unchanged.
616The echo area shows =The table was recalculated up to (formula), which can't be
617calculated here: (reason).=, where /formula/ is the left-hand side, such as =$4=. When nothing
618was written, it shows =This table's formulas can't be calculated here: (reason).= and the
619table is unchanged.
611620
612621If the table's formulas contain Lisp, orgstar asks first:
613622=This table's formulas run Lisp. Run them? (yes, no, always)=. =always= trusts this
docs/manual/guide/14-ios.org +1 −1
@@ -343,7 +343,7 @@ On iOS, only Emacs Lisp and JavaScript blocks run. orgstar evaluates Emacs Lisp
343343- Emacs Lisp the interpreter doesn't have: "This block uses Emacs Lisp that runs only in Emacs, on the Mac."
344344- JavaScript that uses something only node has, such as =Buffer=: "This block uses /name/, which runs only in node."
345345
346Table formulas that orgstar computes itself work on iOS. A table whose formulas need Emacs reports "This table needs Emacs, which runs on the Mac", with the reason, and isn't changed.
346Table formulas that orgstar computes itself work on iOS. In a table whose formulas need Emacs, orgstar applies the formulas up to the first one that needs it and stops there, as Emacs does when a formula fails: the fields written before it stay and the rest are unchanged. The message is "The table was recalculated up to /formula/, which needs Emacs on the Mac", with the formula's left-hand side and the reason. When nothing was written, it is "This table needs Emacs, which runs on the Mac", with the reason, and the table is unchanged.
347347
348348Tangling (=C-c C-v t=, in Commands) works on iOS and writes the tangled files next to the org file, or where =:tangle= says.
349349
docs/manual/install.org +3 −2
@@ -69,8 +69,9 @@ App Store version.
6969A block in another language reports "/language/ blocks don't run in this version of
7070orgstar." An Emacs Lisp block that uses more than the interpreter has reports "This block uses
7171Emacs Lisp that runs only in Emacs." A JavaScript block that uses something only node has
72reports "This block uses /name/, which runs only in node." A table whose formulas need Emacs reports "This table's
73formulas can't be calculated here", with the reason, and isn't changed. The Emacs exports are
72reports "This block uses /name/, which runs only in node." A table whose formulas need Emacs is recalculated up to
73the first formula that needs it, which the message names with the reason; the fields
74before it stay and the rest are unchanged. The Emacs exports are
7475not in the File ▸ Export menu, the export dialog or the command palette; a key bound to
7576Export to PDF with Emacs exports to PDF without LaTeX. LaTeX export is orgstar's own and is in
7677both versions; a file it can't write as Emacs would reports "Can't export to LaTeX", with the
l10n/Localizable.xcstrings +70
@@ -30695,6 +30695,76 @@
3069530695 }
3069630696 }
3069730697 },
30698 "The table was recalculated up to %@, which can't be calculated here: %@.": {
30699 "comment": "Table formulas orgstar calculated up to one it can't",
30700 "localizations": {
30701 "de": {
30702 "stringUnit": {
30703 "state": "translated",
30704 "value": "Die Tabelle wurde bis %@ neu berechnet, das hier nicht berechnet werden kann: %@."
30705 }
30706 },
30707 "es": {
30708 "stringUnit": {
30709 "state": "translated",
30710 "value": "La tabla se recalculó hasta %@, que no se puede calcular aquí: %@."
30711 }
30712 },
30713 "fr": {
30714 "stringUnit": {
30715 "state": "translated",
30716 "value": "Le tableau a été recalculé jusqu'à %@, qui ne peut pas être calculé ici : %@."
30717 }
30718 },
30719 "ja": {
30720 "stringUnit": {
30721 "state": "translated",
30722 "value": "表は%@の手前まで再計算されました。ここでは計算できません:%@。"
30723 }
30724 },
30725 "pt-BR": {
30726 "stringUnit": {
30727 "state": "translated",
30728 "value": "A tabela foi recalculada até %@, que não pode ser calculada aqui: %@."
30729 }
30730 }
30731 }
30732 },
30733 "The table was recalculated up to %@, which needs Emacs on the Mac: %@.": {
30734 "comment": "Table formulas calculated up to one only Emacs can calculate",
30735 "localizations": {
30736 "de": {
30737 "stringUnit": {
30738 "state": "translated",
30739 "value": "Die Tabelle wurde bis %@ neu berechnet, das Emacs auf dem Mac braucht: %@."
30740 }
30741 },
30742 "es": {
30743 "stringUnit": {
30744 "state": "translated",
30745 "value": "La tabla se recalculó hasta %@, que necesita Emacs en el Mac: %@."
30746 }
30747 },
30748 "fr": {
30749 "stringUnit": {
30750 "state": "translated",
30751 "value": "Le tableau a été recalculé jusqu'à %@, qui nécessite Emacs sur Mac : %@."
30752 }
30753 },
30754 "ja": {
30755 "stringUnit": {
30756 "state": "translated",
30757 "value": "表は%@の手前まで再計算されました。MacのEmacsが必要です:%@。"
30758 }
30759 },
30760 "pt-BR": {
30761 "stringUnit": {
30762 "state": "translated",
30763 "value": "A tabela foi recalculada até %@, que precisa do Emacs no Mac: %@."
30764 }
30765 }
30766 }
30767 },
3069830768 "The template to capture with.": {
3069930769 "localizations": {
3070030770 "de": {