Commit fa36a13d84

fa36a13d84a4724675328b2f6ee1bb5e415845aa

parent: 918b9bb6b0

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 21:22 UTC

Keep fields written by a marked row's recalculation on TAB, S-TAB and RET

Errors before any write still move point to the field's start.

Layout: unified · split

Sources/OrgCore/Commands/Table.swift +7 −8
@@ -603,17 +603,16 @@ public struct TableCommand: OrgCommand {
603603 public func applies(in context: EditContext) -> Bool { KeyContext.holds("table", in: context) }
604604
605605 public func run(in context: EditContext) -> CommandStep {
606 let step = tableCommand(context) { buffer in
606 let body = { (buffer: EmacsBuffer) throws in
607607 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 }
608 try perform(buffer)
613609 }
614 // A row marked `#` that recalculates with formulas only Emacs can do.
610 // These recalculate a row marked `#` first, whose written fields stay after an error.
615611 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
612 guard let form = forms[action], EmacsBuffer(context.text, point: context.caret).lookingAtLine("^[ \\t]*\\| *# *(\\||$)") else {
613 return tableCommand(context, body)
614 }
615 return TableRecalculate.recalculating(context, form: form, body)
617616 }
618617
619618 private func perform(_ buffer: EmacsBuffer) throws {
Sources/OrgCore/Compute/TableFormulaCommands.swift +2 −8
@@ -68,17 +68,11 @@ public struct TableRecalculate: OrgCommand {
6868 return request(form: form, reason: unsupported.reason, formula: wrote ? unsupported.formula : nil, partial: wrote ? result : nil, in: context)
6969 }
7070 guard let failure else { return step }
71 guard !result.edits.isEmpty else { return .failed(failure) }
71 // `org-table-save-field` moves point to the field's start even when nothing was written.
72 guard !result.edits.isEmpty || result.selection != [context.caret..<context.caret] else { return .failed(failure) }
7273 return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + [.message(failure)]))
7374 }
7475
75 /// A step that failed with `emacsMessage` as a request to run `form` on the table in
76 /// Emacs, whose text then replaces the table here; other steps unchanged.
77 static func inEmacs(_ step: CommandStep, form: String, in context: EditContext) -> CommandStep {
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
8276 static func request(form: String, reason: String, formula: String?, partial: EditResult?, in context: EditContext) -> CommandStep {
8377 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
8478 let onTblfm = tblfmLine(in: context) != nil
Tests/OrgCoreTests/HeadingCommandTests.swift +11 −5
@@ -131,14 +131,18 @@ struct HeadingOracleTests {
131131func compareWithEmacs(_ inputs: [(text: String, carets: [Int])], _ commands: [(command: any OrgCommand, form: String, headingLineOnly: Bool)], options: EditingOptions = .org) throws {
132132 try #require(EmacsOracle.isAvailable, "Emacs is required for the oracle tests; set ORGSTAR_SKIP_ORACLE to skip")
133133 var cases: [EmacsOracle.Case] = []
134 var ours: [(label: String, text: String, caret: Int, failed: Bool)] = []
134 var ours: [(label: String, text: String, caret: Int, failed: Bool, message: String?)] = []
135135 for (text, carets) in inputs {
136136 for offset in carets {
137137 let onHeadingLine = headingOnLine(at: offset, in: OrgParser.parse(text)) != nil
138138 for (command, form, headingLineOnly) in commands where onHeadingLine || !headingLineOnly {
139139 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(offset, in: text), form: withOptions(options, form)))
140140 let result = runCommand(command, text, caret: offset, options: options)
141 ours.append(("\(command.id) at \(offset) in \(text.debugDescription)", result.text, result.caret, result.failure != nil))
141 // An error after edits that stay, as in Emacs, comes as their last message.
142 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [offset..<offset], calendar: .current, answers: [:], options: options)
143 var message: String?
144 if case .commit(let commit) = command.run(in: context), case .message(let last)? = commit.effects.last { message = last }
145 ours.append(("\(command.id) at \(offset) in \(text.debugDescription)", result.text, result.caret, result.failure != nil, message))
142146 }
143147 }
144148 }
@@ -147,15 +151,17 @@ func compareWithEmacs(_ inputs: [(text: String, carets: [Int])], _ commands: [(c
147151 for (mine, emacs) in zip(ours, theirs) {
148152 let emacsFailed = !emacs.error.isEmpty
149153 let emacsCaret = EmacsOracle.offset(emacs.point, in: emacs.text)
150 let same = mine.failed == emacsFailed && (emacsFailed || (mine.text == emacs.text && mine.caret == emacsCaret))
154 let keptEdits = emacsFailed && !mine.failed && mine.message == emacs.error
155 let same = keptEdits ? mine.text == emacs.text && mine.caret == emacsCaret
156 : mine.failed == emacsFailed && (emacsFailed || (mine.text == emacs.text && mine.caret == emacsCaret))
151157 if !same {
152158 mismatches += 1
153159 if mismatches <= 15 {
154160 let (a, b) = excerpts(mine.text, emacs.text)
155161 Issue.record("""
156162 \(mine.label.prefix(100))
157 ours: \(mine.failed ? "failed" : "\(a.debugDescription) @\(mine.caret)")
158 emacs: \(emacsFailed ? "failed: \(emacs.error)" : "\(b.debugDescription) @\(emacsCaret)")
163 ours: \(mine.failed ? "failed" : "\(a.debugDescription) @\(mine.caret) \(mine.message ?? "")")
164 emacs: \(emacsFailed && !keptEdits ? "failed: \(emacs.error)" : "\(b.debugDescription) @\(emacsCaret) \(emacs.error)")
159165 """)
160166 }
161167 }
Tests/OrgCoreTests/TableFormulaTests.swift +33 −1
@@ -188,6 +188,7 @@ struct TableFormulaTests {
188188 Self.unsupported,
189189 "| 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",
190190 "| a | b |\n|---+---|\n| # | |\n| 2 | |\n#+TBLFM: $2=@0$1+1::@3$2=\(lisp)\n",
191 "| | a | b | c |\n|---+---+---+---|\n| # | 1 | | |\n#+TBLFM: $3=$2*2::$4=\(lisp)\n",
191192 ]
192193 var cases: [EmacsOracle.Case] = []
193194 var ours: [(text: String, caret: Int)] = []
@@ -197,7 +198,8 @@ struct TableFormulaTests {
197198 let onTblfm = (text as NSString).substring(with: (text as NSString).lineRange(for: NSRange(location: caret, length: 0))).contains("#+TBLFM")
198199 let commands: [(any OrgCommand, String)] = onTblfm
199200 ? [(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 : [(TableRecalculate(all: true), "(org-table-recalculate t)"), (TableRecalculate(all: false), "(org-table-recalculate nil)"), (TableIterate(), "(org-table-iterate)"),
202 (TableCommand(.nextField), "(org-table-next-field)"), (TableCommand(.previousField), "(org-table-previous-field)"), (TableCommand(.nextRow), "(org-table-next-row)")]
201203 for (command, form) in commands {
202204 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
203205 let step = command.run(in: context)
@@ -210,6 +212,7 @@ struct TableFormulaTests {
210212 }
211213 }
212214 #expect(cases.count >= 8)
215 #expect(cases.filter { ["(org-table-next-field)", "(org-table-previous-field)", "(org-table-next-row)"].contains($0.form) }.count == 3)
213216 for (i, (theirs, mine)) in zip(try EmacsOracle.run(cases), ours).enumerated() {
214217 #expect(theirs.error.contains("leads outside table"), "\(theirs.error)")
215218 let text = theirs.text.replacingOccurrences(of: failing, with: lisp)
@@ -219,6 +222,35 @@ struct TableFormulaTests {
219222 }
220223 }
221224
225 /// TAB, S-TAB and RET in a row marked `#`, and recalculations with point inside a field,
226 /// when a formula fails: the fields written before it stay and point goes to the field's start.
227 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
228 func errorsKeepFieldsAndMovePointAsEmacs() throws {
229 let marked = "| | a | b | c |\n|---+---+---+---|\n| # | 1 | | |\n#+TBLFM: $3=$2*2::$4=@-9$2\n"
230 let early = "| a | b |\n|---+---|\n| 1 |x|\n| 2 |y |\n#+TBLFM: $2=$1*2::@2$2=7::@3$2=8::@2$1=@-9$1\n"
231 let fine = "| | a | b |\n|---+---+---|\n| # | 1 | |\n| | 2 | |\n#+TBLFM: $3=$2*2\n"
232 func after(_ needle: String, in text: String) -> Int { NSMaxRange((text as NSString).range(of: needle)) }
233 let runs: [(text: String, caret: Int, command: any OrgCommand, form: String)] = [
234 (marked, after("| # | 1", in: marked), TableCommand(.nextField), "(org-table-next-field)"),
235 (marked, after("| # | 1", in: marked), TableCommand(.previousField), "(org-table-previous-field)"),
236 (marked, after("| # | 1", in: marked), TableCommand(.nextRow), "(org-table-next-row)"),
237 (marked, after("| # | 1 | ", in: marked), TableCommand(.nextField), "(org-table-next-field)"),
238 (early, after("| 2", in: early), TableRecalculate(all: true), "(org-table-recalculate t)"),
239 (early, after("| 2 |y", in: early), TableRecalculate(all: true), "(org-table-recalculate t)"),
240 (early, after("| 1 |", in: early), TableRecalculate(all: false), "(org-table-recalculate nil)"),
241 (fine, after("| # | 1", in: fine), TableCommand(.nextField), "(org-table-next-field)"),
242 (fine, after("| # | 1", in: fine), TableCommand(.previousField), "(org-table-previous-field)"),
243 (fine, after("| # | 1", in: fine), TableCommand(.nextRow), "(org-table-next-row)"),
244 ]
245 let cases = runs.map { EmacsOracle.Case(text: $0.text, point: EmacsOracle.point($0.caret, in: $0.text), form: $0.form) }
246 for (i, theirs) in try EmacsOracle.run(cases).enumerated() {
247 let mine = Self.recalculate(runs[i].command, runs[i].text, caret: runs[i].caret)
248 let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error)
249 #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2,
250 "\(runs[i].form) at \(runs[i].caret) in\n\(runs[i].text)\nours:\n\(mine.text)@\(mine.caret) \(mine.failure ?? "")\nemacs:\n\(theirs.text)@\(expected.1) \(theirs.error)")
251 }
252 }
253
222254 /// `runCommand`, with the message of an error that left fields written as the failure.
223255 static func recalculate(_ command: any OrgCommand, _ text: String, caret: Int) -> (text: String, caret: Int, failure: String?) {
224256 let result = runCommand(command, text, caret: caret)
docs/manual/guide/10-tables.org +3 −1
@@ -570,7 +570,9 @@ the whole table in the Emacs preset.
570570
571571A formula that fails, such as one whose reference leads outside the table, stops the
572572command there. As in Emacs, the fields written before it stay, the table isn't aligned,
573and the echo area shows the error.
573the caret goes to the start of its field (on a =#+TBLFM= line it stays put), and the echo
574area shows the error.
575=TAB=, =S-TAB= and =RET= in a row marked =#= stop there too, without moving on.
574576
575577A row marked =#= is recalculated when you press =TAB=, =S-TAB= or =RET= in it, before
576578the caret moves (=org-table-maybe-recalculate-line=), and with =C-c C-c= (Mac =⌃⌘X=).