Commit 0f261d90b8

0f261d90b827fd8245cc35ec403918b6408f8d40

parent: 0dbf01d3bc

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 23:45 UTC

Refuse Calc constants and sqlite :echo tables, fail sqlite tables where Emacs does

Layout: unified · split

Sources/OrgApp/SQLiteBlocks.swift +4 −1
@@ -17,6 +17,8 @@ public enum SQLiteBlocks {
17 do { 17 do {
18 guard let arguments = command.arguments else { throw Refusal(.shell) } 18 guard let arguments = command.arguments else { throw Refusal(.shell) }
19 var shell = try Shell(arguments: arguments) 19 var shell = try Shell(arguments: arguments)
20 // Echoed statements as a table make Emacs's table conversion fail.
21 if shell.echo, !Babel.resultCondScalar(job.finish.params) { throw Refusal(.echo) }
20 var input = job.input 22 var input = job.input
21 var temporary: URL? 23 var temporary: URL?
22 if !job.dataFiles.isEmpty { 24 if !job.dataFiles.isEmpty {
@@ -39,7 +41,7 @@ public enum SQLiteBlocks {
39 /// Why a block can't run as `sqlite3` would run it. 41 /// Why a block can't run as `sqlite3` would run it.
40 struct Refusal: Error, Equatable { 42 struct Refusal: Error, Equatable {
41 enum Reason: Equatable { 43 enum Reason: Equatable {
42 case shell, dotCommand(String), blob, control, width, explain, newTable, importRows, encoding 44 case shell, dotCommand(String), blob, control, width, explain, newTable, importRows, encoding, echo
43 } 45 }
44 let reason: Reason 46 let reason: Reason
45 /// Statements before the refused one ran. 47 /// Statements before the refused one ran.
@@ -58,6 +60,7 @@ public enum SQLiteBlocks {
58 case .newTable: what = String(localized: ".import into a table that doesn't exist yet", comment: "Why an sqlite block can't run here") 60 case .newTable: what = String(localized: ".import into a table that doesn't exist yet", comment: "Why an sqlite block can't run here")
59 case .importRows: what = String(localized: ".import of rows that don't fit the table", comment: "Why an sqlite block can't run here") 61 case .importRows: what = String(localized: ".import of rows that don't fit the table", comment: "Why an sqlite block can't run here")
60 case .encoding: what = String(localized: "text that isn't UTF-8", comment: "Why an sqlite block can't run here") 62 case .encoding: what = String(localized: "text that isn't UTF-8", comment: "Why an sqlite block can't run here")
63 case .echo: what = String(localized: ":echo with a result that isn't text", comment: "Why an sqlite block can't run here")
61 } 64 }
62 return partly 65 return partly
63 ? String(localized: "This sqlite block can't run here: \(what). The statements before it ran.", comment: "An sqlite block refused partway") 66 ? String(localized: "This sqlite block can't run here: \(what). The statements before it ran.", comment: "An sqlite block refused partway")
Sources/OrgApp/TableReason.swift +1
@@ -112,6 +112,7 @@ public enum TableReason {
112 switch reason { 112 switch reason {
113 case "arguments": return String(localized: "arguments", comment: comment) 113 case "arguments": return String(localized: "arguments", comment: comment)
114 case "calc precision": return String(localized: "calc precision", comment: comment) 114 case "calc precision": return String(localized: "calc precision", comment: comment)
115 case "Calc constants": return String(localized: "Calc constants", comment: comment)
115 case "chained comparison": return String(localized: "chained comparison", comment: comment) 116 case "chained comparison": return String(localized: "chained comparison", comment: comment)
116 case "comparison with nan": return String(localized: "comparison with nan", comment: comment) 117 case "comparison with nan": return String(localized: "comparison with nan", comment: comment)
117 case "complex result": return String(localized: "complex result", comment: comment) 118 case "complex result": return String(localized: "complex result", comment: comment)
Sources/OrgCore/Compute/Babel.swift +7 −1
@@ -76,7 +76,13 @@ public struct BabelJob: Sendable, Equatable {
76 case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool, session: Bool = false), calc 76 case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool, session: Bool = false), calc
77 case sqlite(csv: Bool, headers: Bool) 77 case sqlite(csv: Bool, headers: Bool)
78 78
79 var isSQLite: Bool { if case .sqlite = self { true } else { false } } 79 /// ob-calc and ob-sqlite give a list of rows, never a flat list.
80 var givesRows: Bool {
81 switch self {
82 case .calc, .sqlite: true
83 default: false
84 }
85 }
80 } 86 }
81 let kind: Kind 87 let kind: Kind
82 var language = "" 88 var language = ""
Sources/OrgCore/Compute/BabelCalc.swift +4 −1
@@ -51,7 +51,7 @@ extension Babel {
51 } 51 }
52 52
53 /// `org-babel-result-cond`: whether the value is taken as a string. 53 /// `org-babel-result-cond`: whether the value is taken as a string.
54 static func resultCondScalar(_ params: [String]) -> Bool { 54 public static func resultCondScalar(_ params: [String]) -> Bool {
55 params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code") 55 params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
56 || params.contains("pp") || params.contains("file") 56 || params.contains("pp") || params.contains("file")
57 || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table")) 57 || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
@@ -135,6 +135,9 @@ extension Babel {
135 } else { 135 } else {
136 var parser = Calc.Parser(line) 136 var parser = Calc.Parser(line)
137 let tree = try parser.parse() 137 let tree = try parser.parse()
138 // Calc's default modes give `pi` and `e` their values, which Calc here keeps
139 // as symbols for table formulas.
140 if !tree.variables.isDisjoint(with: Calc.constants) { throw Calc.Unsupported("Calc constants") }
138 // `calc-eval` of the line: a number is pushed as one. 141 // `calc-eval` of the line: a number is pushed as one.
139 let first: Calc.Value? 142 let first: Calc.Value?
140 do { 143 do {
Sources/OrgCore/Compute/BabelResults.swift +8 −3
@@ -23,6 +23,7 @@ extension Babel {
23 } 23 }
24 blockRange = found.location..<NSMaxRange(found) 24 blockRange = found.location..<NSMaxRange(found)
25 } 25 }
26 if let failure = sqliteFailure(job.finish, output) { return .failure(.message(failure)) }
26 let value = Self.value(job.finish, output) 27 let value = Self.value(job.finish, output)
27 if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) } 28 if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
28 let buffer = EmacsBuffer(text, point: 0, settings: settings) 29 let buffer = EmacsBuffer(text, point: 0, settings: settings)
@@ -441,13 +442,17 @@ extension Babel {
441 switch value { 442 switch value {
442 case .none: 443 case .none:
443 break 444 break
445 case .string(let s) where params.contains("list") && finish.kind.givesRows:
446 // `split-string` without empty lines, each an item; `org-trim` of the list.
447 var items = s.components(separatedBy: "\n").filter { !$0.isEmpty }.map { "- " + $0 }.joined(separator: "\n")
448 while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() }
449 if !items.isEmpty { buffer.insert(items + "\n") }
444 case .string(var s) where params.contains("list"): 450 case .string(var s) where params.contains("list"):
445 if s.last != "\n" { s += "\n" } 451 if s.last != "\n" { s += "\n" }
446 let items = s.split(separator: "\n", omittingEmptySubsequences: true) 452 let items = s.split(separator: "\n", omittingEmptySubsequences: true)
447 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n") 453 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
448 case .table(let rows) where params.contains("list") && finish.kind.isSQLite: 454 case .table(let rows) where params.contains("list") && finish.kind.givesRows:
449 // ob-sqlite's value is always rows: each an item, its first cell the text and the 455 // Each row an item, its first cell the text and the others lines under it.
450 // others lines under it.
451 listed = true 456 listed = true
452 var items = rows.map { row in 457 var items = rows.map { row in
453 guard let row else { return "- hline\n" } 458 guard let row else { return "- hline\n" }
Sources/OrgCore/Compute/BabelSQLite.swift +12 −3
@@ -108,7 +108,7 @@ extension Babel {
108 let text = output 108 let text = output
109 if scalar { return .string(text) } 109 if scalar { return .string(text) }
110 if text.isEmpty { return .string("") } 110 if text.isEmpty { return .string("") }
111 var rows: [[String]?] = convertRegion(text, csv: csv) 111 guard var rows: [[String]?] = convertRegion(text, csv: csv) else { return .none }
112 if headers, let first = rows.first { 112 if headers, let first = rows.first {
113 rows = [first, nil] + rows.dropFirst() 113 rows = [first, nil] + rows.dropFirst()
114 } 114 }
@@ -117,6 +117,13 @@ extension Babel {
117 return .table(rows.map { $0?.map(babelRead) }) 117 return .table(rows.map { $0?.map(babelRead) })
118 } 118 }
119 119
120 /// The error Emacs stops with while making a table of the output, if any.
121 static func sqliteFailure(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String? {
122 guard case .sqlite(let csv, _) = finish.kind, !resultCondScalar(finish.params), !finish.params.contains("discard"),
123 !output.stdout.isEmpty, convertRegion(output.stdout, csv: csv) == nil else { return nil }
124 return "Invalid search bound (wrong side of point)"
125 }
126
120 /// `org-babel-read` with Lisp evaluation inhibited: a number as Emacs prints it, a single 127 /// `org-babel-read` with Lisp evaluation inhibited: a number as Emacs prints it, a single
121 /// quoted string read, else the cell. 128 /// quoted string read, else the cell.
122 static func babelRead(_ cell: String) -> String { 129 static func babelRead(_ cell: String) -> String {
@@ -131,8 +138,9 @@ extension Babel {
131 } 138 }
132 139
133 /// `org-table-convert-region` on the whole output, then `org-table-to-lisp` of the aligned 140 /// `org-table-convert-region` on the whole output, then `org-table-to-lisp` of the aligned
134 /// table: rows of cells, padded to the widest row. 141 /// table: rows of cells, padded to the widest row. Nil where Emacs fails: a last empty line
135 static func convertRegion(_ text: String, csv: Bool) -> [[String]?] { 142 /// in a region read without a comma separator puts point past the search bound.
143 static func convertRegion(_ text: String, csv: Bool) -> [[String]?]? {
136 var b = Array(text.unicodeScalars) 144 var b = Array(text.unicodeScalars)
137 let nl: Unicode.Scalar = "\n", tab: Unicode.Scalar = "\t", space: Unicode.Scalar = " ", comma: Unicode.Scalar = ",", quote: Unicode.Scalar = "\"" 145 let nl: Unicode.Scalar = "\n", tab: Unicode.Scalar = "\t", space: Unicode.Scalar = " ", comma: Unicode.Scalar = ",", quote: Unicode.Scalar = "\""
138 var end = b.last == nl ? b.count - 1 : b.count 146 var end = b.last == nl ? b.count - 1 : b.count
@@ -220,6 +228,7 @@ extension Babel {
220 i += 1 228 i += 1
221 } 229 }
222 guard let found = match else { break } 230 guard let found = match else { break }
231 if found.lowerBound == end { return nil }
223 replace(found, ["|", " "]) 232 replace(found, ["|", " "])
224 point = found.lowerBound + 2 233 point = found.lowerBound + 2
225 } 234 }
Tests/OrgAppTests/SQLiteBlocksTests.swift +75 −10
@@ -110,7 +110,7 @@ struct SQLiteBlocksTests {
110 "#+begin_src sqlite :prologue \"create table p(a);\" :epilogue \"select count(*) from p;\"\ninsert into p values (1), (2);\n#+end_src\n", 110 "#+begin_src sqlite :prologue \"create table p(a);\" :epilogue \"select count(*) from p;\"\ninsert into p values (1), (2);\n#+end_src\n",
111 "#+begin_src sqlite\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n", 111 "#+begin_src sqlite\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n",
112 "#+begin_src sqlite :bail\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n", 112 "#+begin_src sqlite :bail\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n",
113 "#+begin_src sqlite :echo\nselect 1;\nselect 2;\n#+end_src\n", 113 "#+begin_src sqlite :echo :results output\nselect 1;\nselect 2;\n#+end_src\n",
114 "#+begin_src sqlite\nselect ' a ', '\"b\"', 'c\"d', '-', '1e3', '+5', '.5', '1.';\n#+end_src\n", 114 "#+begin_src sqlite\nselect ' a ', '\"b\"', 'c\"d', '-', '1e3', '+5', '.5', '1.';\n#+end_src\n",
115 "#+begin_src sqlite :list\nselect 'a b', 'c';\nselect 'single';\n#+end_src\n", 115 "#+begin_src sqlite :list\nselect 'a b', 'c';\nselect 'single';\n#+end_src\n",
116 "#+begin_src sqlite :list\nselect 'a' || char(9) || 'b', 'c';\nselect 'd' || char(9) || 'e';\n#+end_src\n", 116 "#+begin_src sqlite :list\nselect 'a' || char(9) || 'b', 'c';\nselect 'd' || char(9) || 'e';\n#+end_src\n",
@@ -119,35 +119,99 @@ struct SQLiteBlocksTests {
119 "#+begin_src sqlite\nselect 1, '';\nselect '', '';\n#+end_src\n", 119 "#+begin_src sqlite\nselect 1, '';\nselect '', '';\n#+end_src\n",
120 ] 120 ]
121 121
122 /// More blocks: each matches Emacs or is refused.
123 static let probes: [String] = [
124 "#+begin_src sqlite :column\nselect 1 as n, null as z, 'abc' as t union all select 12345, 'x', '';\n#+end_src\n",
125 "#+begin_src sqlite :html\nselect '<b>' as \"a&b\", null;\n#+end_src\n",
126 "#+begin_src sqlite :line\nselect 'a\nb' as x, 2 as longer;\nselect 3 as y;\n#+end_src\n",
127 "#+begin_src sqlite\nselect null, 1;\n#+end_src\n",
128 "#+begin_src sqlite\nselect 9223372036854775807, -9223372036854775808, 1.5e300;\n#+end_src\n",
129 "#+begin_src sqlite\nselect 'a' union all select 'b' union all select 'c';\n#+end_src\n",
130 "#+begin_src sqlite :list :nullvalue N\nselect null, 1;\n#+end_src\n",
131 "#+begin_src sqlite :csv\n.mode column\nselect 1 as a, 22 as bb;\n#+end_src\n",
132 "#+begin_src sqlite\nselect 'a|b', 'c';\n#+end_src\n",
133 "#+begin_src sqlite\n-- only a comment\n#+end_src\n",
134 "#+begin_src sqlite :results scalar\nselect 1, 2;\n#+end_src\n",
135 "#+begin_src sqlite :results table\nselect 'x';\n#+end_src\n",
136 "#+begin_src sqlite :colnames yes :list\nselect 1 as a, 2 as b;\n#+end_src\n",
137 "#+begin_src sqlite :colnames yes\nselect 1 as a;\n#+end_src\n",
138 "#+begin_src sqlite :results list\nselect 1;\n#+end_src\n",
139 "#+begin_src sqlite :results drawer\nselect 1, 2;\n#+end_src\n",
140 "#+begin_src sqlite :wrap example\nselect 1, 2;\n#+end_src\n",
141 "#+begin_src sqlite :separator , \nselect 'a b', 2;\n#+end_src\n",
142 "#+begin_src sqlite :list\nselect ' lead', 'trail ';\n#+end_src\n",
143 "#+begin_src sqlite\nselect ' lead', 'trail ', ' ';\n#+end_src\n",
144 "#+begin_src sqlite\nselect 'tab' || char(9) || 'x', 2;\n#+end_src\n",
145 "#+begin_src sqlite\nselect 'α', '日本', 'x';\n#+end_src\n",
146 "#+begin_src sqlite :column\nselect 'a b' as \"c d\";\n#+end_src\n",
147 "#+begin_src sqlite\nselect 1;\nselect 2, 3;\n#+end_src\n",
148 "#+begin_src sqlite\nselect '\"a\" \"b\"', '\"c\\\"d\"';\n#+end_src\n",
149 "#+begin_src sqlite\nselect '1e5', '0x10', '1,5', '--1';\n#+end_src\n",
150 "#+begin_src sqlite :var n=2\nselect $n + $n1;\n#+end_src\n",
151 "#+NAME: h\n| a | b |\n|---+---|\n| 1 | 2 |\n|---+---|\n| 3 | 4 |\n\n#+begin_src sqlite :var t=h :hlines yes\ncreate table v(a, b);\n.import --csv $t v\nselect * from v;\n#+end_src\n",
152 "#+NAME: s\n| x y | 2.50 |\n| \"q\" | 007 |\n\n#+begin_src sqlite :var t=s\ncreate table v(a, b);\n.import --csv $t v\nselect a, b, typeof(b) from v;\n#+end_src\n",
153 "#+begin_src sqlite :echo :list\nselect 1;\n#+end_src\n",
154 "#+begin_src sqlite :echo :results output\nselect 1;\n#+end_src\n",
155 "#+begin_src sqlite :list\nselect '';\nselect 1;\n#+end_src\n",
156 "#+begin_src sqlite :list\nselect '';\n#+end_src\n",
157 "#+begin_src sqlite :list\nselect 1;\nselect '';\n#+end_src\n",
158 "#+begin_src sqlite :list\nselect '';\nselect 1, 2;\n#+end_src\n",
159 "#+begin_src sqlite :results list\nselect 1, 2;\n#+end_src\n",
160 "#+begin_src sqlite :results list :list\nselect 'a', 'b c';\n#+end_src\n",
161 "#+begin_src sqlite :results output :line\nselect 1 as a;\nselect 2 as b;\n#+end_src\n",
162 "#+begin_src sqlite\ncreate table t(a);\ninsert into t values (1);\nselect changes(), total_changes();\n#+end_src\n",
163 ]
164
165 @MainActor
166 @Test(.enabled(if: oracle))
167 func probesMatchEmacsOrAreRefused() async throws {
168 let (ours, emacs, messages) = try await Self.compare(Self.probes)
169 for (i, text) in Self.probes.enumerated() where !messages[i].hasPrefix("This sqlite block can't run here") {
170 if emacs[i].hasPrefix("ERROR: ") {
171 // Emacs fails the run: the same message, and nothing written.
172 #expect(messages[i] == emacs[i].dropFirst("ERROR: ".count) && ours[i] == text, "\(text)\nours (\(messages[i])):\n\(ours[i])\nemacs:\n\(emacs[i])")
173 continue
174 }
175 #expect(ours[i] == emacs[i], "\(text)\nours (\(messages[i])):\n\(ours[i])\nemacs:\n\(emacs[i])")
176 }
177 }
178
122 /// The results the app inserts, as Emacs inserts them running `sqlite3`. 179 /// The results the app inserts, as Emacs inserts them running `sqlite3`.
123 @MainActor 180 @MainActor
124 @Test(.enabled(if: oracle)) 181 @Test(.enabled(if: oracle))
125 func resultsMatchEmacs() async throws { 182 func resultsMatchEmacs() async throws {
183 let (ours, emacs, _) = try await Self.compare(Self.blocks)
184 for (i, text) in Self.blocks.enumerated() {
185 #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
186 }
187 }
188
189 /// Each block run by the app, and by Emacs, with the app's messages.
190 @MainActor
191 static func compare(_ blocks: [String]) async throws -> (ours: [String], emacs: [String], messages: [String]) {
126 let ourFolder = try Folder(), theirFolder = try Folder() 192 let ourFolder = try Folder(), theirFolder = try Folder()
127 var forms: [String] = [] 193 var forms: [String] = []
128 var ours: [String] = [] 194 var ours: [String] = []
129 for text in Self.blocks { 195 var messages: [String] = []
196 for text in blocks {
130 let caret = (text as NSString).range(of: "#+begin_src").location + 2 197 let caret = (text as NSString).range(of: "#+begin_src").location + 2
131 let file = try ourFolder.write("b.org", text) 198 let file = try ourFolder.write("b.org", text)
132 let session = DocumentSession(recovery: FileRecoveryStore(directory: ourFolder.url.appendingPathComponent(".r"))) 199 let session = DocumentSession(recovery: FileRecoveryStore(directory: ourFolder.url.appendingPathComponent(".r")))
133 session.open(file.path) 200 session.open(file.path)
134 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: caret, expect: nil) else { 201 switch session.perform(ExecuteSrcBlock(), path: file.path, at: caret, expect: nil) {
135 Issue.record("not planned: \(text)") 202 case .external(.babel(let job)): messages.append(await session.runBabel(job))
136 return 203 case let other: messages.append("\(other)")
137 } 204 }
138 _ = await session.runBabel(job)
139 ours.append(session.document?.text ?? "") 205 ours.append(session.document?.text ?? "")
140 let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" 206 let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
141 forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char \(caret + 1)) (condition-case e (org-babel-execute-src-block) (error (insert (format \"ERROR: %S\" e)))) (princ (concat (buffer-string) \"\\f\")))") 207 forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char \(caret + 1)) (princ (condition-case e (progn (org-babel-execute-src-block) (concat (buffer-string) \"\\f\")) (error (format \"ERROR: %s\\f\" (error-message-string e))))))")
142 } 208 }
143 let emacs = try Self.emacs(""" 209 let emacs = try Self.emacs("""
144 (progn (require 'org) (require 'ob-sqlite) 210 (progn (require 'org) (require 'ob-sqlite)
145 (setq org-confirm-babel-evaluate nil org-babel-sqlite3-command "\(Self.sqlite3)" default-directory "\(theirFolder.url.path)/") 211 (setq org-confirm-babel-evaluate nil org-babel-sqlite3-command "\(Self.sqlite3)" default-directory "\(theirFolder.url.path)/")
146 \(forms.joined(separator: "\n"))) 212 \(forms.joined(separator: "\n")))
147 """).split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init) 213 """).split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
148 for (i, text) in Self.blocks.enumerated() { 214 return (ours, emacs, messages)
149 #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
150 }
151 } 215 }
152 216
153 /// Emacs in a UTF-8 locale, as it runs on the Mac. 217 /// Emacs in a UTF-8 locale, as it runs on the Mac.
@@ -188,6 +252,7 @@ struct SQLiteBlocksTests {
188 ("#+begin_src sqlite :column\nselect 'é';\n#+end_src\n", .init(.width)), 252 ("#+begin_src sqlite :column\nselect 'é';\n#+end_src\n", .init(.width)),
189 ("#+begin_src sqlite :column\nselect 'a\nb';\n#+end_src\n", .init(.width)), 253 ("#+begin_src sqlite :column\nselect 'a\nb';\n#+end_src\n", .init(.width)),
190 ("#+begin_src sqlite\nexplain select 1;\n#+end_src\n", .init(.explain)), 254 ("#+begin_src sqlite\nexplain select 1;\n#+end_src\n", .init(.explain)),
255 ("#+begin_src sqlite :echo\nselect 1;\n#+end_src\n", .init(.echo)),
191 ("#+begin_src sqlite\ncreate table t(a);\nselect x'01';\n#+end_src\n", .init(.blob, partly: true)), 256 ("#+begin_src sqlite\ncreate table t(a);\nselect x'01';\n#+end_src\n", .init(.blob, partly: true)),
192 (Self.table + "#+begin_src sqlite :var t=tbl\n.import --csv $t v\n#+end_src\n", .init(.newTable)), 257 (Self.table + "#+begin_src sqlite :var t=tbl\n.import --csv $t v\n#+end_src\n", .init(.newTable)),
193 (Self.table + "#+begin_src sqlite :var t=tbl\ncreate table v(a);\n.import --csv $t v\n#+end_src\n", .init(.importRows, partly: true)), 258 (Self.table + "#+begin_src sqlite :var t=tbl\ncreate table v(a);\n.import --csv $t v\n#+end_src\n", .init(.importRows, partly: true)),
Tests/OrgCoreTests/BabelCalcTests.swift +41
@@ -93,6 +93,47 @@ struct BabelCalcTests {
93 } 93 }
94 } 94 }
95 95
96 /// More blocks: each matches Emacs or is refused.
97 static let probes: [String] = [
98 "2^0.5", "-5 % 3", "1/0", "fact(5)", "round(2.5)", "12345678901234 * 10", "1e-5", "0.1 + 0.2", "2 * pi", "max(3, 5)",
99 "1:2 * 2", "e", "sqrt(-1)", "1e100", "[1, 2] + [3, 4]", "-0.5", "100000000000000", "1.23456789012345", "3 x + y", "x^2",
100 "ln(10)", "exp(1)", "7 \\ 2", "abs(-2.5)", "floor(-2.5)", "1 / 7", "2^-2", "[1, 2, 3] * 2", "\"abc\"", "a b c",
101 ].map { "#+begin_src calc\n\($0)\n#+end_src\n" } + [
102 "#+begin_src calc :var x=-3\nabs(x)\n#+end_src\n",
103 "#+begin_src calc :var x=3\nx^2\n#+end_src\n",
104 "#+begin_src calc :var x=5\nx - x\n#+end_src\n",
105 "#+begin_src calc :var v='(1 2 3)\nv * 2\n#+end_src\n",
106 "#+begin_src calc :var v='(1 2 3)\nv\n'n\n#+end_src\n",
107 "#+begin_src calc :results list\n[1, 2, 3]\n#+end_src\n",
108 "#+begin_src calc :results raw\n1/3\n#+end_src\n",
109 "#+begin_src calc :var x=4 y=x\ny\n#+end_src\n",
110 "#+begin_src calc :results vector\n5\n#+end_src\n",
111 "#+begin_src calc :rownames yes\n[[1, 2], [3, 4]]\n#+end_src\n",
112 "#+NAME: hd2\n| a | b |\n|---+---|\n| 1 | 2 |\n\n#+begin_src calc :var m=hd2\nm * 2\n#+end_src\n",
113 "#+begin_src calc\n1\n\n2\n'+\n3\n'*\n#+end_src\n",
114 "#+begin_src calc\n2.\n3\n'/\n#+end_src\n",
115 "#+begin_src calc :epilogue \"'n\"\n4\n#+end_src\n",
116 ]
117
118 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
119 func probesMatchEmacsOrAreRefused() throws {
120 var cases: [EmacsOracle.Case] = []
121 var ours: [(text: String, failure: String?)?] = []
122 for text in Self.probes {
123 ours.append(try? Self.native(text))
124 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(Self.caret(text), in: text), form: """
125 (progn (require 'ob-calc) (setq org-confirm-babel-evaluate nil)
126 (save-window-excursion (calc) (when (> (calc-stack-size) 0) (calc-pop (calc-stack-size))) (calc-quit))
127 (org-babel-execute-src-block))
128 """))
129 }
130 let emacs = try EmacsOracle.run(cases)
131 for (i, theirs) in emacs.enumerated() {
132 guard let mine = ours[i] else { continue }
133 #expect(mine.text == theirs.text, "\(Self.probes[i])\nours (\(mine.failure ?? "")):\n\(mine.text)\nemacs (\(theirs.error)):\n\(theirs.text)")
134 }
135 }
136
96 /// What Calc here doesn't do as Emacs's does is refused, with the reason. 137 /// What Calc here doesn't do as Emacs's does is refused, with the reason.
97 @Test func refusals() throws { 138 @Test func refusals() throws {
98 let refused: [(String, String)] = [ 139 let refused: [(String, String)] = [
Tests/OrgProgramsTests/ProgramsTests.swift +39
@@ -17,6 +17,45 @@ extension Trait where Self == WithPrograms {
17 static var programs: Self { WithPrograms() } 17 static var programs: Self { WithPrograms() }
18} 18}
19 19
20/// The download version runs sqlite blocks with `sqlite3`, and calc natively with Emacs for
21/// what Calc here refuses.
22@MainActor
23@Suite(.programs)
24struct CalcAndSQLiteProgramsTests {
25 func run(_ text: String, in folder: Folder) async throws -> (message: String, text: String) {
26 let file = try folder.write("b.org", text)
27 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
28 session.open(file.path)
29 let caret = (text as NSString).range(of: "#+begin_src").location + 2
30 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: caret, expect: nil) else {
31 Issue.record("not planned: \(text)")
32 return ("", "")
33 }
34 return (await session.runBabel(job), session.document?.text ?? "")
35 }
36
37 @Test(.enabled(if: FileManager.default.isExecutableFile(atPath: "/usr/bin/sqlite3")))
38 func sqliteRunsSqlite3WithTables() async throws {
39 let table = "#+NAME: t\n| 1 | one |\n| 2 | two |\n\n"
40 let text = table + "#+begin_src sqlite :var t=t :db x.db\ncreate table v(a, b);\n.import --csv $t v\nselect b, a * 2 from v;\n#+end_src\n"
41 let ran = try await run(text, in: try Folder())
42 #expect(ran.message == "Code block evaluation complete.")
43 #expect(ran.text == text + "\n#+RESULTS:\n| one | 2\r |\n| two | 4\r |\n")
44 }
45
46 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
47 func calcFallsBackToEmacs() async throws {
48 let folder = try Folder()
49 let native = try await run("#+begin_src calc\n1/3\n#+end_src\n", in: folder)
50 #expect(native.text == "#+begin_src calc\n1/3\n#+end_src\n\n#+RESULTS:\n: 0.333333333333\n")
51 let emacs = try await run("#+begin_src calc\n2^100\n#+end_src\n", in: folder)
52 #expect(emacs.message == "Code block evaluation complete.")
53 #expect(emacs.text == "#+begin_src calc\n2^100\n#+end_src\n\n#+RESULTS:\n: 1267650600228229401496703205376\n")
54 let failed = try await run("#+begin_src calc\n'+\n#+end_src\n", in: folder)
55 #expect(failed.message == "Too few elements on stack")
56 }
57}
58
20@MainActor 59@MainActor
21@Suite(.programs) 60@Suite(.programs)
22struct EmacsFallbackTests { 61struct EmacsFallbackTests {
docs/manual/guide/11-code-blocks.org +3 −3
@@ -642,7 +642,7 @@ Each run starts with an empty stack. In Emacs the Calculator's stack carries ove
642 642
643=:var= values can be numbers, and lists and tables of integers; a table of one row is a vector. Errors that Emacs reports, such as "Too few elements on stack" or a stack key on a formula ("Invalid data object encountered"), fail the run without writing a result. 643=:var= values can be numbers, and lists and tables of integers; a table of one row is a vector. Errors that Emacs reports, such as "Too few elements on stack" or a stack key on a formula ("Invalid data object encountered"), fail the run without writing a result.
644 644
645What orgstar's Calc doesn't do as Emacs's Calc does is refused rather than given a different result: functions and forms table formulas also refuse, stack keys other than those above, dates, string variables, variables named like Calc's constants (=e=, =pi=, =i=) or with characters other than letters and digits, lists with fractional numbers, and a =:prologue= or =:epilogue= that is a bare number. The message is "This calc block can't be calculated here:" with the reason. The download version then runs the block in =emacs -Q --batch= when Emacs is installed. 645What orgstar's Calc doesn't do as Emacs's Calc does is refused rather than given a different result: functions and forms table formulas also refuse, Calc's constants such as =pi= and =e= (which Emacs replaces by their values), stack keys other than those above, dates, string variables, variables named like Calc's constants (=e=, =pi=, =i=) or with characters other than letters and digits, lists with fractional numbers, and a =:prologue= or =:epilogue= that is a bare number. The message is "This calc block can't be calculated here:" with the reason. The download version then runs the block in =emacs -Q --batch= when Emacs is installed.
646 646
647* sqlite blocks 647* sqlite blocks
648 648
@@ -669,11 +669,11 @@ select item, price * 2 from prices;
669,#+end_src 669,#+end_src
670#+end_src 670#+end_src
671 671
672The output is read as a table the way ob-sqlite reads it, with =org-table-convert-region=; a single value becomes a scalar. In =csv= mode =sqlite3= ends lines with CR LF and Emacs keeps the CR, so the last column of each row ends with a CR, which shows as =^M=; orgstar writes the same. 672The output is read as a table the way ob-sqlite reads it, with =org-table-convert-region=; a single value becomes a scalar. Where that conversion fails in Emacs, as it does for output whose last line is empty in a mode other than =csv=, the run fails with the same message. In =csv= mode =sqlite3= ends lines with CR LF and Emacs keeps the CR, so the last column of each row ends with a CR, which shows as =^M=; orgstar writes the same.
673 673
674In the Mac App Store version, =:db= must be in a folder orgstar has access to: a folder in the sidebar, or one you granted access to. 674In the Mac App Store version, =:db= must be in a folder orgstar has access to: a folder in the sidebar, or one you granted access to.
675 675
676Without =sqlite3=, these dot-commands run: =.headers= (=.header=), =.mode= with =list=, =csv=, =column=, =html= or =line=, =.separator= and =.nullvalue= with one plain argument, and =.import FILE TABLE= (with =--csv= or not) into a table that exists, of rows that fit it. Anything else is refused with "This sqlite block can't run here:" and the reason: other dot-commands, header values with characters the shell would read differently (spaces, quotes, =~=, =;=, =|=), BLOB values, control characters other than tab and newline in values, text other than ASCII or values on several lines in =column= mode and in =line= mode's column names, =EXPLAIN= statements, and text that isn't UTF-8. When the refused value comes after other statements, those statements have already run, and the message says so. 676Without =sqlite3=, these dot-commands run: =.headers= (=.header=), =.mode= with =list=, =csv=, =column=, =html= or =line=, =.separator= and =.nullvalue= with one plain argument, and =.import FILE TABLE= (with =--csv= or not) into a table that exists, of rows that fit it. Anything else is refused with "This sqlite block can't run here:" and the reason: other dot-commands, header values with characters the shell would read differently (spaces, quotes, =~=, =;=, =|=), BLOB values, control characters other than tab and newline in values, text other than ASCII or values on several lines in =column= mode and in =line= mode's column names, =EXPLAIN= statements, text that isn't UTF-8, and =:echo= unless the result is text (=:results output=, for example). When the refused value comes after other statements, those statements have already run, and the message says so.
677 677
678* Graphics 678* Graphics
679 679
l10n/Localizable.xcstrings +70
@@ -1813,6 +1813,41 @@
1813 } 1813 }
1814 } 1814 }
1815 }, 1815 },
1816 ":echo with a result that isn't text": {
1817 "comment": "Why an sqlite block can't run here",
1818 "localizations": {
1819 "de": {
1820 "stringUnit": {
1821 "state": "translated",
1822 "value": ":echo mit einem Ergebnis, das kein Text ist"
1823 }
1824 },
1825 "es": {
1826 "stringUnit": {
1827 "state": "translated",
1828 "value": ":echo con un resultado que no es texto"
1829 }
1830 },
1831 "fr": {
1832 "stringUnit": {
1833 "state": "translated",
1834 "value": ":echo avec un résultat qui n’est pas du texte"
1835 }
1836 },
1837 "ja": {
1838 "stringUnit": {
1839 "state": "translated",
1840 "value": "テキストではない結果での :echo"
1841 }
1842 },
1843 "pt-BR": {
1844 "stringUnit": {
1845 "state": "translated",
1846 "value": ":echo com um resultado que não é texto"
1847 }
1848 }
1849 }
1850 },
1816 "A folder with config.toml and capture.toml, such as a synced copy of ~/.config/orgstar from your Mac. Changes to them apply as they sync.": { 1851 "A folder with config.toml and capture.toml, such as a synced copy of ~/.config/orgstar from your Mac. Changes to them apply as they sync.": {
1817 "localizations": { 1852 "localizations": {
1818 "de": { 1853 "de": {
@@ -4964,6 +4999,41 @@
4964 } 4999 }
4965 } 5000 }
4966 }, 5001 },
5002 "Calc constants": {
5003 "comment": "Why a table needs Emacs",
5004 "localizations": {
5005 "de": {
5006 "stringUnit": {
5007 "state": "translated",
5008 "value": "Calc-Konstanten"
5009 }
5010 },
5011 "es": {
5012 "stringUnit": {
5013 "state": "translated",
5014 "value": "constantes de Calc"
5015 }
5016 },
5017 "fr": {
5018 "stringUnit": {
5019 "state": "translated",
5020 "value": "constantes de Calc"
5021 }
5022 },
5023 "ja": {
5024 "stringUnit": {
5025 "state": "translated",
5026 "value": "Calc の定数"
5027 }
5028 },
5029 "pt-BR": {
5030 "stringUnit": {
5031 "state": "translated",
5032 "value": "constantes do Calc"
5033 }
5034 }
5035 }
5036 },
4967 "Calendar": { 5037 "Calendar": {
4968 "localizations": { 5038 "localizations": {
4969 "de": { 5039 "de": {