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 {
301public enum ExternalRequest: Sendable, Equatable { 301public enum ExternalRequest: Sendable, Equatable {
302 /// Recalculate the table whose text is at `table` in Emacs, running `form` with point at 302 /// Recalculate the table whose text is at `table` in Emacs, running `form` with point at
303 /// `point`, and put Emacs's table text in its place. `lisp` when its formulas run Lisp. 303 /// `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)
305 /// Run a src block; `Babel.finish` turns its output into the result edit. 308 /// Run a src block; `Babel.finish` turns its output into the result edit.
306 case babel(BabelJob) 309 case babel(BabelJob)
307 /// Follow a link: the app opens URLs and files and searches headings. 310 /// 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 {
24 if TableRecalculate.tblfmLine(in: context) != nil || atStart { return TableRecalculate(all: true).run(in: context) } 24 if TableRecalculate.tblfmLine(in: context) != nil || atStart { return TableRecalculate(all: true).run(in: context) }
25 // `org-table-maybe-eval-formula`, then `org-table-maybe-recalculate-line` on a row 25 // `org-table-maybe-eval-formula`, then `org-table-maybe-recalculate-line` on a row
26 // marked `#`, which aligns, or else `org-table-align`. 26 // 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
28 try buffer.tableMaybeEvalFormula() 28 try buffer.tableMaybeEvalFormula()
29 guard buffer.lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else { return buffer.tableAlign() } 29 guard buffer.lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else { return buffer.tableAlign() }
30 do { 30 try buffer.tableRecalculate(all: false)
31 try buffer.tableRecalculate(all: false)
32 } catch let error as Calc.Unsupported {
33 throw EmacsBuffer.UserError(message: TableRecalculate.emacsMessage + error.reason)
34 }
35 } 31 }
36 return TableRecalculate.inEmacs(step, form: "(org-ctrl-c-ctrl-c)", in: context)
37 } 32 }
38 // Org says to edit table.el tables with C-c '; here their borders line up again. 33 // Org says to edit table.el tables with C-c '; here their borders line up again.
39 if KeyContext.holds("table-el", in: context) { return TableElAlign().run(in: context) } 34 if KeyContext.holds("table-el", in: context) { return TableElAlign().run(in: context) }
Sources/OrgCore/Compute/Calc.swift +2
@@ -7,6 +7,8 @@ import Foundation
7public enum Calc { 7public enum Calc {
8 public struct Unsupported: Error, Equatable, CustomStringConvertible { 8 public struct Unsupported: Error, Equatable, CustomStringConvertible {
9 public let reason: String 9 public let reason: String
10 /// The left-hand side of the table formula that threw, once recalculation knows it.
11 public var formula: String?
10 public var description: String { reason } 12 public var description: String { reason }
11 init(_ reason: String) { self.reason = reason } 13 init(_ reason: String) { self.reason = reason }
12 } 14 }
Sources/OrgCore/Compute/TableFormulaCommands.swift +59 −40
@@ -1,8 +1,7 @@
1import Foundation 1import Foundation
2 2
3/// C-c * and C-u C-c *: `org-table-recalculate`, and C-c C-c on a `#+TBLFM` line. Tables the 3/// 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 4/// native evaluator can't do become a request to recalculate them in Emacs.
5/// recalculates them in Emacs.
6public struct TableRecalculate: OrgCommand { 5public struct TableRecalculate: OrgCommand {
7 public let all: Bool 6 public let all: Bool
8 public init(all: Bool) { self.all = all } 7 public init(all: Bool) { self.all = all }
@@ -23,38 +22,64 @@ public struct TableRecalculate: OrgCommand {
23 } 22 }
24 23
25 public func run(in context: EditContext) -> CommandStep { 24 public func run(in context: EditContext) -> CommandStep {
26 let step = commitBuffer(context) { buffer in 25 let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)"
27 do { 26 return Self.recalculating(context, form: form) { buffer in
28 if let line = Self.tblfmLine(in: context) { 27 if let line = Self.tblfmLine(in: context) {
29 // `org-table-calc-current-TBLFM`: that line's formulas, every row, with 28 // `org-table-calc-current-TBLFM`: that line's formulas, every row, with
30 // point at the end of the table. 29 // point at the end of the table, then back where it was, even after an error.
31 let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " ")) 30 let formulas = String(line[line.index(after: line.firstIndex(of: ":")!)...]).trimmingCharacters(in: .init(charactersIn: " "))
32 let saved = buffer.marker(buffer.point) 31 let saved = buffer.marker(buffer.point)
33 defer { buffer.release(saved) } 32 defer {
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)
42 buffer.point = saved.position 33 buffer.point = saved.position
43 } else { 34 buffer.release(saved)
44 try buffer.tableRecalculate(all: all)
45 } 35 }
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
46 } catch let error as Calc.Unsupported { 61 } catch let error as Calc.Unsupported {
47 throw EmacsBuffer.UserError(message: Self.emacsMessage + error.reason) 62 unsupported = error
48 } 63 }
49 } 64 }
50 let form = Self.tblfmLine(in: context) != nil ? "(org-table-calc-current-TBLFM)" : all ? "(org-table-recalculate t)" : "(org-table-recalculate nil)" 65 guard case .commit(let result) = step else { return step }
51 return Self.inEmacs(step, form: form, in: context) 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)]))
52 } 73 }
53 74
54 /// A step that failed with `emacsMessage` as a request to run `form` on the table in 75 /// A step that failed with `emacsMessage` as a request to run `form` on the table in
55 /// Emacs, whose text then replaces the table here; other steps unchanged. 76 /// Emacs, whose text then replaces the table here; other steps unchanged.
56 static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep { 77 static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep {
57 guard case .failed(let message) = step, message.hasPrefix(emacsMessage) else { return step } 78 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 {
58 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options) 83 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
59 let onTblfm = tblfmLine(in: context) != nil 84 let onTblfm = tblfmLine(in: context) != nil
60 if onTblfm { 85 if onTblfm {
@@ -64,7 +89,7 @@ public struct TableRecalculate: OrgCommand {
64 let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? "" 89 let tblfm = onTblfm ? tblfmLine(in: context) ?? "" : buffer.firstTblfm(after: table.upperBound) ?? ""
65 return .external(.emacsTable( 90 return .external(.emacsTable(
66 table: table, point: context.caret, form: form, 91 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
68 )) 93 ))
69 } 94 }
70} 95}
@@ -79,30 +104,24 @@ public struct TableIterate: OrgCommand {
79 104
80 public func run(in context: EditContext) -> CommandStep { 105 public func run(in context: EditContext) -> CommandStep {
81 var message = "" 106 var message = ""
82 var step = commitBuffer(context) { buffer in 107 let step = TableRecalculate.recalculating(context, form: "(org-table-iterate)") { buffer in
83 guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") } 108 guard buffer.atTable else { throw EmacsBuffer.UserError(message: "Not at a table") }
84 func table() -> String { buffer.substring(buffer.tableBegin(), buffer.tableEnd()) } 109 func table() -> String { buffer.substring(buffer.tableBegin(), buffer.tableEnd()) }
85 var last = table() 110 var last = table()
86 do { 111 for iteration in 1...10 {
87 for iteration in 1...10 { 112 try buffer.tableRecalculate(all: true)
88 try buffer.tableRecalculate(all: true) 113 let this = table()
89 let this = table() 114 if this == last {
90 if this == last { 115 message = iteration > 1 ? "Convergence after \(iteration) iterations" : "Table was already stable"
91 message = iteration > 1 ? "Convergence after \(iteration) iterations" : "Table was already stable" 116 return
92 return
93 }
94 last = this
95 } 117 }
96 } catch let error as Calc.Unsupported { 118 last = this
97 throw EmacsBuffer.UserError(message: TableRecalculate.emacsMessage + error.reason)
98 } 119 }
99 // The recalculations stay, as Emacs leaves them before its error. 120 // The recalculations stay, as Emacs leaves them before its error.
100 message = "No convergence after 10 iterations" 121 message = "No convergence after 10 iterations"
101 } 122 }
102 if case .commit(let result) = step { 123 guard case .commit(let result) = step, !message.isEmpty else { return step }
103 step = .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(message)])) 124 return .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 } 125 }
107} 126}
108 127
Sources/OrgCore/Compute/TableFormulas.swift +35 −21
@@ -752,47 +752,51 @@ extension EmacsBuffer {
752 guard let line = tblfm ?? firstTblfm(after: end) else { return } 752 guard let line = tblfm ?? firstTblfm(after: end) else { return }
753 let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs } 753 let stored = try Self.storedFormulas(line).sorted { $0.lhs < $1.lhs }
754 guard !stored.isEmpty else { return } 754 guard !stored.isEmpty else { return }
755 var columnEquations: [(Int, String)] = [] 755 // `org-table-save-field`: the field is restored even when a formula fails.
756 var fieldEquations: [(String, String)] = [] 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)] = []
757 for (oldLHS, rawRHS) in stored { 766 for (oldLHS, rawRHS) in stored {
758 let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis) 767 let rhs = try substituteNames(try Self.handleFirstLast(rawRHS, analysis: analysis), analysis: analysis)
759 if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") } 768 if oldLHS.range(of: "^@-?I+", options: .regularExpression) != nil { throw UserError(message: "Can't assign to hline relative reference") }
760 let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis) 769 let lhs = try Self.handleFirstLast(oldLHS, analysis: analysis)
761 if lhs.range(of: "^\\$[0-9]+$", options: .regularExpression) != nil { 770 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))
763 } else { 772 } else {
764 fieldEquations.append((lhs, rhs)) 773 fieldEquations.append((lhs, rhs, oldLHS))
765 } 774 }
766 } 775 }
767 // `org-table-expand-lhs-ranges`. 776 // `org-table-expand-lhs-ranges`.
768 var fields: [(row: Int, column: Int, rhs: String)] = [] 777 var fields: [(row: Int, column: Int, rhs: String, lhs: String)] = []
769 for (lhs, rhs) in fieldEquations { 778 for (lhs, rhs, oldLHS) in fieldEquations {
770 if let m = lhs.firstMatch(of: /^@([0-9]+)\$([0-9]+)$/) { 779 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))
772 } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil { 781 } else if lhs.range(of: "^[a-zA-Z][_a-zA-Z0-9]*$", options: .regularExpression) != nil {
773 guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else { 782 guard let location = analysis.namedFields.last(where: { $0.name == lhs }), let row = Self.lineToDline(location.line, analysis) else {
774 throw UserError(message: "Unknown field: \(lhs)") 783 throw UserError(message: "Unknown field: \(lhs)")
775 } 784 }
776 fields.append((row, location.column, rhs)) 785 fields.append((row, location.column, rhs, oldLHS))
777 } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil { 786 } else if lhs.range(of: "^@[-+0-9]+\\$-?[0-9]+$", options: .regularExpression) != nil {
778 // `org-table-goto-field` knows only absolute fields and names. 787 // `org-table-goto-field` knows only absolute fields and names.
779 throw UserError(message: "Unknown field: \(lhs)") 788 throw UserError(message: "Unknown field: \(lhs)")
780 } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) { 789 } else if let m = lhs.firstMatch(of: /^@([0-9]+)$/) {
781 let row = try Self.integer(String(m.1)) 790 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)) }
783 } else { 792 } else {
784 let corners = try rangeCorners(lhs, analysis: analysis) 793 let corners = try rangeCorners(lhs, analysis: analysis)
785 guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else { 794 guard let r1 = Self.lineToDline(corners.r1, analysis), let r2 = Self.lineToDline(corners.r2, analysis, above: true), r1 <= r2 else {
786 throw Calc.Unsupported("formula range") 795 throw Calc.Unsupported("formula range")
787 } 796 }
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)) } }
789 } 798 }
790 } 799 }
791 let savedLine = lineStart(point)
792 let savedColumn = tableCurrentColumn()
793 let lineMarker = marker(savedLine)
794 defer { release(lineMarker) }
795
796 let endMarker = marker(end) 800 let endMarker = marker(end)
797 defer { release(endMarker) } 801 defer { release(endMarker) }
798 var beg: Int 802 var beg: Int
@@ -843,11 +847,13 @@ extension EmacsBuffer {
843 point = rowStart 847 point = rowStart
844 return tableCurrentDataLine() 848 return tableCurrentDataLine()
845 } 849 }
846 for (column, rhs) in columnEquations { 850 for (column, rhs, lhs) in columnEquations {
847 point = rowMarker.position 851 point = rowMarker.position
848 tableGotoColumn(column, force: true) 852 tableGotoColumn(column, force: true)
849 if untouchable.contains("@\(dline)$\(column)") { continue } 853 // Org reads the mark at point, which in a field of one space is on the bar
850 try tableEvalFormula(rhs, analysis: analysis) 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) }
851 } 857 }
852 } 858 }
853 point = rowMarker.position 859 point = rowMarker.position
@@ -858,11 +864,19 @@ extension EmacsBuffer {
858 let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1 864 let count = substring(lineStart(point), lineEnd(point)).filter { $0 == "|" }.count - 1
859 if field.column > count { throw UserError(message: "Missing columns in the table. Aborting") } 865 if field.column > count { throw UserError(message: "Missing columns in the table. Aborting") }
860 tableGotoColumn(field.column) 866 tableGotoColumn(field.column)
861 try tableEvalFormula(field.rhs, analysis: analysis) 867 try Self.naming(field.lhs) { try tableEvalFormula(field.rhs, analysis: analysis) }
862 } 868 }
863 tableAlign() 869 tableAlign()
864 point = lineMarker.position 870 }
865 tableGotoColumn(savedColumn) 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 }
866 } 880 }
867 881
868 /// `org-table-get-range` with `corners-only`. 882 /// `org-table-get-range` with `corners-only`.
Sources/Orgstar/ContentView.swift +14 −3
@@ -1049,11 +1049,22 @@ struct ContentView: View {
1049 case .columnView(let view): 1049 case .columnView(let view):
1050 panel = .columns(UUID(), view) 1050 panel = .columns(UUID(), view)
1051 #if APPSTORE 1051 #if APPSTORE
1052 case .emacsTable(_, _, _, let reason, _): 1052 case .emacsTable(_, _, _, let reason, _, let formula, let partial):
1053 commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate")) 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 }
1054 #else 1060 #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):
1056 guard EmacsRunner.executable() != nil else { 1062 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 }
1057 return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate")) 1068 return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1058 } 1069 }
1059 let run = { 1070 let run = {
Sources/OrgstarMobile/MobileEditor.swift +7 −1
@@ -334,6 +334,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
334 case .external(.columnView(let view)) where onColumnView != nil: 334 case .external(.columnView(let view)) where onColumnView != nil:
335 onColumnView?(view) 335 onColumnView?(view)
336 case .external(let request): 336 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)) }
337 onMessage?(Self.unavailable(request, title: command.title)) 340 onMessage?(Self.unavailable(request, title: command.title))
338 } 341 }
339 return step 342 return step
@@ -341,7 +344,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
341 344
342 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs. 345 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
343 static func unavailable(_ request: ExternalRequest, title: String) -> String { 346 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 {
345 return String(localized: "This table needs Emacs, which runs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas only Emacs can calculate") 351 return String(localized: "This table needs Emacs, which runs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas only Emacs can calculate")
346 } 352 }
347 return String(localized: "\(CommandTitle.localized(title)) isn't available on iPhone and iPad.", comment: "A command that runs only on the Mac") 353 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 {
26 "| a |\n|---|\n| 1 |\n| 2 |\n|---|\n| |\n#+TBLFM: @>$1=vmax(@I..@II)-vmin(@I..@II)+vcount(@I..@II)+vmedian(@I..@II)\n", 26 "| a |\n|---|\n| 1 |\n| 2 |\n|---|\n| |\n#+TBLFM: @>$1=vmax(@I..@II)-vmin(@I..@II)+vcount(@I..@II)+vmedian(@I..@II)\n",
27 "#+CONSTANTS: c=10 k=2.5\n| a | b |\n|---+---|\n| 1 | |\n| 2 | |\n#+TBLFM: $2=$1*$c+$k\n", 27 "#+CONSTANTS: c=10 k=2.5\n| a | b |\n|---+---|\n| 1 | |\n| 2 | |\n#+TBLFM: $2=$1*$c+$k\n",
28 "* Rates\n:PROPERTIES:\n:Rate: 3\n:END:\n| h | pay |\n|---+-----|\n| 2 | |\n#+TBLFM: $2=$1*$PROP_Rate\n", 28 "* 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",
29 ] 37 ]
30 38
31 /// Lisp formulas, names, parameters, marked rows, remote tables, durations, dates and 39 /// Lisp formulas, names, parameters, marked rows, remote tables, durations, dates and
@@ -128,7 +136,7 @@ struct TableFormulaTests {
128 : [(TableRecalculate(all: true), "(org-table-recalculate t)"), (TableRecalculate(all: false), "(org-table-recalculate nil)")] 136 : [(TableRecalculate(all: true), "(org-table-recalculate t)"), (TableRecalculate(all: false), "(org-table-recalculate nil)")]
129 for (command, form) in commands { 137 for (command, form) in commands {
130 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: form)) 138 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))
132 } 140 }
133 } 141 }
134 } 142 }
@@ -143,12 +151,6 @@ struct TableFormulaTests {
143 #expect(failure.contains("non-numeric field") || failure.contains("division by zero"), "\(failure)") 151 #expect(failure.contains("non-numeric field") || failure.contains("division by zero"), "\(failure)")
144 continue 152 continue
145 } 153 }
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 }
152 let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error) 154 let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error)
153 #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2, 155 #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2,
154 "\(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 "\(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 {
156 #expect(fallbacks < ours.count / 2, "\(fallbacks) fallbacks") 158 #expect(fallbacks < ours.count / 2, "\(fallbacks) fallbacks")
157 } 159 }
158 160
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
159 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: C-c C-c on every `#+TBLFM` line below the folder. 230 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: C-c C-c on every `#+TBLFM` line below the folder.
160 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil)) 231 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
161 func corpusMatchesEmacs() throws { 232 func corpusMatchesEmacs() throws {
Tests/OrgProgramsTests/ProgramsTests.swift +2 −2
@@ -27,7 +27,7 @@ struct EmacsFallbackTests {
27 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 27 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
28 session.open(file.path) 28 session.open(file.path)
29 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil) 29 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 {
31 Issue.record("\(step)") 31 Issue.record("\(step)")
32 return 32 return
33 } 33 }
@@ -46,7 +46,7 @@ struct EmacsFallbackTests {
46 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 46 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
47 session.open(file.path) 47 session.open(file.path)
48 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil) 48 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 {
50 Issue.record("\(step)") 50 Issue.record("\(step)")
51 return 51 return
52 } 52 }
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=,
568convergence after 10 iterations=, and the ten passes stay. =C-u C-c *= also recalculates 568convergence after 10 iterations=, and the ten passes stay. =C-u C-c *= also recalculates
569the whole table in the Emacs preset. 569the whole table in the Emacs preset.
570 570
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
571A row marked =#= is recalculated when you press =TAB=, =S-TAB= or =RET= in it, before 575A row marked =#= is recalculated when you press =TAB=, =S-TAB= or =RET= in it, before
572the caret moves (=org-table-maybe-recalculate-line=), and with =C-c C-c= (Mac =⌃⌘X=). 576the caret moves (=org-table-maybe-recalculate-line=), and with =C-c C-c= (Mac =⌃⌘X=).
573Other rows are recalculated only by the commands above. Emacs skips a second automatic 577Other 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
606export in Emacs cancels the one that is running. 610export in Emacs cancels the one that is running.
607 611
608The [[file:../install.org][Mac App Store version]] doesn't run Emacs, so it recalculates 612The [[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 613only the tables orgstar computes itself. In any other table it applies the formulas in
610table's formulas can't be calculated here: (reason).=, and the table is unchanged. 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.
611 620
612If the table's formulas contain Lisp, orgstar asks first: 621If the table's formulas contain Lisp, orgstar asks first:
613=This table's formulas run Lisp. Run them? (yes, no, always)=. =always= trusts this 622=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
343- Emacs Lisp the interpreter doesn't have: "This block uses Emacs Lisp that runs only in Emacs, on the Mac." 343- Emacs Lisp the interpreter doesn't have: "This block uses Emacs Lisp that runs only in Emacs, on the Mac."
344- JavaScript that uses something only node has, such as =Buffer=: "This block uses /name/, which runs only in node." 344- JavaScript that uses something only node has, such as =Buffer=: "This block uses /name/, which runs only in node."
345 345
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.
347 347
348Tangling (=C-c C-v t=, in Commands) works on iOS and writes the tangled files next to the org file, or where =:tangle= says. 348Tangling (=C-c C-v t=, in Commands) works on iOS and writes the tangled files next to the org file, or where =:tangle= says.
349 349
docs/manual/install.org +3 −2
@@ -69,8 +69,9 @@ App Store version.
69A block in another language reports "/language/ blocks don't run in this version of 69A block in another language reports "/language/ blocks don't run in this version of
70orgstar." An Emacs Lisp block that uses more than the interpreter has reports "This block uses 70orgstar." An Emacs Lisp block that uses more than the interpreter has reports "This block uses
71Emacs Lisp that runs only in Emacs." A JavaScript block that uses something only node has 71Emacs 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 72reports "This block uses /name/, which runs only in node." A table whose formulas need Emacs is recalculated up to
73formulas can't be calculated here", with the reason, and isn't changed. The Emacs exports are 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
74not in the File ▸ Export menu, the export dialog or the command palette; a key bound to 75not in the File ▸ Export menu, the export dialog or the command palette; a key bound to
75Export to PDF with Emacs exports to PDF without LaTeX. LaTeX export is orgstar's own and is in 76Export to PDF with Emacs exports to PDF without LaTeX. LaTeX export is orgstar's own and is in
76both versions; a file it can't write as Emacs would reports "Can't export to LaTeX", with the 77both 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 @@
30695 } 30695 }
30696 } 30696 }
30697 }, 30697 },
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 },
30698 "The template to capture with.": { 30768 "The template to capture with.": {
30699 "localizations": { 30769 "localizations": {
30700 "de": { 30770 "de": {