Run calc and sqlite blocks in-process !433

merged merged by cmc on 2026-11-22 00:16 UTC · krz/orgstar:m13-blocks into main

20 files changed, +2438 −20

Layout: unified · split

Sources/OrgApp/DocumentSession.swift +4
@@ -929,6 +929,10 @@ public final class DocumentSession {
929 #if canImport(JavaScriptCore) 929 #if canImport(JavaScriptCore)
930 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output } 930 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output }
931 #endif 931 #endif
932 if job.calc != nil { return try TableReason.calcBlock(job) }
933 #if canImport(SQLite3)
934 if let output = try SQLiteBlocks.run(job, directory: directory) { return output }
935 #endif
932 guard let output = try Babel.evaluateNatively(job) else { 936 guard let output = try Babel.evaluateNatively(job) else {
933 #if os(macOS) 937 #if os(macOS)
934 throw Babel.Failure.message(job.lispForm == nil 938 throw Babel.Failure.message(job.lispForm == nil
Sources/OrgApp/SQLiteBlocks.swift added +547
@@ -0,0 +1,547 @@
1#if canImport(SQLite3)
2import Foundation
3import OrgCore
4import SQLite3
5
6/// sqlite blocks with the SQLite library, as `sqlite3` (macOS's, 3.54.0) runs them for ob-sqlite,
7/// for builds that can't start it. The command-line options ob-sqlite writes and the dot-commands
8/// `.headers`, `.mode`, `.separator`, `.nullvalue` and `.import` into an existing table are
9/// emulated in the list, csv, column, html and line modes. Anything else, and values whose text
10/// `sqlite3` would escape or lay out by display width, is refused rather than shown differently.
11public enum SQLiteBlocks {
12 /// Runs `job` when it is an sqlite block, in `directory` or its `:dir`; nil for other jobs.
13 public static func run(_ job: BabelJob, directory: URL) throws -> BabelOutput? {
14 guard job.language == "sqlite", let command = job.sqlite else { return nil }
15 let folder = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
16 guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
17 do {
18 guard let arguments = command.arguments else { throw Refusal(.shell) }
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) }
22 var input = job.input
23 var temporary: URL?
24 if !job.dataFiles.isEmpty {
25 let files = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-sqlite-\(UUID().uuidString)")
26 try FileManager.default.createDirectory(at: files, withIntermediateDirectories: true)
27 temporary = files
28 for (token, contents) in job.dataFiles {
29 let file = files.appendingPathComponent("sql-data-\(token.filter(\.isNumber))")
30 try contents.write(to: file, atomically: true, encoding: .utf8)
31 input = input.replacingOccurrences(of: token, with: file.path)
32 }
33 }
34 defer { if let temporary { try? FileManager.default.removeItem(at: temporary) } }
35 return try shell.run(input, folder: folder)
36 } catch let refusal as Refusal {
37 throw Babel.Failure.message(refusal.message)
38 }
39 }
40
41 /// Why a block can't run as `sqlite3` would run it.
42 struct Refusal: Error, Equatable {
43 enum Reason: Equatable {
44 case shell, dotCommand(String), blob, control, width, explain, newTable, importRows, encoding, echo
45 }
46 let reason: Reason
47 /// Statements before the refused one ran.
48 var partly = false
49 init(_ reason: Reason, partly: Bool = false) { (self.reason, self.partly) = (reason, partly) }
50
51 var message: String {
52 let what: String
53 switch reason {
54 case .shell: what = String(localized: "header arguments with shell syntax", comment: "Why an sqlite block can't run here")
55 case .dotCommand(let name): what = String(localized: "the dot-command \(name)", comment: "Why an sqlite block can't run here")
56 case .blob: what = String(localized: "BLOB values", comment: "Why an sqlite block can't run here")
57 case .control: what = String(localized: "control characters in values", comment: "Why an sqlite block can't run here")
58 case .width: what = String(localized: "text other than plain ASCII in column or line mode", comment: "Why an sqlite block can't run here")
59 case .explain: what = String(localized: "EXPLAIN statements", 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")
61 case .importRows: what = String(localized: ".import of rows that don't fit the table", 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")
64 }
65 return partly
66 ? String(localized: "This sqlite block can't run here: \(what). The statements before it ran.", comment: "An sqlite block refused partway")
67 : String(localized: "This sqlite block can't run here: \(what).", comment: "An sqlite block refused before it ran")
68 }
69 }
70
71 /// `sqlite3` reading the input as a script.
72 struct Shell {
73 enum Mode: String { case list, csv, column, html, line }
74 var mode = Mode.list
75 var header = false
76 /// Set by `.headers`, which outlasts a change of mode; the command-line options don't.
77 var headerFlag: Bool?
78 var separator = "|"
79 var rowSeparator = "\n"
80 var nullValue = ""
81 var echo = false
82 var bail = false
83 var readonly = false
84 var database: String?
85
86 init(arguments: [String]) throws {
87 var i = 0
88 while i < arguments.count {
89 let argument = arguments[i]
90 switch argument {
91 case "-header": header = true
92 case "-noheader": header = false
93 case "-separator", "-nullvalue":
94 guard i + 1 < arguments.count else { throw Refusal(.shell) }
95 i += 1
96 if argument == "-separator" { separator = arguments[i] } else { nullValue = arguments[i] }
97 case "-echo": echo = true
98 case "-bail": bail = true
99 case "-readonly": readonly = true
100 case "-csv", "-list", "-column", "-html", "-line": change(to: Mode(rawValue: String(argument.dropFirst()))!)
101 default:
102 guard !argument.hasPrefix("-"), database == nil else { throw Refusal(.shell) }
103 database = argument
104 }
105 i += 1
106 }
107 }
108
109 mutating func change(to new: Mode) {
110 mode = new
111 separator = ["csv": ",", "list": "|", "line": ": "][new.rawValue] ?? ""
112 rowSeparator = new == .csv ? "\r\n" : "\n"
113 nullValue = ""
114 header = headerFlag ?? (new == .column || new == .html)
115 }
116
117 /// What `process_input` reads: dot-commands, lines it only echoes, and SQL.
118 enum Item {
119 case echo(String)
120 case dot(String, [String])
121 case sql(String, line: Int)
122 }
123
124 static func isSpace(_ c: UInt8) -> Bool { c == 32 || (9...13).contains(c) }
125
126 /// `line_is_all_whitespace`: spaces and SQL comments.
127 static func isAllWhitespace(_ line: String) -> Bool {
128 let z = Array(line.utf8)
129 var i = 0
130 while i < z.count {
131 if isSpace(z[i]) { i += 1; continue }
132 if z[i] == UInt8(ascii: "/"), i + 1 < z.count, z[i + 1] == UInt8(ascii: "*") {
133 i += 2
134 while i < z.count, !(z[i] == UInt8(ascii: "*") && i + 1 < z.count && z[i + 1] == UInt8(ascii: "/")) { i += 1 }
135 if i >= z.count { return false }
136 i += 2
137 continue
138 }
139 if z[i] == UInt8(ascii: "-"), i + 1 < z.count, z[i + 1] == UInt8(ascii: "-") {
140 while i < z.count, z[i] != UInt8(ascii: "\n") { i += 1 }
141 if i >= z.count { return true }
142 continue
143 }
144 return false
145 }
146 return true
147 }
148
149 static func items(_ input: String) throws -> [Item] {
150 var lines = input.components(separatedBy: "\n")
151 if lines.last == "" { lines.removeLast() }
152 var items: [Item] = []
153 var sql = ""
154 var start = 0
155 for (n, line) in lines.enumerated() {
156 if sql.isEmpty, isAllWhitespace(line) {
157 items.append(.echo(line))
158 continue
159 }
160 if sql.isEmpty, line.hasPrefix(".") || line.hasPrefix("#") {
161 items.append(line.hasPrefix(".") ? .dot(line, try dotArguments(line)) : .echo(line))
162 continue
163 }
164 if sql.isEmpty {
165 sql = String(decoding: line.utf8.drop(while: isSpace), as: UTF8.self)
166 start = n + 1
167 } else {
168 sql += "\n" + line
169 }
170 if line.contains(";"), sqlite3_complete(sql) != 0 {
171 items.append(.sql(sql, line: start))
172 sql = ""
173 } else if !sql.isEmpty, isAllWhitespace(sql) {
174 items.append(.echo(sql))
175 sql = ""
176 }
177 }
178 if !sql.isEmpty { items.append(.sql(sql, line: start)) }
179 return items
180 }
181
182 /// A dot-command's words, refused unless it is one of those emulated, written plainly.
183 static func dotArguments(_ line: String) throws -> [String] {
184 let words = line.dropFirst().split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)
185 let name = words.first ?? ""
186 let refusal = Refusal(.dotCommand("." + name))
187 guard !line.contains(where: { "\"'\\\r;".contains($0) }) else { throw refusal }
188 switch name {
189 case "header", "headers":
190 guard words.count == 2, ["on", "off", "yes", "no", "1", "0", "true", "false"].contains(words[1]) else { throw refusal }
191 case "mode":
192 guard words.count == 2, Mode(rawValue: words[1]) != nil else { throw refusal }
193 case "separator", "nullvalue":
194 guard words.count == 2 else { throw refusal }
195 case "import":
196 let rest = words.dropFirst().filter { $0 != "--csv" && $0 != "-csv" }
197 guard rest.count == 2, !rest[rest.startIndex].hasPrefix("-"), !rest[rest.startIndex].hasPrefix("|"),
198 !rest[rest.startIndex].hasPrefix("<<"), !rest.last!.hasPrefix("-"), !rest.last!.contains(".") else { throw refusal }
199 default:
200 throw refusal
201 }
202 return words
203 }
204
205 mutating func run(_ input: String, folder: URL) throws -> BabelOutput {
206 let items = try Self.items(input)
207 var out = Data()
208 var err = ""
209 func write(_ s: String) { out.append(contentsOf: Array(s.utf8)) }
210 var db: OpaquePointer?
211 let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
212 let path = database.map { URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path } ?? ":memory:"
213 defer { sqlite3_close(db) }
214 if sqlite3_open_v2(path, &db, flags, nil) != SQLITE_OK {
215 let reason = db.map { String(cString: sqlite3_errmsg($0)) } ?? "out of memory"
216 if Sandbox.isActive || !Self.onMac {
217 throw Babel.Failure.message(String(localized: "Can't open the database \(database ?? ""): \(reason). orgstar can open files only in the folders it has access to.", comment: "An sqlite block's database that can't be opened"))
218 }
219 return BabelOutput(stdout: "", stderr: "Error: unable to open database \"\(database ?? "")\": \(reason)\n", status: 1)
220 }
221 var errors = 0
222 var ran = false
223 for item in items {
224 if errors > 0, bail { break }
225 switch item {
226 case .echo(let line):
227 if echo { write(line + "\n") }
228 case .dot(let line, let words):
229 if echo { write(line + "\n") }
230 do {
231 if try dot(words, db: db!, error: &err) { errors += 1 }
232 } catch var refusal as Refusal {
233 refusal.partly = ran
234 throw refusal
235 }
236 ran = true
237 case .sql(let sql, let line):
238 if echo { write(sql + "\n") }
239 do {
240 if try execute(sql, line: line, db: db!, write: write, error: &err) { errors += 1 }
241 } catch var refusal as Refusal {
242 refusal.partly = refusal.partly || ran
243 throw refusal
244 }
245 ran = true
246 }
247 }
248 return BabelOutput(stdout: String(decoding: out, as: UTF8.self), stderr: err, status: errors > 0 ? 1 : 0)
249 }
250
251 static var onMac: Bool {
252 #if os(macOS)
253 true
254 #else
255 false
256 #endif
257 }
258
259 /// A dot-command; true when it failed.
260 mutating func dot(_ words: [String], db: OpaquePointer, error: inout String) throws -> Bool {
261 switch words[0] {
262 case "header", "headers":
263 headerFlag = ["on", "yes", "1", "true"].contains(words[1])
264 header = headerFlag!
265 case "mode":
266 change(to: Mode(rawValue: words[1])!)
267 case "separator":
268 separator = words[1]
269 case "nullvalue":
270 nullValue = words[1]
271 default:
272 return try importFile(words, db: db, error: &error)
273 }
274 return false
275 }
276
277 /// `.import FILE TABLE` into a table that exists, as CSV.
278 func importFile(_ words: [String], db: OpaquePointer, error: inout String) throws -> Bool {
279 let rest = words.dropFirst().filter { $0 != "--csv" && $0 != "-csv" }
280 let csvOption = words.count != rest.count + 1
281 let (file, table) = (rest[rest.startIndex], rest[rest.startIndex + 1])
282 var columnSeparator = csvOption ? UInt8(ascii: ",") : (separator.utf8.first ?? UInt8(ascii: ","))
283 if columnSeparator >= 0x80 { columnSeparator = UInt8(ascii: ",") }
284 var statement: OpaquePointer?
285 let quoted = "\"" + table.replacingOccurrences(of: "\"", with: "\"\"") + "\""
286 guard sqlite3_prepare_v2(db, "SELECT count(*) FROM pragma_table_info('\(table.replacingOccurrences(of: "'", with: "''"))')", -1, &statement, nil) == SQLITE_OK else {
287 throw Refusal(.newTable)
288 }
289 let columns = sqlite3_step(statement) == SQLITE_ROW ? Int(sqlite3_column_int(statement, 0)) : 0
290 sqlite3_finalize(statement)
291 guard columns > 0 else { throw Refusal(.newTable) }
292 guard let data = FileManager.default.contents(atPath: file) else {
293 error += "Error: cannot open \"\(file)\"\n"
294 return true
295 }
296 let rows = try Self.csvRows(Array(data), separator: columnSeparator)
297 guard rows.allSatisfy({ $0.count == columns }) else { throw Refusal(.importRows) }
298 let insert = "INSERT INTO \(quoted) VALUES(" + Array(repeating: "?", count: columns).joined(separator: ",") + ")"
299 guard sqlite3_prepare_v2(db, insert, -1, &statement, nil) == SQLITE_OK else { throw Refusal(.newTable) }
300 defer { sqlite3_finalize(statement) }
301 let commit = sqlite3_get_autocommit(db) != 0
302 if commit { sqlite3_exec(db, "BEGIN", nil, nil, nil) }
303 var failed = false
304 let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
305 for (n, row) in rows.enumerated() {
306 for (i, field) in row.enumerated() { sqlite3_bind_text(statement, Int32(i + 1), field, -1, transient) }
307 sqlite3_step(statement)
308 if sqlite3_reset(statement) != SQLITE_OK {
309 error += "\(file):\(n + 1): INSERT failed: \(String(cString: sqlite3_errmsg(db)))\n"
310 failed = true
311 if bail { break }
312 }
313 }
314 if commit { sqlite3_exec(db, "COMMIT", nil, nil, nil) }
315 return failed
316 }
317
318 /// `csv_read_one_field` over a file of well-formed CSV: rows of fields.
319 static func csvRows(_ bytes: [UInt8], separator: UInt8) throws -> [[String]] {
320 let quote = UInt8(ascii: "\""), newline = UInt8(ascii: "\n"), cr = UInt8(ascii: "\r")
321 var rows: [[String]] = []
322 var row: [String] = []
323 var i = 0
324 // Any quote must open a field and close it; else the reader's warnings and
325 // recovery would apply.
326 while i < bytes.count {
327 var field: [UInt8] = []
328 if bytes[i] == quote {
329 i += 1
330 while true {
331 guard i < bytes.count else { throw Refusal(.importRows) }
332 if bytes[i] == quote {
333 if i + 1 < bytes.count, bytes[i + 1] == quote {
334 field.append(quote)
335 i += 2
336 continue
337 }
338 i += 1
339 break
340 }
341 field.append(bytes[i])
342 i += 1
343 }
344 guard i == bytes.count || bytes[i] == separator || bytes[i] == newline else { throw Refusal(.importRows) }
345 } else {
346 while i < bytes.count, bytes[i] != separator, bytes[i] != newline {
347 guard bytes[i] != quote else { throw Refusal(.importRows) }
348 field.append(bytes[i])
349 i += 1
350 }
351 if i < bytes.count, bytes[i] == newline, field.last == cr { field.removeLast() }
352 }
353 guard let text = String(bytes: field, encoding: .utf8) else { throw Refusal(.encoding) }
354 row.append(text)
355 if i < bytes.count, bytes[i] == separator {
356 i += 1
357 if i == bytes.count { row.append("") }
358 } else {
359 rows.append(row)
360 row = []
361 if i < bytes.count { i += 1 }
362 }
363 }
364 if !row.isEmpty { rows.append(row) }
365 // The first-row byte-order mark the reader skips.
366 if let first = rows.first?.first, first.hasPrefix("\u{FEFF}") { throw Refusal(.encoding) }
367 return rows
368 }
369
370 /// `shell_exec` of one group of statements; true when one failed.
371 func execute(_ sql: String, line: Int, db: OpaquePointer, write: (String) -> Void, error: inout String) throws -> Bool {
372 var bytes = Array(sql.utf8CString)
373 return try bytes.withUnsafeMutableBufferPointer { buffer -> Bool in
374 var next: UnsafePointer<CChar>? = UnsafePointer(buffer.baseAddress!)
375 while let start = next, start.pointee != 0 {
376 var statement: OpaquePointer?
377 var tail: UnsafePointer<CChar>?
378 if sqlite3_prepare_v2(db, start, -1, &statement, &tail) != SQLITE_OK {
379 error += "Parse error near line \(line): \(String(cString: sqlite3_errmsg(db)))\n"
380 return true
381 }
382 next = tail
383 while let rest = next, rest.pointee != 0, Self.isSpace(UInt8(bitPattern: rest.pointee)) { next = rest + 1 }
384 guard let statement else { continue }
385 defer { sqlite3_finalize(statement) }
386 if sqlite3_stmt_isexplain(statement) != 0 { throw Refusal(.explain) }
387 let failed = try output(statement, db: db, write: write)
388 if failed {
389 error += "Error near line \(line): \(String(cString: sqlite3_errmsg(db)))\n"
390 return true
391 }
392 }
393 return false
394 }
395 }
396
397 /// A value as text, with its type; nil text for NULL.
398 struct Cell {
399 let text: String?
400 let numeric: Bool
401 }
402
403 func cell(_ statement: OpaquePointer, _ i: Int32) throws -> Cell {
404 switch sqlite3_column_type(statement, i) {
405 case SQLITE_NULL: return Cell(text: nil, numeric: false)
406 case SQLITE_BLOB: throw Refusal(.blob)
407 case let type:
408 guard let pointer = sqlite3_column_text(statement, i) else { return Cell(text: nil, numeric: false) }
409 let bytes = UnsafeBufferPointer(start: pointer, count: Int(sqlite3_column_bytes(statement, i)))
410 guard let text = String(bytes: bytes, encoding: .utf8) else { throw Refusal(.encoding) }
411 try Self.check(text)
412 return Cell(text: text, numeric: type == SQLITE_INTEGER || type == SQLITE_FLOAT)
413 }
414 }
415
416 /// Control characters other than tab and newline `sqlite3` escapes.
417 static func check(_ text: String) throws {
418 if text.unicodeScalars.contains(where: { ($0.value < 0x20 && $0 != "\t" && $0 != "\n") || $0.value == 0x7F }) {
419 throw Refusal(.control)
420 }
421 }
422
423 /// Writes the statement's rows in the mode; true when stepping failed.
424 func output(_ statement: OpaquePointer, db: OpaquePointer, write: (String) -> Void) throws -> Bool {
425 let count = sqlite3_column_count(statement)
426 let names = try (0..<count).map { i -> String in
427 let name = sqlite3_column_name(statement, i).map { String(cString: $0) } ?? ""
428 try Self.check(name)
429 return name
430 }
431 var rows: [[Cell]] = []
432 var failed = false
433 var buffered = ""
434 func emit(_ s: String) { if mode == .column { buffered += s } else { write(s) } }
435 while true {
436 let rc = sqlite3_step(statement)
437 if rc == SQLITE_DONE { break }
438 guard rc == SQLITE_ROW else {
439 failed = true
440 break
441 }
442 guard count > 0 else { continue }
443 let row = try (0..<count).map { try cell(statement, $0) }
444 switch mode {
445 case .column:
446 rows.append(row)
447 case .line:
448 let width = try names.map { name -> Int in
449 guard name.allSatisfy({ $0.isASCII }) else { throw Refusal(.width) }
450 return name.utf8.count
451 }.max() ?? 0
452 if !rows.isEmpty { emit("\n") }
453 rows.append([])
454 for (name, value) in zip(names, row) {
455 let pieces = (value.text ?? nullValue).components(separatedBy: "\n")
456 var lines = Array(pieces)
457 // A final newline ends the last line.
458 if lines.count > 1, lines.last == "" { lines.removeLast() }
459 emit(String(repeating: " ", count: width - name.utf8.count) + name + separator + lines[0] + "\n")
460 for more in lines.dropFirst() {
461 emit(String(repeating: " ", count: width + separator.utf8.count) + more + "\n")
462 }
463 }
464 case .html:
465 if rows.isEmpty, header {
466 emit("<TR>\n" + names.map { "<TH>" + Self.html($0) + "\n" }.joined() + "</TR>\n")
467 }
468 rows.append([])
469 emit("<TR>\n" + row.map { "<TD>" + ($0.text.map(Self.html) ?? "null") + "\n" }.joined() + "</TR>\n")
470 case .list, .csv:
471 if rows.isEmpty, header {
472 emit(names.map { mode == .csv ? csv($0) : $0 }.joined(separator: separator) + rowSeparator)
473 }
474 rows.append([])
475 emit(row.map { value in
476 guard let text = value.text else { return nullValue }
477 return mode == .csv && !value.numeric ? csv(text) : text
478 }.joined(separator: separator) + rowSeparator)
479 }
480 }
481 if mode == .column, !rows.isEmpty {
482 try column(names: names, rows: rows, emit: emit)
483 write(buffered)
484 }
485 return failed
486 }
487
488 /// CSV quoting: a field with a control character, space, quote, apostrophe, DEL or byte
489 /// above ASCII, or with the separator, is quoted.
490 func csv(_ text: String) -> String {
491 let special = text.isEmpty || text.utf8.contains { $0 < 0x20 || $0 == 0x20 || $0 == 0x22 || $0 == 0x27 || $0 >= 0x7F }
492 guard special || (!separator.isEmpty && text.contains(separator)) else { return text }
493 return "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\""
494 }
495
496 /// `sqlite3`'s HTML escaping, which writes `>` as `&lt;`.
497 static func html(_ text: String) -> String {
498 var out = ""
499 for c in text.unicodeScalars {
500 switch c {
501 case "<", ">": out += "&lt;"
502 case "&": out += "&amp;"
503 case "\"": out += "&quot;"
504 case "'": out += "&#39;"
505 default: out.unicodeScalars.append(c)
506 }
507 }
508 return out
509 }
510
511 /// Column mode: each column as wide as its widest text, the titles centered over a rule,
512 /// numbers to the right, two spaces between columns, no spaces at the ends of lines.
513 func column(names: [String], rows: [[Cell]], emit: (String) -> Void) throws {
514 func plain(_ s: String) throws -> String {
515 guard s.allSatisfy({ $0.isASCII && $0 != "\t" && $0 != "\n" }) else { throw Refusal(.width) }
516 return s
517 }
518 let texts = try rows.map { try $0.map { try plain($0.text ?? nullValue) } }
519 let titles = try names.map(plain)
520 var widths = Array(repeating: 0, count: names.count)
521 for (i, title) in titles.enumerated() where header { widths[i] = max(widths[i], title.count) }
522 for row in texts { for (i, text) in row.enumerated() { widths[i] = max(widths[i], text.count) } }
523 func line(_ cells: [String], _ align: (Int) -> Character) -> String {
524 var s = ""
525 for (i, text) in cells.enumerated() {
526 let space = widths[i] - text.count
527 switch align(i) {
528 case "c": s += String(repeating: " ", count: space / 2) + text + String(repeating: " ", count: space - space / 2)
529 case "r": s += String(repeating: " ", count: space) + text
530 default: s += text + String(repeating: " ", count: space)
531 }
532 if i < cells.count - 1 { s += " " }
533 }
534 while s.last == " " { s.removeLast() }
535 return s + "\n"
536 }
537 if header {
538 emit(line(titles) { _ in "c" })
539 emit(line(widths.map { String(repeating: "-", count: $0) }) { _ in "l" })
540 }
541 for (row, cells) in zip(texts, rows) {
542 emit(line(row) { cells[$0].numeric ? "r" : "l" })
543 }
544 }
545 }
546}
547#endif
Sources/OrgApp/TableReason.swift +19
@@ -6,6 +6,20 @@ public enum TableReason {
6 /// The reason translated, or as it is when it's one this doesn't know. 6 /// The reason translated, or as it is when it's one this doesn't know.
7 public static func localized(_ reason: String) -> String { translated(reason) ?? reason } 7 public static func localized(_ reason: String) -> String { translated(reason) ?? reason }
8 8
9 /// Why a calc block can't be calculated here, `Calc.Unsupported`'s reason, in the app's language.
10 public static func calcRefusal(_ reason: String) -> String {
11 String(localized: "This calc block can't be calculated here: \(localized(reason)).", comment: "A calc block orgstar can't calculate")
12 }
13
14 /// A calc block's result, or a refusal in the app's language.
15 public static func calcBlock(_ job: BabelJob) throws -> BabelOutput {
16 do {
17 return try Babel.evaluateCalc(job)
18 } catch let refusal as Calc.Unsupported {
19 throw Babel.Failure.message(calcRefusal(refusal.reason))
20 }
21 }
22
9 /// Nil for a reason not known here. 23 /// Nil for a reason not known here.
10 static func translated(_ reason: String) -> String? { 24 static func translated(_ reason: String) -> String? {
11 if reason.hasPrefix("Lisp ") { 25 if reason.hasPrefix("Lisp ") {
@@ -19,6 +33,8 @@ public enum TableReason {
19 if let name = value("variable ") { return String(localized: "variable \(name)", comment: "Why a table needs Emacs: a Calc variable") } 33 if let name = value("variable ") { return String(localized: "variable \(name)", comment: "Why a table needs Emacs: a Calc variable") }
20 if let number = value("number size ") { return String(localized: "number size \(number)", comment: "Why a table needs Emacs: a number too large") } 34 if let number = value("number size ") { return String(localized: "number size \(number)", comment: "Why a table needs Emacs: a number too large") }
21 if let flag = value("format flag ") { return String(localized: "format flag \(flag)", comment: "Why a table needs Emacs: a format specifier flag") } 35 if let flag = value("format flag ") { return String(localized: "format flag \(flag)", comment: "Why a table needs Emacs: a format specifier flag") }
36 if let key = value("stack command ") { return String(localized: "stack command \(key)", comment: "Why a calc block needs Emacs: a key it runs on the stack") }
37 if let name = value("value of :var ") { return String(localized: "value of :var \(name)", comment: "Why a calc block needs Emacs: a variable's value") }
22 return nil 38 return nil
23 } 39 }
24 40
@@ -96,6 +112,7 @@ public enum TableReason {
96 switch reason { 112 switch reason {
97 case "arguments": return String(localized: "arguments", comment: comment) 113 case "arguments": return String(localized: "arguments", comment: comment)
98 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)
99 case "chained comparison": return String(localized: "chained comparison", comment: comment) 116 case "chained comparison": return String(localized: "chained comparison", comment: comment)
100 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)
101 case "complex result": return String(localized: "complex result", comment: comment) 118 case "complex result": return String(localized: "complex result", comment: comment)
@@ -103,6 +120,7 @@ public enum TableReason {
103 case "constants that refer to themselves": return String(localized: "constants that refer to themselves", comment: comment) 120 case "constants that refer to themselves": return String(localized: "constants that refer to themselves", comment: comment)
104 case "date arithmetic": return String(localized: "date arithmetic", comment: comment) 121 case "date arithmetic": return String(localized: "date arithmetic", comment: comment)
105 case "date syntax": return String(localized: "date syntax", comment: comment) 122 case "date syntax": return String(localized: "date syntax", comment: comment)
123 case "dates in calc blocks": return String(localized: "dates in calc blocks", comment: comment)
106 case "daylight saving time": return String(localized: "daylight saving time", comment: comment) 124 case "daylight saving time": return String(localized: "daylight saving time", comment: comment)
107 case "division by zero": return String(localized: "division by zero", comment: comment) 125 case "division by zero": return String(localized: "division by zero", comment: comment)
108 case "duration size": return String(localized: "duration size", comment: comment) 126 case "duration size": return String(localized: "duration size", comment: comment)
@@ -114,6 +132,7 @@ public enum TableReason {
114 case "logarithm domain": return String(localized: "logarithm domain", comment: comment) 132 case "logarithm domain": return String(localized: "logarithm domain", comment: comment)
115 case "number": return String(localized: "number", comment: comment) 133 case "number": return String(localized: "number", comment: comment)
116 case "number size": return String(localized: "number size", comment: comment) 134 case "number size": return String(localized: "number size", comment: comment)
135 case "numeric :prologue or :epilogue": return String(localized: "numeric :prologue or :epilogue", comment: comment)
117 case "range outside row": return String(localized: "range outside row", comment: comment) 136 case "range outside row": return String(localized: "range outside row", comment: comment)
118 case "reference outside table": return String(localized: "reference outside table", comment: comment) 137 case "reference outside table": return String(localized: "reference outside table", comment: comment)
119 case "remote table name from a range": return String(localized: "remote table name from a range", comment: comment) 138 case "remote table name from a range": return String(localized: "remote table name from a range", comment: comment)
Sources/OrgCore/Commands/Table.swift +2 −1
@@ -131,7 +131,8 @@ extension EmacsBuffer {
131 fixed = cookie.1.first 131 fixed = cookie.1.first
132 } else { 132 } else {
133 nonEmpty += 1 133 nonEmpty += 1
134 if numberRegex.firstMatch(in: cell, range: NSRange(location: 0, length: (cell as NSString).length)) != nil { numbers += 1 } 134 // `$` doesn't match before a CR in Emacs.
135 if !cell.unicodeScalars.contains("\r"), numberRegex.firstMatch(in: cell, range: NSRange(location: 0, length: (cell as NSString).length)) != nil { numbers += 1 }
135 } 136 }
136 } 137 }
137 widths.append(maxWidth) 138 widths.append(maxWidth)
Sources/OrgCore/Compute/Babel.swift +41 −2
@@ -53,6 +53,12 @@ public struct BabelJob: Sendable, Equatable {
53 /// A Lisp header value couldn't be evaluated without the file's path: plan again with 53 /// A Lisp header value couldn't be evaluated without the file's path: plan again with
54 /// `Babel.replan` before running. 54 /// `Babel.replan` before running.
55 public internal(set) var needsFile = false 55 public internal(set) var needsFile = false
56 /// A calc block, for `Babel.evaluateCalc`.
57 public internal(set) var calc: Babel.CalcBlock?
58 /// An sqlite block's `sqlite3` command line, for `SQLiteBlocks`.
59 public internal(set) var sqlite: Babel.SQLiteCommand?
60 /// Files the runner writes, each where its key stands in `input`: `:var` tables as CSV.
61 public internal(set) var dataFiles: [String: String] = [:]
56 62
57 public struct Need: Sendable, Equatable { 63 public struct Need: Sendable, Equatable {
58 /// The `:var` value, `name` or `name(args)`. 64 /// The `:var` value, `name` or `name(args)`.
@@ -64,7 +70,20 @@ public struct BabelJob: Sendable, Equatable {
64 /// `compiled`: C, C++, D, Java, Fortran and Clojure, by `language`. 70 /// `compiled`: C, C++, D, Java, Fortran and Clojure, by `language`.
65 /// `script`: ruby and js, whose value comes back as their `inspect` prints it, from 71 /// `script`: ruby and js, whose value comes back as their `inspect` prints it, from
66 /// the result file for ruby and the output for js. 72 /// the result file for ruby and the output for js.
67 enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool, session: Bool = false) } 73 /// `calc`: the value as JSON, `{"value": …}` or `{"rows": […]}`. `sqlite`: the output of
74 /// `sqlite3`, read as CSV when `csv`, with a rule after the first row when `headers`.
75 enum Kind: Sendable, Equatable {
76 case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool, session: Bool = false), calc
77 case sqlite(csv: Bool, headers: Bool)
78
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 }
86 }
68 let kind: Kind 87 let kind: Kind
69 var language = "" 88 var language = ""
70 public internal(set) var params: [String] 89 public internal(set) var params: [String]
@@ -358,7 +377,7 @@ public enum Babel {
358 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled { 377 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled {
359 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run.")) 378 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
360 } 379 }
361 let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp"].contains(language) || generic[language] != nil 380 let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp", "calc", "sqlite"].contains(language) || generic[language] != nil
362 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil 381 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
363 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) { 382 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) {
364 return .failure(.message("\(key) isn't supported yet; nothing was run.")) 383 return .failure(.message("\(key) isn't supported yet; nothing was run."))
@@ -517,6 +536,26 @@ public enum Babel {
517 job.lispForm = form 536 job.lispForm = form
518 return .success(job) 537 return .success(job)
519 } 538 }
539 if language == "calc" {
540 do {
541 return .success(try calcJob(body: body, vars: vars, params: params, finish: finishBase(.calc), directory: dir, block: location,
542 blockText: blockText, alwaysAsk: alwaysAsk))
543 } catch let error as Failure {
544 return .failure(error)
545 } catch {
546 return .failure(.message("\(error)"))
547 }
548 }
549 if language == "sqlite" {
550 do {
551 return .success(try sqliteJob(body: body, vars: vars, params: params, finishBase: finishBase, directory: dir, block: location,
552 blockText: blockText, alwaysAsk: alwaysAsk))
553 } catch let error as Failure {
554 return .failure(error)
555 } catch {
556 return .failure(.message("\(error)"))
557 }
558 }
520 if ["dot", "plantuml", "mermaid"].contains(language) { 559 if ["dot", "plantuml", "mermaid"].contains(language) {
521 // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`. 560 // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`.
522 guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) } 561 guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) }
Sources/OrgCore/Compute/BabelCache.swift +20
@@ -9,6 +9,10 @@ extension Babel {
9 static func cacheState(language: String, params: Params, tables: Tables, body: String, location: Range<Int>, name: String?, 9 static func cacheState(language: String, params: Params, tables: Tables, body: String, location: Range<Int>, name: String?,
10 call: Bool, text: NSString, options: Options, model: DocumentModel) throws -> (hash: String, current: Bool, value: VarValue?) { 10 call: Bool, text: NSString, options: Options, model: DocumentModel) throws -> (hash: String, current: Bool, value: VarValue?) {
11 let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound } 11 let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound }
12 // ob-sqlite writes a table to a new temporary file each run, so Emacs's hash never matches.
13 if language == "sqlite", tables.vars.contains(where: { if case .table = $0.1 { true } else { false } }) {
14 throw Failure.message(":cache with a table :var isn't supported for sqlite blocks; nothing was run.")
15 }
12 // The hash is taken outside the shell's own binding of `shell-file-name`, so its 16 // The hash is taken outside the shell's own binding of `shell-file-name`, so its
13 // variables are written for the user's shell whatever the block's language. 17 // variables are written for the user's shell whatever the block's language.
14 let expanded = try languageExpansion(body, language: language, tables: tables, params: params, 18 let expanded = try languageExpansion(body, language: language, tables: tables, params: params,
@@ -34,6 +38,22 @@ extension Babel {
34 if language == "python" { 38 if language == "python" {
35 return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n") 39 return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n")
36 } 40 }
41 if language == "calc" {
42 // `org-babel-expand-body:calc`.
43 return (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
44 }
45 if language == "sqlite" {
46 // `org-babel-expand-body:sqlite`, with no tables.
47 var expanded = body
48 for (name, value) in vars {
49 switch value {
50 case .scalar(let s): expanded = replacingCaseInsensitively("$" + name, in: expanded, with: s)
51 case .number(let n): expanded = replacingCaseInsensitively("$" + name, in: expanded, with: n)
52 default: break
53 }
54 }
55 return [params.single[":prologue"] ?? "", expanded, params.single[":epilogue"] ?? ""].joined(separator: "\n")
56 }
37 if language == "emacs-lisp" || language == "elisp" { 57 if language == "emacs-lisp" || language == "elisp" {
38 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" } 58 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
39 return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)" 59 return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)"
Sources/OrgCore/Compute/BabelCalc.swift added +257
@@ -0,0 +1,257 @@
1import Foundation
2
3// ob-calc (Org 9.8.7) on `Calc`: each line of the body goes onto a fresh Calc stack, as in a
4// new Emacs, and the value is the top of the stack. Calc's own modes apply, not
5// `org-calc-default-modes`: 12 digits shown in full.
6
7extension Babel {
8 /// A calc block: its lines, trimmed, and its variables as Calc values.
9 public struct CalcBlock: Sendable, Equatable {
10 let lines: [String]
11 let vars: [Variable]
12 /// `org-babel-result-cond` takes the value as a string.
13 let scalar: Bool
14 /// Why the block can't run here, found when it was planned.
15 let refusal: Calc.Unsupported?
16
17 struct Variable: Sendable, Equatable {
18 let name: String
19 let value: Calc.Value
20 }
21 }
22
23 /// `org-babel-execute:calc` with `emacs -Q` modes.
24 static let calcModes: Calc.Modes = {
25 var modes = Calc.Modes()
26 modes.format = .float(0)
27 return modes
28 }()
29
30 /// Plans a calc block: natively through `job.calc`, and in Emacs through `job.input`.
31 static func calcJob(body: String, vars: [(String, VarValue)], params: Params, finish: BabelJob.Finish, directory: String?,
32 block: Range<Int>, blockText: String, alwaysAsk: Bool) throws -> BabelJob {
33 let prologue = params.single[":prologue"], epilogue = params.single[":epilogue"]
34 let expanded = (prologue.map { $0 + "\n" } ?? "") + body + (epilogue.map { "\n" + $0 + "\n" } ?? "")
35 var job = BabelJob(language: "calc", runner: .emacs, input: calcScript(body: body, vars: vars, params: params, finish: finish),
36 directory: directory, block: block, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
37 let lines = expanded.components(separatedBy: CharacterSet(charactersIn: "\n\r")).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
38 var values: [CalcBlock.Variable] = []
39 var refusal: Calc.Unsupported?
40 do {
41 // `org-babel-read` makes a number of an unquoted `:prologue 2`, which `concat` refuses.
42 if [":prologue", ":epilogue"].contains(where: { key in params.single[key].map { !params.quoted.contains(key) && number($0) != nil } ?? false }) {
43 throw Calc.Unsupported("numeric :prologue or :epilogue")
44 }
45 values = try vars.map { try CalcBlock.Variable(name: $0.0, value: calcValue($0.1, name: $0.0)) }
46 } catch let error as Calc.Unsupported {
47 refusal = error
48 }
49 job.calc = CalcBlock(lines: lines, vars: values, scalar: resultCondScalar(finish.params), refusal: refusal)
50 return job
51 }
52
53 /// `org-babel-result-cond`: whether the value is taken as a string.
54 public static func resultCondScalar(_ params: [String]) -> Bool {
55 params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
56 || params.contains("pp") || params.contains("file")
57 || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
58 }
59
60 /// A `:var` value as ob-calc pushes it: a number read by Calc, a list as a vector, a table as
61 /// a matrix (one row as a vector). Strings, Lisp floats inside lists, and names Calc reads as
62 /// something else are refused.
63 static func calcValue(_ value: VarValue, name: String) throws -> Calc.Value {
64 let refusal = Calc.Unsupported("value of :var \(name)")
65 guard name.range(of: "^[A-Za-z][A-Za-z0-9]*$", options: .regularExpression) != nil, !Calc.constants.contains(name), !Calc.reserved.contains(name) else { throw refusal }
66 func integer(_ cell: Cell) throws -> Calc.Value {
67 guard case .number(let n) = cell, let i = Int(n) else { throw refusal }
68 return .int(i)
69 }
70 switch value {
71 case .number(let n):
72 return try Calc.withModes(calcModes) {
73 var parser = Calc.Parser(n.replacingOccurrences(of: "e+", with: "e"))
74 return try Calc.Evaluator(modes: calcModes).eval(try parser.parse())
75 }
76 case .list(let items) where items.count > 1:
77 return .vector(try items.map(integer))
78 case .table(let rows) where !rows.isEmpty && !rows.contains(where: { $0 == nil || $0!.isEmpty }):
79 let matrix = try rows.map { try $0!.map(integer) }
80 return matrix.count == 1 ? .vector(matrix[0]) : .vector(matrix.map { .vector($0) })
81 default:
82 throw refusal
83 }
84 }
85
86 /// Runs `job.calc` as ob-calc does: the output `calcScript` prints. Throws `Calc.Unsupported`
87 /// for what Calc here doesn't do as Emacs's does, and `Failure` for Emacs's errors.
88 public static func evaluateCalc(_ job: BabelJob) throws -> BabelOutput {
89 guard let block = job.calc else { throw Failure.message("Not a calc block.") }
90 if let refusal = block.refusal { throw refusal }
91 do {
92 return try calc(block)
93 } catch let error as Calc.Failure {
94 // `math-read-number` of the error `calc-eval` returns.
95 throw Failure.message("Wrong type argument: stringp, (\(error.position) \"\(error.reason)\")")
96 }
97 }
98
99 static func calc(_ block: CalcBlock) throws -> BabelOutput {
100 try Calc.withModes(calcModes) {
101 let evaluator = Calc.Evaluator(modes: calcModes)
102 let names = Set(block.vars.map(\.name))
103 var stored: [String: Calc.Value] = [:]
104 for variable in block.vars { stored[variable.name] = variable.value }
105 /// Stack entries: a number, or the string ob-calc pushes for any other value.
106 /// `known` is false when Calc here couldn't tell whether ob-calc pushed a number.
107 enum Entry { case number(Calc.Value), text(String, known: Bool) }
108 var stack: [Entry] = []
109 func pop() throws -> Calc.Value {
110 guard let top = stack.popLast() else { throw Failure.message("Too few elements on stack") }
111 switch top {
112 case .number(let v): return v
113 case .text(_, true): throw Failure.message("Invalid data object encountered")
114 case .text(_, false): throw Calc.Unsupported("symbolic arithmetic")
115 }
116 }
117 for line in block.lines where !line.isEmpty {
118 if names.contains(line) {
119 stack.append(.number(stored[line]!))
120 } else if line.hasPrefix("'") {
121 let key = String(line.dropFirst())
122 let node: Calc.Node
123 switch key {
124 case "+", "-", "*", "/", "^", "%", "\\":
125 guard stack.count >= 2 else { throw Failure.message("Too few elements on stack") }
126 let b = try pop(), a = try pop()
127 node = .binary(Character(key), .number(a), .number(b))
128 case "n": node = .unary("-", .number(try pop()))
129 case "&": node = .binary("/", .number(.int(1)), .number(try pop()))
130 case "Q": node = .call("sqrt", [.number(try pop())])
131 case "A": node = .call("abs", [.number(try pop())])
132 default: throw Calc.Unsupported("stack command '\(key)")
133 }
134 stack.append(.number(try checked(try evaluator.eval(node))))
135 } else {
136 var parser = Calc.Parser(line)
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") }
141 // `calc-eval` of the line: a number is pushed as one.
142 let first: Calc.Value?
143 do {
144 first = try checked(try evaluator.eval(tree))
145 } catch is Calc.Unsupported where !tree.variables.isDisjoint(with: names) {
146 // Calc here can't keep this formula of the block's variables, which
147 // Emacs's Calc keeps as a formula unless it simplifies to a number.
148 first = nil
149 }
150 if let first, isNumber(first) {
151 stack.append(.number(first))
152 } else {
153 // The formula again with the block's variables put in, as text.
154 let resolved = try checked(try evaluator.eval(tree.substituting(stored)))
155 let text = try Calc.format(resolved, calcModes.format).replacingOccurrences(of: "'", with: "")
156 stack.append(.text(text, known: first != nil))
157 }
158 }
159 }
160 guard let top = stack.last else { throw Failure.message("Too few elements on stack") }
161 let result: Calc.Value
162 switch top {
163 case .number(let v): result = v
164 case .text(let s, _):
165 var parser = Calc.Parser(s)
166 result = try checked(try evaluator.eval(try parser.parse()))
167 }
168 let object: [String: Any]
169 if case .vector(let items) = result, !block.scalar {
170 let rows: [[Calc.Value]]
171 if case .vector(let first)? = items.first, !first.isEmpty,
172 items.allSatisfy({ if case .vector(let row) = $0 { row.count == first.count } else { false } }) {
173 rows = items.map { if case .vector(let row) = $0 { row } else { [] } }
174 } else {
175 rows = [items]
176 }
177 guard !rows.contains(where: \.isEmpty) else { throw Calc.Unsupported("empty vector") }
178 object = ["rows": try rows.map { try $0.map { try Calc.format($0, calcModes.format) } }]
179 } else {
180 object = ["value": try Calc.format(result, calcModes.format)]
181 }
182 let data = try JSONSerialization.data(withJSONObject: object)
183 return BabelOutput(stdout: String(decoding: data, as: UTF8.self))
184 }
185 }
186
187 static func isNumber(_ value: Calc.Value) -> Bool {
188 switch value {
189 case .int, .float, .frac: true
190 default: false
191 }
192 }
193
194 /// Dates show in Calc's own format, not Org's.
195 static func checked(_ value: Calc.Value) throws -> Calc.Value {
196 func hasDate(_ v: Calc.Value) -> Bool {
197 switch v {
198 case .date: true
199 case .vector(let items): items.contains(where: hasDate)
200 default: false
201 }
202 }
203 if hasDate(value) { throw Calc.Unsupported("dates in calc blocks") }
204 return value
205 }
206
207 /// Emacs running `org-babel-execute:calc` on the block, printing the value as JSON.
208 static func calcScript(body: String, vars: [(String, VarValue)], params: Params, finish: BabelJob.Finish) -> String {
209 var entries = vars.map { "(:var . (\($0.0) . \(lispLiteral($0.1))))" }
210 for key in [":prologue", ":epilogue"] {
211 if let value = params.single[key] {
212 entries.append("(\(key) . \(!params.quoted.contains(key) && number(value) != nil ? value : lispString(value)))")
213 }
214 }
215 entries.append("(:result-params . (" + finish.params.map { lispString($0) }.joined(separator: " ") + "))")
216 return """
217 ;;; -*- lexical-binding: t -*-
218 (require 'ob-calc)
219 (require 'json)
220 (condition-case err
221 (let* ((inhibit-message t)
222 (result (org-babel-execute:calc \(lispString(body)) '(\(entries.joined(separator: " "))))))
223 (princ (json-encode
224 (if (listp result)
225 `((rows . ,(vconcat (mapcar (lambda (row) (vconcat (mapcar (lambda (c) (format "%s" c)) row))) result))))
226 `((value . ,(format "%s" result)))))))
227 (error (let ((inhibit-message nil)) (message "%s" (error-message-string err)))
228 (kill-emacs 1)))
229 """
230 }
231}
232
233extension Calc {
234 /// `body` with `modes`' precision, fractions and symbolic mode.
235 static func withModes<T>(_ modes: Modes, _ body: () throws -> T) throws -> T {
236 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
237 return try $precision.withValue(modes.precision) {
238 try $fractions.withValue(modes.preferFractions) {
239 try $symbolicMode.withValue(modes.symbolic, operation: body)
240 }
241 }
242 }
243}
244
245extension Calc.Node {
246 /// `org-babel-calc-maybe-resolve-var`: the variables in `values` replaced by their values.
247 func substituting(_ values: [String: Calc.Value]) -> Calc.Node {
248 switch self {
249 case .number: self
250 case .variable(let name): values[name].map(Calc.Node.number) ?? self
251 case .vector(let items): .vector(items.map { $0.substituting(values) })
252 case .unary(let op, let a): .unary(op, a.substituting(values))
253 case .binary(let op, let a, let b): .binary(op, a.substituting(values), b.substituting(values))
254 case .call(let name, let args): .call(name, args.map { $0.substituting(values) })
255 }
256 }
257}
Sources/OrgCore/Compute/BabelResults.swift +40 −6
@@ -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)
@@ -42,7 +43,15 @@ extension Babel {
42 43
43 /// The language's result handling: `org-babel-result-cond` and the table import. 44 /// The language's result handling: `org-babel-result-cond` and the table import.
44 static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { 45 static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
45 reassemble(rawValue(finish, output), finish) 46 let value = reassemble(rawValue(finish, output), finish)
47 switch (finish.kind, value) {
48 case (.calc, .string(let s)), (.sqlite, .string(let s)):
49 // `org-babel-execute-src-block` makes a table of a value that isn't a list.
50 if !finish.params.contains("output"), finish.params.contains("vector") || finish.params.contains("table") { return .table([[s]]) }
51 return value
52 default:
53 return value
54 }
46 } 55 }
47 56
48 static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { 57 static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
@@ -54,10 +63,16 @@ extension Babel {
54 if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" } 63 if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
55 return .string(link + "]") 64 return .string(link + "]")
56 } 65 }
57 let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code") 66 let scalar = resultCondScalar(params)
58 || params.contains("pp") || params.contains("file")
59 || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
60 switch finish.kind { 67 switch finish.kind {
68 case .calc:
69 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
70 return .string(output.stdout)
71 }
72 if let rows = object["rows"] as? [[String]] { return .table(rows) }
73 return .string(object["value"] as? String ?? "")
74 case .sqlite(let csv, let headers):
75 return sqliteValue(output.stdout, csv: csv, headers: headers, scalar: scalar)
61 case .shell(let valueIsExitStatus): 76 case .shell(let valueIsExitStatus):
62 var results = output.stdout 77 var results = output.stdout
63 if valueIsExitStatus { 78 if valueIsExitStatus {
@@ -103,6 +118,10 @@ extension Babel {
103 case .shell(let valueIsExitStatus): 118 case .shell(let valueIsExitStatus):
104 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout 119 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
105 case .generic: return output.stdout 120 case .generic: return output.stdout
121 case .calc:
122 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
123 return object["value"] as? String ?? ""
124 case .sqlite: return output.stdout
106 case .compiled: return compiledResult(finish, output) 125 case .compiled: return compiledResult(finish, output)
107 case .script(let js, let session): return finish.output || (js && !session) ? output.stdout : (output.resultFile ?? "") 126 case .script(let js, let session): return finish.output || (js && !session) ? output.stdout : (output.resultFile ?? "")
108 } 127 }
@@ -423,10 +442,24 @@ extension Babel {
423 switch value { 442 switch value {
424 case .none: 443 case .none:
425 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") }
426 case .string(var s) where params.contains("list"): 450 case .string(var s) where params.contains("list"):
427 if s.last != "\n" { s += "\n" } 451 if s.last != "\n" { s += "\n" }
428 let items = s.split(separator: "\n", omittingEmptySubsequences: true) 452 let items = s.split(separator: "\n", omittingEmptySubsequences: true)
429 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n") 453 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
454 case .table(let rows) where params.contains("list") && finish.kind.givesRows:
455 // Each row an item, its first cell the text and the others lines under it.
456 listed = true
457 var items = rows.map { row in
458 guard let row else { return "- hline\n" }
459 return "- " + (row.first ?? "") + "\n" + row.dropFirst().map { " " + $0 + "\n" }.joined()
460 }.joined()
461 while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() }
462 buffer.insert(items + "\n")
430 case .table(let rows) where params.contains("list"): 463 case .table(let rows) where params.contains("list"):
431 listed = true 464 listed = true
432 let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") } 465 let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
@@ -440,7 +473,8 @@ extension Babel {
440 buffer.tableAlign() 473 buffer.tableAlign()
441 buffer.point = buffer.tableEnd() 474 buffer.point = buffer.tableEnd()
442 case .string(var s): 475 case .string(var s):
443 if !s.isEmpty, s.last != "\n" { s += "\n" } 476 // `org-string-nw-p`: a blank result gets no newline.
477 if s.unicodeScalars.contains(where: { !" \r\t\n".unicodeScalars.contains($0) }), s.unicodeScalars.last != "\n" { s += "\n" }
444 buffer.insert(s) 478 buffer.insert(s)
445 } 479 }
446 let end = buffer.marker(buffer.point, advances: true) 480 let end = buffer.marker(buffer.point, advances: true)
@@ -500,7 +534,7 @@ extension Babel {
500 /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block. 534 /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
501 static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) { 535 static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
502 let text = buffer.substring(beg, end) 536 let text = buffer.substring(beg, end)
503 var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0) 537 var size = text.components(separatedBy: "\n").count - (text.utf16.last == 10 ? 1 : 0)
504 if text.isEmpty { size = 0 } 538 if text.isEmpty { size = 0 }
505 guard size > 0 else { return } 539 guard size > 0 else { return }
506 if size < 10 { 540 if size < 10 {
Sources/OrgCore/Compute/BabelSQLite.swift added +259
@@ -0,0 +1,259 @@
1import Foundation
2
3// ob-sqlite (Org 9.8.7): the body goes to `sqlite3` on standard input, with the options the
4// header arguments name, and the output becomes the result through `org-table-convert-region`.
5
6extension Babel {
7 /// An sqlite block's `sqlite3` command line.
8 public struct SQLiteCommand: Sendable, Equatable {
9 /// The command for the shell, as ob-sqlite writes it.
10 public let command: String
11 /// The command's words after `sqlite3` when they hold nothing the shell would change;
12 /// nil otherwise.
13 public let arguments: [String]?
14 }
15
16 /// Stands, in a job's input, for a data file the runner writes (`BabelJob.dataFiles`).
17 public static func dataFileToken(_ n: Int) -> String { "__ORGSTAR_DATA_FILE_\(n)__" }
18
19 static func sqliteJob(body: String, vars: [(String, VarValue)], params: Params, finishBase: (BabelJob.Finish.Kind) -> BabelJob.Finish,
20 directory: String?, block: Range<Int>, blockText: String, alwaysAsk: Bool) throws -> BabelJob {
21 let separator = params.single[":separator"], nullvalue = params.single[":nullvalue"], db = params.single[":db"]
22 let headers = params.single[":colnames"] == "yes"
23 let others = [":header", ":echo", ":bail", ":column", ":csv", ":html", ":line", ":list"].filter { params.single[$0] != nil }
24 let formatted = others.contains { [":csv", ":column", ":line", ":list", ":html"].contains($0) } || separator != nil
25 let fields: [(String, String)] = [
26 ("cmd", "sqlite3"),
27 ("header", headers ? "-header" : "-noheader"),
28 ("separator", separator.map { "-separator \($0)" } ?? ""),
29 ("nullvalue", nullvalue.map { "-nullvalue \($0)" } ?? ""),
30 ("others", others.map { "-" + $0.dropFirst() }.joined(separator: " ")),
31 ("csv", formatted ? "" : "-csv"),
32 ("readonly", params.single[":readonly"] == "yes" ? "-readonly" : ""),
33 ("db", db ?? ""),
34 ]
35 // `org-fill-template`.
36 var command = "%cmd %header %separator %nullvalue %others %csv %readonly %db "
37 for (key, value) in fields { command = command.replacingOccurrences(of: "%" + key, with: value) }
38 let words = command.split(separator: " ").dropFirst().map(String.init)
39 let plain = words.allSatisfy { $0.range(of: "^[A-Za-z0-9._/:@%+=,-]+$", options: .regularExpression) != nil }
40 && !(db?.hasPrefix("-") ?? false) && words.count == command.split(separator: " ").count - 1
41
42 // `org-babel-sql-expand-vars`: `$name` replaced, a table by a CSV file of it.
43 var expanded = body
44 var files: [String: String] = [:]
45 for (name, value) in vars {
46 guard name.range(of: "^[A-Za-z0-9_-]+$", options: .regularExpression) != nil else {
47 throw Failure.message(":var \(name) isn't supported for sqlite blocks; nothing was run.")
48 }
49 let replacement: String
50 switch value {
51 case .scalar(let s): replacement = s
52 case .number(let n): replacement = n
53 case .table(let rows):
54 let token = dataFileToken(files.count)
55 files[token] = try csvFile(rows, name: name)
56 replacement = token
57 case .list:
58 throw Failure.message(":var \(name) is a list, which sqlite blocks can't take; nothing was run.")
59 }
60 expanded = replacingCaseInsensitively("$" + name, in: expanded, with: replacement)
61 }
62 let input = [params.single[":prologue"] ?? "", expanded, params.single[":epilogue"] ?? ""].joined(separator: "\n") + "\n"
63 var finish = finishBase(.sqlite(csv: !formatted, headers: headers))
64 // ob-sqlite doesn't put back the names `:var` tables gave up.
65 (finish.colnames, finish.rownames) = (nil, nil)
66 var job = BabelJob(language: "sqlite", runner: .process(executable: command, arguments: []), input: input, directory: directory,
67 block: block, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
68 job.sqlite = SQLiteCommand(command: command, arguments: plain ? words : nil)
69 job.dataFiles = files
70 return job
71 }
72
73 /// `replace-regexp-in-string` of a literal with `case-fold-search`.
74 static func replacingCaseInsensitively(_ target: String, in text: String, with replacement: String) -> String {
75 let ns = text as NSString
76 var result = ""
77 var location = 0
78 while location <= ns.length {
79 let found = ns.range(of: target, options: [.caseInsensitive, .literal], range: NSRange(location: location, length: ns.length - location))
80 guard found.location != NSNotFound else { break }
81 result += ns.substring(with: NSRange(location: location, length: found.location - location)) + replacement
82 location = NSMaxRange(found)
83 }
84 return result + ns.substring(from: min(location, ns.length))
85 }
86
87 /// `orgtbl-to-csv` of a table: rules dropped, a field with `"` or `,` quoted, no final
88 /// newline. Cells the Org exporter could change are refused.
89 static func csvFile(_ rows: [[Cell]?], name: String) throws -> String {
90 try rows.compactMap { $0 }.map { row in
91 try row.map { cell in
92 let text = cellText(cell)
93 guard text.range(of: "[\\[\\]{}<>@\\\\\\n\\t]|src_|call_", options: .regularExpression) == nil,
94 text == text.trimmingCharacters(in: .whitespaces) else {
95 throw Failure.message(":var \(name) has a cell the Org exporter may change; nothing was run.")
96 }
97 return text.contains("\"") || text.contains(",") ? "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : text
98 }.joined(separator: ",")
99 }.joined(separator: "\n")
100 }
101
102 // MARK: - Results
103
104 /// ob-sqlite's result from `sqlite3`'s output: the output
105 /// as a string or through `org-table-convert-region` as a table, a single cell alone.
106 static func sqliteValue(_ output: String, csv: Bool, headers: Bool, scalar: Bool) -> Value {
107 // csv mode ends lines with CRLF, and Emacs keeps the CR.
108 let text = output
109 if scalar { return .string(text) }
110 if text.isEmpty { return .string("") }
111 guard var rows: [[String]?] = convertRegion(text, csv: csv) else { return .none }
112 if headers, let first = rows.first {
113 rows = [first, nil] + rows.dropFirst()
114 }
115 // `org-babel-sqlite-table-or-scalar`.
116 if rows.count == 1, let only = rows[0], only.count == 1 { return .string(babelRead(only[0])) }
117 return .table(rows.map { $0?.map(babelRead) })
118 }
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
127 /// `org-babel-read` with Lisp evaluation inhibited: a number as Emacs prints it, a single
128 /// quoted string read, else the cell.
129 static func babelRead(_ cell: String) -> String {
130 guard cell.contains(where: { !$0.isWhitespace }) else { return cell }
131 if !cell.contains("\r"), let n = number(cell), cell.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil { return n }
132 let trimmed = cell.trimmingCharacters(in: .whitespacesAndNewlines)
133 if trimmed.hasPrefix("\""), trimmed.count >= 2, trimmed.hasSuffix("\""),
134 let (sexp, length) = try? LispReader.readFirst(trimmed), length == trimmed.count, let s = sexp.string {
135 return s
136 }
137 return cell
138 }
139
140 /// `org-table-convert-region` on the whole output, then `org-table-to-lisp` of the aligned
141 /// table: rows of cells, padded to the widest row. Nil where Emacs fails: a last empty line
142 /// in a region read without a comma separator puts point past the search bound.
143 static func convertRegion(_ text: String, csv: Bool) -> [[String]?]? {
144 var b = Array(text.unicodeScalars)
145 let nl: Unicode.Scalar = "\n", tab: Unicode.Scalar = "\t", space: Unicode.Scalar = " ", comma: Unicode.Scalar = ",", quote: Unicode.Scalar = "\""
146 var end = b.last == nl ? b.count - 1 : b.count
147 var point = 0
148 func bol(_ i: Int) -> Bool { i == 0 || b[i - 1] == nl }
149 func replace(_ range: Range<Int>, _ s: [Unicode.Scalar]) {
150 b.replaceSubrange(range, with: s)
151 if end >= range.upperBound { end += s.count - range.count } else if end > range.lowerBound { end = range.lowerBound }
152 }
153 enum Separator { case comma, tab, spaces }
154 var separator = Separator.comma
155 if !csv {
156 let lines = String(String.UnicodeScalarView(b[0..<end])).components(separatedBy: "\n").filter { !$0.isEmpty }
157 if !lines.contains(where: { !$0.contains("\t") }) {
158 separator = .tab
159 } else if !lines.contains(where: { !$0.contains(",") }) {
160 separator = .comma
161 } else {
162 separator = .spaces
163 }
164 }
165 if separator == .comma {
166 while point < end {
167 if bol(point) {
168 replace(point..<point, ["|", " "])
169 point += 2
170 continue
171 }
172 var j = point
173 while j < b.count, b[j] == space || b[j] == tab { j += 1 }
174 if j == b.count || b[j] == nl {
175 // `[ \t]*$`, then the next line.
176 replace(point..<j, [" ", "|"])
177 point += 2
178 if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
179 continue
180 }
181 if b[j] == quote, let close = b[(j + 1)...].firstIndex(of: quote) {
182 let content = b[(j + 1)..<close].map { $0 == nl ? space : $0 }
183 replace(point..<(close + 1), Array(content))
184 point += content.count
185 if point < b.count, b[point] == quote {
186 replace(point..<point, [quote])
187 point += 1
188 }
189 continue
190 }
191 if point < b.count, b[point] != comma, b[point] != nl {
192 while point < b.count, b[point] != comma, b[point] != nl { point += 1 }
193 continue
194 }
195 if j < b.count, b[j] == comma {
196 replace(point..<(j + 1), [" ", "|", " "])
197 point += 3
198 continue
199 }
200 if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
201 }
202 } else {
203 // `re-search-forward` of "^\\|\t", or "^ *\\| *\t *\\| \\{1,\\}", each match
204 // replaced by "| ".
205 while point <= end {
206 var match: Range<Int>?
207 var i = point
208 while i <= end, match == nil {
209 if bol(i) {
210 var k = i
211 if separator == .spaces { while k < end, b[k] == space { k += 1 } }
212 match = i..<k
213 } else if i < end {
214 if separator == .tab {
215 if b[i] == tab { match = i..<(i + 1) }
216 } else {
217 var k = i
218 while k < end, b[k] == space { k += 1 }
219 if k < end, b[k] == tab {
220 var m = k + 1
221 while m < end, b[m] == space { m += 1 }
222 match = i..<m
223 } else if k > i {
224 match = i..<k
225 }
226 }
227 }
228 i += 1
229 }
230 guard let found = match else { break }
231 if found.lowerBound == end { return nil }
232 replace(found, ["|", " "])
233 point = found.lowerBound + 2
234 }
235 }
236 // The table: the lines from the start that begin with `|`.
237 var rows: [[String]] = []
238 for line in String(String.UnicodeScalarView(b)).components(separatedBy: "\n") {
239 var s = Substring(line)
240 s = s.drop { $0 == " " || $0 == "\t" }
241 guard s.first == "|" else { break }
242 s = s.dropFirst()
243 var cells: [String] = []
244 while true {
245 s = s.drop { $0 == " " || $0 == "\t" }
246 if s.isEmpty { break }
247 let field = s.prefix { $0 != "|" }
248 var cell = Substring(field)
249 while let last = cell.last, last == " " || last == "\t" { cell = cell.dropLast() }
250 cells.append(String(cell))
251 s = s.dropFirst(field.count)
252 if !s.isEmpty { s = s.dropFirst() }
253 }
254 rows.append(cells)
255 }
256 let width = rows.map(\.count).max() ?? 0
257 return rows.map { $0 + Array(repeating: "", count: width - $0.count) }
258 }
259}
Sources/OrgCore/Semantic/DisplayWidth.swift +3
@@ -8,6 +8,9 @@ func displayWidth(of character: Character) -> Int {
8 guard let scalar = character.unicodeScalars.first else { return 0 } 8 guard let scalar = character.unicodeScalars.first else { return 0 }
9 if scalar.properties.isEmojiPresentation { return 2 } 9 if scalar.properties.isEmojiPresentation { return 2 }
10 switch scalar.value { 10 switch scalar.value {
11 case 0x00...0x08, 0x0B...0x1F, 0x7F:
12 // Emacs shows a control character as `^M`.
13 return character.unicodeScalars.count == 1 ? 2 : 1
11 case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF, 14 case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF,
12 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x20000...0x3FFFD: 15 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x20000...0x3FFFD:
13 return 2 16 return 2
Sources/OrgPrograms/BabelRunner.swift +6 −1
@@ -51,7 +51,12 @@ public enum BabelRunner {
51 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 51 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
52 defer { try? FileManager.default.removeItem(at: folder) } 52 defer { try? FileManager.default.removeItem(at: folder) }
53 let resultFile = folder.appendingPathComponent("result") 53 let resultFile = folder.appendingPathComponent("result")
54 let input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path) 54 var input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
55 for (token, contents) in job.dataFiles {
56 let file = folder.appendingPathComponent("sql-data-\(token.filter(\.isNumber))")
57 try contents.write(to: file, atomically: true, encoding: .utf8)
58 input = input.replacingOccurrences(of: token, with: file.path)
59 }
55 if case .session(let name, let executable, let kind) = job.runner { 60 if case .session(let name, let executable, let kind) = job.runner {
56 let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory 61 let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory
57 return try await BabelSessions.shared.run(job, name: name, executable: executable, kind: kind, directory: directory, resultFile: resultFile) 62 return try await BabelSessions.shared.run(job, name: name, executable: executable, kind: kind, directory: directory, resultFile: resultFile)
Sources/OrgPrograms/Programs.swift +13
@@ -21,8 +21,21 @@ public struct Programs: ProgramRunning {
21 if words.count == 1, !BabelRunner.installed(words[0]), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } 21 if words.count == 1, !BabelRunner.installed(words[0]), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
22 case .session(_, let executable, _): 22 case .session(_, let executable, _):
23 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } 23 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
24 case .process where job.language == "sqlite":
25 // `sqlite3` when it's installed, as Emacs runs it; the SQLite library otherwise.
26 if !BabelRunner.installed("sqlite3"), let output = try SQLiteBlocks.run(job, directory: fileDirectory) { return output }
24 case .process: 27 case .process:
25 break 28 break
29 case .emacs where job.calc != nil:
30 // calc natively, and in Emacs what Calc here refuses.
31 do {
32 return try Babel.evaluateCalc(job)
33 } catch let refusal as Calc.Unsupported {
34 guard emacs() != nil else { throw BabelRunner.Failure(description: TableReason.calcRefusal(refusal.reason)) }
35 }
36 let output = try await BabelRunner.run(job, fileDirectory: fileDirectory)
37 if output.status != 0 { throw BabelRunner.Failure(description: output.stderr.trimmingCharacters(in: .whitespacesAndNewlines)) }
38 return output
26 case .emacs: 39 case .emacs:
27 // Emacs Lisp in `Elisp` when Emacs isn't installed. 40 // Emacs Lisp in `Elisp` when Emacs isn't installed.
28 if emacs() == nil { 41 if emacs() == nil {
Tests/OrgAppTests/SQLiteBlocksTests.swift added +288
@@ -0,0 +1,288 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// sqlite blocks with the SQLite library, compared with macOS's `sqlite3` and with Emacs
8/// running it.
9struct SQLiteBlocksTests {
10 static let sqlite3 = "/usr/bin/sqlite3"
11 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && FileManager.default.isExecutableFile(atPath: sqlite3)
12
13 static let values = """
14 select 1 as a, 'x y' as b, null as c, 2.50 as d, 'it''s' as e, '' as f, -7 as g, 0.1 + 0.2 as h
15 union all select 22, 'é,ü', 'q"t', 1e20, '<&>', ' lead', 3.0, 'tab\tin';
16 """
17
18 /// Options as ob-sqlite writes them, and scripts.
19 static let cli: [([String], String)] = [
20 (["-noheader", "-csv"], values),
21 (["-header", "-csv"], values),
22 (["-noheader", "-list"], values),
23 (["-noheader", "-header", "-list"], values),
24 (["-noheader", "-column"], "select 1 as a, 'xx' as long_name, 2.5 as mid union all select -10, null, 'text';\nselect 'second' as s;"),
25 (["-noheader", "-html"], values),
26 (["-noheader", "-line"], values + "\nselect 'a\nb\n' as multi, 'c' as longer_name;"),
27 (["-noheader", "-separator", "X"], values),
28 (["-header", "-separator", ";"], values),
29 (["-noheader", "-separator", "X", "-nullvalue", "N"], values),
30 (["-noheader", "-nullvalue", "N", "-csv"], values),
31 (["-noheader", "-csv"], "\nselect 1;\n\n select 2; select 3;\n# comment\nselect 4\n;\nselect 5"),
32 (["-noheader", "-echo", "-csv"], "\nselect 1;\n select 2; select 3;\n# c\n.mode list\n\nselect 4\n;\n"),
33 (["-noheader", "-csv"], ".headers on\nselect 1 as a;\n.mode column\nselect 2 as b;\n.mode list\nselect 3 as c;\n.mode csv\nselect 4 as d;\n"),
34 (["-noheader", "-csv"], ".mode column\n.headers off\nselect 1 as a, null as n;\n.headers on\n.mode html\n.nullvalue N\nselect 1 as a, null as n;"),
35 (["-noheader", "-csv"], ".mode line\n.separator X\nselect 1 as a, null as n;\n.mode csv\n.separator :\nselect 'a:b' as a, 'c,d';"),
36 (["-noheader", "-csv"], ".nullvalue N\nselect null;\n.mode list\nselect null;\n.nullvalue M\nselect null, 1;"),
37 (["-noheader", "-csv"], "create table t(a integer, b text, c real);\ninsert into t values (1, 'one', 1.5), (2, null, -0.25), (30, 'thirty', 1e100);\nselect * from t order by a;\nselect count(*) as n from t;\nselect a from t where 0;"),
38 (["-noheader", "-column"], "create table t(a, b);\ninsert into t values (1, 'xx'), (22, null), (3.5, 'y');\nselect * from t;\nselect a from t where 0;\n"),
39 (["-noheader", "-csv"], "select 1;\nselect * from nope;\nselect 2;\nselect 3; select * from nope; select 4;\nselect 5;"),
40 (["-noheader", "-bail", "-csv"], "select 1;\nselect * from nope;\nselect 2;"),
41 (["-noheader", "-csv"], "select 1 union all select abs(-9223372036854775808);\nselect 2;"),
42 (["-noheader", "-csv"], "create table t(a unique);\ninsert into t values (1);\ninsert into t values (1);\nselect count(*) from t;"),
43 (["-noheader", "-csv"], "select 1 -- a comment\n;\n/* c */ select 2;\n-- only a comment\nselect 3 /* trailing"),
44 (["-noheader", "-csv"], "select $x, ?, :y;"),
45 (["-noheader", "-html"], "select 'a''b\"c<d>e&f' as \"<h>\";"),
46 (["-noheader", "-csv"], "select 'line\ntwo', 'a,b', '\"', 'plain' as \"col name\", 'x' as \"q\"\"n\";"),
47 (["-noheader", "-csv"], ".mode list\n.separator ,\nselect 'a,b', 'c';\n.mode list\nselect 'a,b';"),
48 (["-noheader", "-header", "-csv"], "create table t(a, b);\n.headers on\nselect * from t;\ninsert into t values (1, 2);\nselect * from t;"),
49 ]
50
51 static func cliOutput(_ arguments: [String], _ input: String, folder: URL) throws -> (stdout: String, status: Int32) {
52 let process = Process()
53 process.executableURL = URL(fileURLWithPath: sqlite3)
54 process.arguments = arguments
55 process.currentDirectoryURL = folder
56 let stdin = Pipe(), stdout = Pipe()
57 process.standardInput = stdin
58 process.standardOutput = stdout
59 process.standardError = FileHandle.nullDevice
60 try process.run()
61 stdin.fileHandleForWriting.write(Data(input.utf8))
62 try stdin.fileHandleForWriting.close()
63 let data = stdout.fileHandleForReading.readDataToEndOfFile()
64 process.waitUntilExit()
65 return (String(decoding: data, as: UTF8.self), process.terminationStatus)
66 }
67
68 @Test(.enabled(if: oracle))
69 func shellMatchesSqlite3() throws {
70 for (arguments, script) in Self.cli {
71 let input = script + "\n"
72 let theirFolder = try Folder(), ourFolder = try Folder()
73 let theirs = try Self.cliOutput(arguments, input, folder: theirFolder.url)
74 var shell = try SQLiteBlocks.Shell(arguments: arguments)
75 let ours = try shell.run(input, folder: ourFolder.url)
76 #expect(ours.stdout == theirs.stdout, "\(arguments) \(script.debugDescription)\nours:\n\(ours.stdout.debugDescription)\nsqlite3:\n\(theirs.stdout.debugDescription)")
77 #expect(ours.status == theirs.status, "\(arguments) \(script.debugDescription)")
78 }
79 }
80
81 static let table = "#+NAME: tbl\n| id | name |\n|----+-------|\n| 1 | one |\n| 2 | two |\n| 3 | x, \"y\" |\n\n"
82
83 static let blocks: [String] = [
84 "#+begin_src sqlite\nselect 1 as a, 'x y' as b, null as c, 2.50 as d;\nselect 'q\"t', 'é', '007', '\"quoted\"';\n#+end_src\n",
85 "#+begin_src sqlite :colnames yes\nselect 1 as a, 2 as b;\nselect 3, 4;\n#+end_src\n",
86 "#+begin_src sqlite\nselect 42;\n#+end_src\n",
87 "#+begin_src sqlite\nselect 'line\ntwo', 'a,b';\n#+end_src\n",
88 "#+begin_src sqlite :list\nselect 1, 'x y';\n#+end_src\n",
89 "#+begin_src sqlite :column\nselect 1 as a, 'x y' as b;\n#+end_src\n",
90 "#+begin_src sqlite :html\nselect 1 as a, 'x' as b;\n#+end_src\n",
91 "#+begin_src sqlite :line\nselect 1 as a, 'x' as b;\n#+end_src\n",
92 "#+begin_src sqlite :separator X\nselect 1 as a, 'x y' as b;\n#+end_src\n",
93 "#+begin_src sqlite :separator , :nullvalue N\nselect 1, null, 'a b';\n#+end_src\n",
94 "#+begin_src sqlite :header\nselect 1 as a, 2 as b;\n#+end_src\n",
95 "#+begin_src sqlite :csv\nselect 1 as a, 'b c' as b;\n#+end_src\n",
96 "#+begin_src sqlite :results output\nselect 1, 2;\n#+end_src\n",
97 "#+begin_src sqlite :results output\nselect 'line\ntwo', 'a,b';\n#+end_src\n",
98 "#+begin_src sqlite :results verbatim\nselect 1, 2;\nselect 3, 4;\n#+end_src\n",
99 "#+begin_src sqlite :results raw\nselect '*bold*';\n#+end_src\n",
100 "#+begin_src sqlite :results table\nselect 7;\n#+end_src\n",
101 "#+begin_src sqlite :results list\nselect 1, 2;\nselect 3, 4;\n#+end_src\n",
102 "#+begin_src sqlite\ncreate table t(a);\n#+end_src\n",
103 "#+begin_src sqlite\nselect 1 where 0;\n#+end_src\n",
104 "#+begin_src sqlite :db test.db\ncreate table if not exists t(a, b);\ninsert into t values (1, 'one'), (2, 'two');\nselect * from t order by a;\n#+end_src\n",
105 "#+begin_src sqlite :db test2.db :readonly yes\nselect 1;\n#+end_src\n",
106 "#+begin_src sqlite :var x=3 name=\"two\"\nselect $x * 2, '$name', $X;\n#+end_src\n",
107 "#+begin_src sqlite :var x=2.50\nselect $x;\n#+end_src\n",
108 table + "#+begin_src sqlite :var t=tbl\ncreate table v(id integer, name text);\n.mode csv\n.import $t v\nselect name, id * 10 from v order by id;\n#+end_src\n",
109 table + "#+begin_src sqlite :var t=tbl :colnames yes\ncreate table v(id integer, name text);\n.import --csv $t v\n.headers on\nselect * from v;\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",
112 "#+begin_src sqlite :bail\nselect 1;\nselect * from nope;\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",
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",
117 "#+begin_src sqlite :separator ,\nselect 1, 2;\nselect 3;\n#+end_src\n",
118 "#+begin_src sqlite\nselect '';\n#+end_src\n",
119 "#+begin_src sqlite\nselect 1, '';\nselect '', '';\n#+end_src\n",
120 ]
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 "#+begin_src sqlite :cache yes :var x=4\nselect $x * 2;\n#+end_src\n",
164 "#+begin_src sqlite :cache yes :prologue \"select 0;\"\nselect 1, 2;\n#+end_src\n",
165 ]
166
167 @MainActor
168 @Test(.enabled(if: oracle))
169 func probesMatchEmacsOrAreRefused() async throws {
170 let (ours, emacs, messages) = try await Self.compare(Self.probes)
171 for (i, text) in Self.probes.enumerated() where !messages[i].hasPrefix("This sqlite block can't run here") {
172 if emacs[i].hasPrefix("ERROR: ") {
173 // Emacs fails the run: the same message, and nothing written.
174 #expect(messages[i] == emacs[i].dropFirst("ERROR: ".count) && ours[i] == text, "\(text)\nours (\(messages[i])):\n\(ours[i])\nemacs:\n\(emacs[i])")
175 continue
176 }
177 #expect(ours[i] == emacs[i], "\(text)\nours (\(messages[i])):\n\(ours[i])\nemacs:\n\(emacs[i])")
178 }
179 }
180
181 /// The results the app inserts, as Emacs inserts them running `sqlite3`.
182 @MainActor
183 @Test(.enabled(if: oracle))
184 func resultsMatchEmacs() async throws {
185 let (ours, emacs, _) = try await Self.compare(Self.blocks)
186 for (i, text) in Self.blocks.enumerated() {
187 #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
188 }
189 }
190
191 /// Each block run by the app, and by Emacs, with the app's messages.
192 @MainActor
193 static func compare(_ blocks: [String]) async throws -> (ours: [String], emacs: [String], messages: [String]) {
194 let ourFolder = try Folder(), theirFolder = try Folder()
195 var forms: [String] = []
196 var ours: [String] = []
197 var messages: [String] = []
198 for text in blocks {
199 let caret = (text as NSString).range(of: "#+begin_src").location + 2
200 let file = try ourFolder.write("b.org", text)
201 let session = DocumentSession(recovery: FileRecoveryStore(directory: ourFolder.url.appendingPathComponent(".r")))
202 session.open(file.path)
203 switch session.perform(ExecuteSrcBlock(), path: file.path, at: caret, expect: nil) {
204 case .external(.babel(let job)): messages.append(await session.runBabel(job))
205 case let other: messages.append("\(other)")
206 }
207 ours.append(session.document?.text ?? "")
208 let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
209 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))))))")
210 }
211 let emacs = try Self.emacs("""
212 (progn (require 'org) (require 'ob-sqlite)
213 (setq org-confirm-babel-evaluate nil org-babel-sqlite3-command "\(Self.sqlite3)" default-directory "\(theirFolder.url.path)/")
214 \(forms.joined(separator: "\n")))
215 """).split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
216 return (ours, emacs, messages)
217 }
218
219 /// Emacs in a UTF-8 locale, as it runs on the Mac.
220 static func emacs(_ form: String) throws -> String {
221 let process = Process()
222 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
223 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
224 process.environment = ProcessInfo.processInfo.environment.merging(["LANG": "en_US.UTF-8", "LC_ALL": "en_US.UTF-8"]) { $1 }
225 let pipe = Pipe()
226 process.standardOutput = pipe
227 process.standardError = FileHandle.nullDevice
228 try process.run()
229 let data = pipe.fileHandleForReading.readDataToEndOfFile()
230 process.waitUntilExit()
231 return String(decoding: data, as: UTF8.self)
232 }
233
234 static func plan(_ text: String) throws -> BabelJob {
235 let caret = (text as NSString).range(of: "#+begin_src").location + 2
236 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
237 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned: \(text)") }
238 return job
239 }
240
241 /// What can't be shown as `sqlite3` shows it is refused, with nothing written.
242 @Test func refusals() throws {
243 let refused: [(String, SQLiteBlocks.Refusal)] = [
244 ("#+begin_src sqlite :db \"my file.db\"\nselect 1;\n#+end_src\n", .init(.shell)),
245 ("#+begin_src sqlite :separator |\nselect 1;\n#+end_src\n", .init(.shell)),
246 ("#+begin_src sqlite :header :separator ;\nselect 1;\n#+end_src\n", .init(.shell)),
247 ("#+begin_src sqlite\n.separator ;\nselect 1;\n#+end_src\n", .init(.dotCommand(".separator"))),
248 ("#+begin_src sqlite :db ~/x.db\nselect 1;\n#+end_src\n", .init(.shell)),
249 ("#+begin_src sqlite\n.tables\n#+end_src\n", .init(.dotCommand(".tables"))),
250 ("#+begin_src sqlite\n.mode box\nselect 1;\n#+end_src\n", .init(.dotCommand(".mode"))),
251 ("#+begin_src sqlite\n.separator \"\\t\"\nselect 1;\n#+end_src\n", .init(.dotCommand(".separator"))),
252 ("#+begin_src sqlite\nselect x'00';\n#+end_src\n", .init(.blob)),
253 ("#+begin_src sqlite\nselect 'a' || char(13) || 'b';\n#+end_src\n", .init(.control)),
254 ("#+begin_src sqlite :column\nselect 'é';\n#+end_src\n", .init(.width)),
255 ("#+begin_src sqlite :column\nselect 'a\nb';\n#+end_src\n", .init(.width)),
256 ("#+begin_src sqlite\nexplain select 1;\n#+end_src\n", .init(.explain)),
257 ("#+begin_src sqlite :echo\nselect 1;\n#+end_src\n", .init(.echo)),
258 ("#+begin_src sqlite\ncreate table t(a);\nselect x'01';\n#+end_src\n", .init(.blob, partly: true)),
259 (Self.table + "#+begin_src sqlite :var t=tbl\n.import --csv $t v\n#+end_src\n", .init(.newTable)),
260 (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)),
261 ]
262 let folder = try Folder()
263 for (text, refusal) in refused {
264 #expect(throws: Babel.Failure.message(refusal.message), "\(text)") { try SQLiteBlocks.run(Self.plan(text), directory: folder.url) }
265 }
266 #expect(try SQLiteBlocks.run(Self.plan("#+begin_src js\n1\n#+end_src\n"), directory: folder.url) == nil)
267 }
268
269 /// The sandboxed builds run calc blocks natively, and say why they refuse one.
270 @MainActor
271 @Test func calcBlocksRunInTheSession() async throws {
272 let folder = try Folder()
273 for (text, message, result) in [
274 ("#+begin_src calc\n1/3\n#+end_src\n", "Code block evaluation complete.", "#+RESULTS:\n: 0.333333333333\n"),
275 ("#+begin_src calc\n1\n'x\n#+end_src\n", "This calc block can't be calculated here: stack command 'x.", ""),
276 ] {
277 let file = try folder.write("c.org", text)
278 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
279 session.open(file.path)
280 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 2, expect: nil) else {
281 Issue.record("not planned: \(text)")
282 return
283 }
284 #expect(await session.runBabel(job) == message)
285 #expect(session.document?.text == text + (result.isEmpty ? "" : "\n" + result))
286 }
287 }
288}
Tests/OrgCoreTests/BabelCalcTests.swift added +166
@@ -0,0 +1,166 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// calc blocks on `Calc`, compared with ob-calc in Emacs.
6struct BabelCalcTests {
7 static let table = "#+NAME: tb\n| 1 | 2 |\n| 3 | 4 |\n\n"
8
9 static let cases: [String] = [
10 "#+begin_src calc\n1+2\n#+end_src\n",
11 "#+begin_src calc\n1/3\n#+end_src\n",
12 "#+begin_src calc\n10 / 4\n#+end_src\n",
13 "#+begin_src calc\n7 % 3\n#+end_src\n",
14 "#+begin_src calc\n3.0\n#+end_src\n",
15 "#+begin_src calc\n1e3\n#+end_src\n",
16 "#+begin_src calc\n1.5e20 * 3\n#+end_src\n",
17 "#+begin_src calc\n1:3 + 1:6\n#+end_src\n",
18 "#+begin_src calc\nsqrt(2)\n#+end_src\n",
19 "#+begin_src calc\nsin(30)\n#+end_src\n",
20 "#+begin_src calc\n 5 \n\n#+end_src\n",
21 "#+begin_src calc\n3\n4\n'+\n#+end_src\n",
22 "#+begin_src calc\n1\n2\n'-\n#+end_src\n",
23 "#+begin_src calc\n1\n3\n'/\n#+end_src\n",
24 "#+begin_src calc\n2\n10\n'^\n#+end_src\n",
25 "#+begin_src calc\n7\n2\n'%\n#+end_src\n",
26 "#+begin_src calc\n7\n2\n'\\\n#+end_src\n",
27 "#+begin_src calc\n2\n'n\n#+end_src\n",
28 "#+begin_src calc\n4\n'&\n#+end_src\n",
29 "#+begin_src calc\n9\n'Q\n#+end_src\n",
30 "#+begin_src calc\n-3\n'A\n#+end_src\n",
31 "#+begin_src calc\n1.0\n2\n'+\n#+end_src\n",
32 "#+begin_src calc\n1\n2\n#+end_src\n",
33 "#+begin_src calc :var x=5 y=2.5\nx*y+1\n#+end_src\n",
34 "#+begin_src calc :var x=5\nx\n#+end_src\n",
35 "#+begin_src calc :var x=5\nx*2\n#+end_src\n",
36 "#+begin_src calc :var x=5\n2 x\n#+end_src\n",
37 "#+begin_src calc :var x=5\n[x, 2 x]\n#+end_src\n",
38 "#+begin_src calc :var x=5\nx\nx\n'*\n#+end_src\n",
39 "#+begin_src calc :var x=2.5\nx\n2\n'*\n#+end_src\n",
40 "#+begin_src calc :var x=0.1\nx * 3\n#+end_src\n",
41 "#+begin_src calc :var x=1e20\nx\n#+end_src\n",
42 "#+begin_src calc :var xy=5 x=2\nxy\n#+end_src\n",
43 "#+begin_src calc :var x=5 :results table\nx\n#+end_src\n",
44 "#+begin_src calc\nx + 1\n#+end_src\n",
45 "#+begin_src calc\n2 x + 3 x\n#+end_src\n",
46 "#+begin_src calc\n[1, 2, 3]\n#+end_src\n",
47 "#+begin_src calc\n[[1, 2], [3, 4]]\n#+end_src\n",
48 "#+begin_src calc\n[1, [2, 3]]\n#+end_src\n",
49 "#+begin_src calc\n[[1, 2], [3]]\n#+end_src\n",
50 "#+begin_src calc :results scalar\n[1, 2, 3]\n#+end_src\n",
51 "#+begin_src calc :results output\n1+1\n#+end_src\n",
52 "#+begin_src calc :results verbatim\n1/4\n#+end_src\n",
53 "#+begin_src calc :var v='(1 2 3)\nvsum(v)\n#+end_src\n",
54 "#+begin_src calc :var v='(1 2 3)\nv\n#+end_src\n",
55 table + "#+begin_src calc :var m=tb\nm\n#+end_src\n",
56 "#+begin_src calc :prologue \"2\" :epilogue \"'*\"\n3\n#+end_src\n",
57 "#+NAME: hd\n| a | b |\n|---+---|\n| 1 | 2 |\n| 3 | 4 |\n\n#+begin_src calc :var m=hd\nm\n#+end_src\n",
58 // Errors in Emacs: the result isn't written.
59 "#+begin_src calc :var x=5\n3\n'+\n#+end_src\n",
60 "#+begin_src calc :var x=5\nx*2\n3\n'+\n#+end_src\n",
61 "#+begin_src calc\n'+\n#+end_src\n",
62 "#+begin_src calc\n#+end_src\n",
63 ]
64
65 static func caret(_ text: String) -> Int { (text as NSString).range(of: "#+begin_src").location + 2 }
66
67 /// The block run with `Babel.evaluateCalc`.
68 static func native(_ text: String) throws -> (text: String, failure: String?) {
69 try TestBabelRunner.execute(text, caret: caret(text), directory: FileManager.default.temporaryDirectory, native: true)
70 }
71
72 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
73 func blocksMatchEmacs() throws {
74 let folder = FileManager.default.temporaryDirectory
75 var emacsCases: [EmacsOracle.Case] = []
76 var ours: [(text: String, failure: String?)] = []
77 var fallback: [(text: String, failure: String?)] = []
78 for text in Self.cases {
79 ours.append(try Self.native(text))
80 fallback.append(try TestBabelRunner.execute(text, caret: Self.caret(text), directory: folder))
81 emacsCases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(Self.caret(text), in: text), form: """
82 (progn (require 'ob-calc) (setq org-confirm-babel-evaluate nil)
83 ;; A new stack, as in a new Emacs.
84 (save-window-excursion (calc) (when (> (calc-stack-size) 0) (calc-pop (calc-stack-size))) (calc-quit))
85 (org-babel-execute-src-block))
86 """))
87 }
88 let emacs = try EmacsOracle.run(emacsCases)
89 for (i, theirs) in emacs.enumerated() {
90 #expect(ours[i].text == theirs.text, "case \(i):\n\(Self.cases[i])\nours (\(ours[i].failure ?? "")):\n\(ours[i].text)\nemacs (\(theirs.error)):\n\(theirs.text)")
91 #expect((ours[i].failure != nil) == !theirs.error.isEmpty, "case \(i): ours \(ours[i].failure ?? "ok"), emacs \(theirs.error)")
92 #expect(fallback[i].text == theirs.text, "case \(i) in Emacs:\n\(Self.cases[i])\nours:\n\(fallback[i].text)\nemacs:\n\(theirs.text)")
93 }
94 }
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 "#+begin_src calc :cache yes :prologue \"2\"\n3\n'+\n#+end_src\n",
117 "#+begin_src calc :cache yes :var x=2\nx*3\n#+end_src\n",
118 ]
119
120 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
121 func probesMatchEmacsOrAreRefused() throws {
122 var cases: [EmacsOracle.Case] = []
123 var ours: [(text: String, failure: String?)?] = []
124 for text in Self.probes {
125 ours.append(try? Self.native(text))
126 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(Self.caret(text), in: text), form: """
127 (progn (require 'ob-calc) (setq org-confirm-babel-evaluate nil)
128 (save-window-excursion (calc) (when (> (calc-stack-size) 0) (calc-pop (calc-stack-size))) (calc-quit))
129 (org-babel-execute-src-block))
130 """))
131 }
132 let emacs = try EmacsOracle.run(cases)
133 for (i, theirs) in emacs.enumerated() {
134 guard let mine = ours[i] else { continue }
135 #expect(mine.text == theirs.text, "\(Self.probes[i])\nours (\(mine.failure ?? "")):\n\(mine.text)\nemacs (\(theirs.error)):\n\(theirs.text)")
136 }
137 }
138
139 /// What Calc here doesn't do as Emacs's does is refused, with the reason.
140 @Test func refusals() throws {
141 let refused: [(String, String)] = [
142 ("#+begin_src calc\n1\n'x\n#+end_src\n", "stack command 'x"),
143 ("#+begin_src calc\n1\n2\n'TAB\n#+end_src\n", "stack command 'TAB"),
144 ("#+begin_src calc :var s=\"abc\"\ns\n#+end_src\n", "value of :var s"),
145 ("#+begin_src calc :var v='(1.5 2)\nv\n#+end_src\n", "value of :var v"),
146 ("#+begin_src calc :var v='(1)\nv\n#+end_src\n", "value of :var v"),
147 ("#+begin_src calc :var e=5\ne\n#+end_src\n", "value of :var e"),
148 ("#+begin_src calc :var my_x=5\nmy_x\n#+end_src\n", "value of :var my_x"),
149 ("#+begin_src calc :prologue 2\n3\n#+end_src\n", "numeric :prologue or :epilogue"),
150 ("#+begin_src calc\n2^100\n#+end_src\n", "integer size"),
151 ("#+begin_src calc\n[]\n#+end_src\n", "empty vector"),
152 (Self.table + "#+begin_src calc :var m=tb\ndet(m)\n#+end_src\n", "function det"),
153 ]
154 for (text, reason) in refused {
155 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [Self.caret(text)..<Self.caret(text)])
156 guard case .success(let job) = Babel.plan(context) else { Issue.record("not planned: \(text)"); continue }
157 #expect(job.runner == .emacs)
158 #expect(throws: Calc.Unsupported.self, "\(text)") { try Babel.evaluateCalc(job) }
159 do {
160 _ = try Babel.evaluateCalc(job)
161 } catch let error as Calc.Unsupported {
162 #expect(error.reason == reason, "\(text)")
163 }
164 }
165 }
166}
Tests/OrgCoreTests/BabelTests.swift +11 −2
@@ -11,7 +11,12 @@ enum TestBabelRunner {
11 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 11 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
12 defer { try? FileManager.default.removeItem(at: folder) } 12 defer { try? FileManager.default.removeItem(at: folder) }
13 let resultFile = folder.appendingPathComponent("result") 13 let resultFile = folder.appendingPathComponent("result")
14 let input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path) 14 var input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
15 for (token, contents) in job.dataFiles {
16 let file = folder.appendingPathComponent(token)
17 try contents.write(to: file, atomically: true, encoding: .utf8)
18 input = input.replacingOccurrences(of: token, with: file.path)
19 }
15 let process = Process() 20 let process = Process()
16 process.executableURL = URL(fileURLWithPath: "/usr/bin/env") 21 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
17 switch job.runner { 22 switch job.runner {
@@ -42,7 +47,8 @@ enum TestBabelRunner {
42 try stdin.fileHandleForWriting.close() 47 try stdin.fileHandleForWriting.close()
43 let data = stdout.fileHandleForReading.readDataToEndOfFile() 48 let data = stdout.fileHandleForReading.readDataToEndOfFile()
44 process.waitUntilExit() 49 process.waitUntilExit()
45 return BabelOutput(stdout: String(decoding: data, as: UTF8.self), resultFile: try? String(contentsOf: resultFile, encoding: .utf8)) 50 return BabelOutput(stdout: String(decoding: data, as: UTF8.self), resultFile: try? String(contentsOf: resultFile, encoding: .utf8),
51 status: process.terminationStatus)
46 } 52 }
47 53
48 /// Plans, runs and finishes the block at `caret`: the new text, or the failure. 54 /// Plans, runs and finishes the block at `caret`: the new text, or the failure.
@@ -50,6 +56,7 @@ enum TestBabelRunner {
50 static func execute(_ text: String, caret: Int, directory: URL, native: Bool = false) throws -> (text: String, failure: String?) { 56 static func execute(_ text: String, caret: Int, directory: URL, native: Bool = false) throws -> (text: String, failure: String?) {
51 func run(_ job: BabelJob, directory: URL) throws -> BabelOutput { 57 func run(_ job: BabelJob, directory: URL) throws -> BabelOutput {
52 guard native else { return try TestBabelRunner.run(job, directory: directory) } 58 guard native else { return try TestBabelRunner.run(job, directory: directory) }
59 if job.calc != nil { return try Babel.evaluateCalc(job) }
53 guard let output = try Babel.evaluateNatively(job) else { throw NativeUnsupported() } 60 guard let output = try Babel.evaluateNatively(job) else { throw NativeUnsupported() }
54 return output 61 return output
55 } 62 }
@@ -70,6 +77,8 @@ enum TestBabelRunner {
70 guard case .message(let message) = failure else { return (text, nil) } 77 guard case .message(let message) = failure else { return (text, nil) }
71 return (text, message) 78 return (text, message)
72 } 79 }
80 // A calc block's error in Emacs.
81 if job.calc != nil, output.status != 0 { return (text, "error") }
73 if let file = Babel.fileResult(job, output: output) { 82 if let file = Babel.fileResult(job, output: output) {
74 try file.contents.write(to: directory.appendingPathComponent(file.path), atomically: true, encoding: .utf8) 83 try file.contents.write(to: directory.appendingPathComponent(file.path), atomically: true, encoding: .utf8)
75 } 84 }
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 +52 −3
@@ -94,6 +94,8 @@ On the Mac, orgstar starts each interpreter outside a =:session= through =/bin/s
94| =js=, =javascript= | =node FILE=, the program written to a file, or JavaScriptCore without node; see below | 94| =js=, =javascript= | =node FILE=, the program written to a file, or JavaScriptCore without node; see below |
95| =R= | =Rscript -= | 95| =R= | =Rscript -= |
96| =awk= | =awk -f=, the program written to a file | 96| =awk= | =awk -f=, the program written to a file |
97| =calc= | orgstar's Calc, or =emacs -Q --batch=; see below |
98| =sqlite= | =sqlite3=, or the SQLite library without it; see below |
97| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below | 99| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below |
98| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below | 100| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below |
99 101
@@ -103,7 +105,7 @@ Any other language is refused with "No way to run /language/ blocks yet."
103 105
104A run that takes longer than five minutes is stopped. Runs in a =:session= have no time limit, except in JavaScriptCore. 106A run that takes longer than five minutes is stopped. Runs in a =:session= have no time limit, except in JavaScriptCore.
105 107
106The [[file:../install.org][Mac App Store version]] starts no programs, so only Emacs Lisp and JavaScript blocks run there; see /In the Mac App Store version/ below. 108The [[file:../install.org][Mac App Store version]] starts no programs, so only Emacs Lisp, JavaScript, calc and sqlite blocks run there; see /In the Mac App Store version/ below.
107 109
108** JavaScript in JavaScriptCore 110** JavaScript in JavaScriptCore
109 111
@@ -626,6 +628,53 @@ In the [[file:../install.org][Mac App Store version]], Emacs Lisp blocks run in
626 628
627Variables are bound with =let= around the body. =:results output= collects what the block prints with =princ=, =prin1=, =print= and =terpri=. 629Variables are bound with =let= around the body. =:results output= collects what the block prints with =princ=, =prin1=, =print= and =terpri=.
628 630
631* calc blocks
632
633A =calc= block runs as ob-calc runs it in =emacs -Q=, with orgstar's Calc, the one table formulas use. Each line of the body is trimmed and handled in turn; blank lines are skipped:
634
635- A line that is the name of a =:var= puts its value on the stack.
636- A line that starts with ='= runs a stack key on the stack: ='+=, ='-=, ='*=, ='/=, ='^=, ='%= (modulo), ='\= (integer division), ='n= (negate), ='&= (inverse), ='Q= (square root) and ='A= (absolute value).
637- Any other line is a formula. Its value goes on the stack; if it isn't a number, the formula is evaluated again with the block's variables put in, and that goes on the stack as text, as ob-calc does.
638
639The result is the top of the stack, shown with Calc's own settings in =emacs -Q=: 12 significant digits, all of them shown (=1/3= gives =0.333333333333=). A vector is written as a table row and a matrix as a table, unless =:results= asks for a string. =:prologue= and =:epilogue= add lines before and after the body.
640
641Each run starts with an empty stack. In Emacs the Calculator's stack carries over from one block to the next, so a block that relies on what an earlier block left there gives a different result in orgstar.
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.
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, 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
647* sqlite blocks
648
649A =sqlite= block runs as ob-sqlite runs it: the body goes to =sqlite3= on standard input, with the options the header arguments name, and the output becomes the result. The download version runs =sqlite3= (macOS has one in =/usr/bin=) and uses the SQLite library only when it isn't installed. The Mac App Store version and iOS run the block in the SQLite library, writing the output as macOS's =sqlite3= writes it.
650
651| Header argument | Effect |
652|-----------------------------+----------------------------------------------------------------------------|
653| =:db file= | The database, relative to the file's folder or =:dir=; without it, an in-memory one |
654| =:readonly yes= | Opens the database read-only |
655| =:csv=, =:list=, =:column=, =:html=, =:line= | The output mode; without one or =:separator=, =csv= |
656| =:separator s=, =:nullvalue s= | The column separator and the text for NULL, in list mode |
657| =:colnames yes= | The first row of the result becomes the table's header |
658| =:header=, =:echo=, =:bail= | Pass =-header=, =-echo= and =-bail= to =sqlite3= |
659
660As in Emacs, a mode option resets the header, separator and NULL text to that mode's, so =:header= has an effect only with =:separator= alone.
661
662=:var= values replace =$name= in the body, in any case. A table becomes a CSV file and =$name= its path, for =.import=:
663
664#+begin_src org
665,#+begin_src sqlite :var t=prices :db shop.db
666create table if not exists prices(item text, price real);
667.import --csv $t prices
668select item, price * 2 from prices;
669,#+end_src
670#+end_src
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. 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
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
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
629* Graphics 678* Graphics
630 679
631=dot= (Graphviz), =plantuml= and =mermaid= blocks draw a picture into =:file=, and the result is a link to it. =:file= is required: "/language/ code blocks need a :file header argument". The file's extension picks the output format; with none, =png= is used. 680=dot= (Graphviz), =plantuml= and =mermaid= blocks draw a picture into =:file=, and the result is a link to it. =:file= is required: "/language/ code blocks need a :file header argument". The file's extension picks the output format; with none, =png= is used.
@@ -748,7 +797,7 @@ Tangling stops, writes nothing and says why when:
748 797
749* On iOS 798* On iOS
750 799
751- Only Emacs Lisp blocks, in orgstar's own interpreter, and JavaScript blocks, in JavaScriptCore (see /JavaScript in JavaScriptCore/ above), run. Any other language, compiled languages included, fails with "/language/ blocks need the Mac to run." (for example "C blocks need the Mac to run."), and so does a block whose =:var= refers to a block in another language. 800- Only Emacs Lisp blocks, in orgstar's own interpreter, JavaScript blocks, in JavaScriptCore (see /JavaScript in JavaScriptCore/ above), and calc and sqlite blocks (see above) run. Any other language, compiled languages included, fails with "/language/ blocks need the Mac to run." (for example "C blocks need the Mac to run."), and so does a block whose =:var= refers to a block in another language.
752- JavaScript blocks can use =:session=. There are no other sessions and no graphics. 801- JavaScript blocks can use =:session=. There are no other sessions and no graphics.
753- The trust prompt works the same way, with its own =trusted.json= on the device. 802- The trust prompt works the same way, with its own =trusted.json= on the device.
754- There is no cancel command. 803- There is no cancel command.
@@ -759,7 +808,7 @@ See [[file:14-ios.org][iOS]] for the rest of the iOS app.
759 808
760* In the Mac App Store version 809* In the Mac App Store version
761 810
762- Only Emacs Lisp blocks, in the same interpreter as on iOS, and JavaScript blocks, in JavaScriptCore, run. Any other language, compiled languages included, fails with "/language/ blocks don't run in this version of orgstar." 811- Only Emacs Lisp blocks, in the same interpreter as on iOS, JavaScript blocks, in JavaScriptCore, and calc and sqlite blocks run. Any other language, compiled languages included, fails with "/language/ blocks don't run in this version of orgstar."
763- JavaScript blocks can use =:session=. There are no other sessions and no graphics. 812- JavaScript blocks can use =:session=. There are no other sessions and no graphics.
764- The trust prompt works the same way. 813- The trust prompt works the same way.
765- Tangling works as in the download version, =:shebang= included. A target outside your folders needs access to its folder first: orgstar asks with Grant Access…, as described in [[file:../install.org][Install]]. So does a =:file= result outside them. 814- Tangling works as in the download version, =:shebang= included. A target outside your folders needs access to its folder first: orgstar asks with Grant Access…, as described in [[file:../install.org][Install]]. So does a =:file= result outside them.
docs/manual/guide/14-ios.org +3 −2
@@ -343,11 +343,12 @@ Publishing works from Commands as on the Mac, with the =[[publish]]= projects in
343 343
344=C-c C-c= on a source block asks whether to run it (yes, no, or always for this block), as on the Mac. 344=C-c C-c= on a source block asks whether to run it (yes, no, or always for this block), as on the Mac.
345 345
346On iOS, only Emacs Lisp and JavaScript blocks run. orgstar evaluates Emacs Lisp with its own interpreter, which covers a subset of the language, and JavaScript in JavaScriptCore, as =node= would run it, sessions included. Other results: 346On iOS, only Emacs Lisp, JavaScript, calc and sqlite blocks run. orgstar evaluates Emacs Lisp with its own interpreter, which covers a subset of the language, JavaScript in JavaScriptCore, as =node= would run it, sessions included, calc with its own Calc and sqlite with the SQLite library, as =sqlite3= would; see [[file:11-code-blocks.org][Code blocks]]. Other results:
347 347
348- A block in another language: "/language/ blocks need the Mac to run." 348- A block in another language: "/language/ blocks need the Mac to run."
349- Emacs Lisp the interpreter doesn't have: "This block uses Emacs Lisp that runs only in Emacs, on the Mac." 349- Emacs Lisp the interpreter doesn't have: "This block uses Emacs Lisp that runs only in Emacs, on the Mac."
350- JavaScript that uses something only node has, such as =Buffer=: "This block uses /name/, which runs only in node." 350- JavaScript that uses something only node has, such as =Buffer=: "This block uses /name/, which runs only in node."
351- A calc or sqlite block orgstar can't run as Emacs would: "This calc block can't be calculated here: /reason/." or "This sqlite block can't run here: /reason/."
351 352
352Table 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. 353Table 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.
353 354
@@ -444,7 +445,7 @@ Quick Look in the Files app shows org files as the HTML export renders them.
444 445
445* What the Mac has that iOS doesn't 446* What the Mac has that iOS doesn't
446 447
447- In the download version: running code blocks in languages other than Emacs Lisp and JavaScript, Emacs Lisp beyond orgstar's interpreter, JavaScript that needs node, and tables that need Emacs. 448- In the download version: running code blocks in languages other than Emacs Lisp, JavaScript, calc and sqlite, Emacs Lisp beyond orgstar's interpreter, JavaScript that needs node, and tables that need Emacs.
448- In the download version, LaTeX-made PDF export. 449- In the download version, LaTeX-made PDF export.
449- Idle detection from keyboard and mouse input; iOS uses the time away from the app instead. 450- Idle detection from keyboard and mouse input; iOS uses the time away from the app instead.
450- In the download version, attaching by hard link or symbolic link. 451- In the download version, attaching by hard link or symbolic link.
docs/manual/install.org +3 −3
@@ -16,8 +16,8 @@ There are two versions of the Mac app. Both edit the same files in the same way;
16differ in where they come from, how orgstar+ is bought, and what they can run. 16differ in where they come from, how orgstar+ is bought, and what they can run.
17 17
18- The Mac App Store version runs in the App Sandbox and starts no other programs. Emacs 18- The Mac App Store version runs in the App Sandbox and starts no other programs. Emacs
19 Lisp blocks run in orgstar's own interpreter and JavaScript blocks in JavaScriptCore, as on 19 Lisp blocks run in orgstar's own interpreter, JavaScript blocks in JavaScriptCore, and calc and
20 iOS; other languages, Emacs and gnuplot are not used. orgstar+ is an in-app purchase shared 20 sqlite blocks built in, as on iOS; other languages, Emacs and gnuplot are not used. orgstar+ is an in-app purchase shared
21 with the iPhone and iPad app. 21 with the iPhone and iPad app.
22- The download version, from Homebrew or files.krz.sh, is signed with a Developer ID and 22- The download version, from Homebrew or files.krz.sh, is signed with a Developer ID and
23 notarized. It runs code blocks with the programs installed on the Mac, hands some tables and 23 notarized. It runs code blocks with the programs installed on the Mac, hands some tables and
@@ -54,7 +54,7 @@ App Store version.
54 54
55| Feature | Mac App Store version | Download version | 55| Feature | Mac App Store version | Download version |
56|----------------------------+-------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------| 56|----------------------------+-------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------|
57| Code blocks | Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore | Every language installed; Emacs Lisp in Emacs and JavaScript in node, or built in without them | 57| Code blocks | Emacs Lisp, JavaScript, calc and sqlite, each built in | Every language installed; Emacs Lisp in Emacs and JavaScript in node, or built in without them |
58| Sessions, graphics | JavaScript sessions; no graphics | Yes | 58| Sessions, graphics | JavaScript sessions; no graphics | Yes |
59| Tangling | Yes | Yes | 59| Tangling | Yes | Yes |
60| Table formulas | Those orgstar computes itself | The rest in Emacs as well | 60| Table formulas | Those orgstar computes itself | The rest in Emacs as well |
l10n/Localizable.xcstrings +665
@@ -1743,6 +1743,111 @@
1743 "+work-home": { 1743 "+work-home": {
1744 "shouldTranslate": false 1744 "shouldTranslate": false
1745 }, 1745 },
1746 ".import into a table that doesn't exist yet": {
1747 "comment": "Why an sqlite block can't run here",
1748 "localizations": {
1749 "de": {
1750 "stringUnit": {
1751 "state": "translated",
1752 "value": ".import in eine Tabelle, die noch nicht existiert"
1753 }
1754 },
1755 "es": {
1756 "stringUnit": {
1757 "state": "translated",
1758 "value": ".import en una tabla que aún no existe"
1759 }
1760 },
1761 "fr": {
1762 "stringUnit": {
1763 "state": "translated",
1764 "value": ".import dans une table qui n’existe pas encore"
1765 }
1766 },
1767 "ja": {
1768 "stringUnit": {
1769 "state": "translated",
1770 "value": "まだ存在しないテーブルへの .import"
1771 }
1772 },
1773 "pt-BR": {
1774 "stringUnit": {
1775 "state": "translated",
1776 "value": ".import em uma tabela que ainda não existe"
1777 }
1778 }
1779 }
1780 },
1781 ".import of rows that don't fit the table": {
1782 "comment": "Why an sqlite block can't run here",
1783 "localizations": {
1784 "de": {
1785 "stringUnit": {
1786 "state": "translated",
1787 "value": ".import von Zeilen, die nicht zur Tabelle passen"
1788 }
1789 },
1790 "es": {
1791 "stringUnit": {
1792 "state": "translated",
1793 "value": ".import de filas que no encajan en la tabla"
1794 }
1795 },
1796 "fr": {
1797 "stringUnit": {
1798 "state": "translated",
1799 "value": ".import de lignes qui ne correspondent pas à la table"
1800 }
1801 },
1802 "ja": {
1803 "stringUnit": {
1804 "state": "translated",
1805 "value": "テーブルに合わない行の .import"
1806 }
1807 },
1808 "pt-BR": {
1809 "stringUnit": {
1810 "state": "translated",
1811 "value": ".import de linhas que não cabem na tabela"
1812 }
1813 }
1814 }
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 },
1746 "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.": {
1747 "localizations": { 1852 "localizations": {
1748 "de": { 1853 "de": {
@@ -4138,6 +4243,41 @@
4138 } 4243 }
4139 } 4244 }
4140 }, 4245 },
4246 "BLOB values": {
4247 "comment": "Why an sqlite block can't run here",
4248 "localizations": {
4249 "de": {
4250 "stringUnit": {
4251 "state": "translated",
4252 "value": "BLOB-Werte"
4253 }
4254 },
4255 "es": {
4256 "stringUnit": {
4257 "state": "translated",
4258 "value": "valores BLOB"
4259 }
4260 },
4261 "fr": {
4262 "stringUnit": {
4263 "state": "translated",
4264 "value": "valeurs BLOB"
4265 }
4266 },
4267 "ja": {
4268 "stringUnit": {
4269 "state": "translated",
4270 "value": "BLOB 値"
4271 }
4272 },
4273 "pt-BR": {
4274 "stringUnit": {
4275 "state": "translated",
4276 "value": "valores BLOB"
4277 }
4278 }
4279 }
4280 },
4141 "Back to today (.)": { 4281 "Back to today (.)": {
4142 "localizations": { 4282 "localizations": {
4143 "de": { 4283 "de": {
@@ -4859,6 +4999,41 @@
4859 } 4999 }
4860 } 5000 }
4861 }, 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 },
4862 "Calendar": { 5037 "Calendar": {
4863 "localizations": { 5038 "localizations": {
4864 "de": { 5039 "de": {
@@ -4997,6 +5172,41 @@
4997 } 5172 }
4998 } 5173 }
4999 }, 5174 },
5175 "Can't open the database %@: %@. orgstar can open files only in the folders it has access to.": {
5176 "comment": "An sqlite block's database that can't be opened",
5177 "localizations": {
5178 "de": {
5179 "stringUnit": {
5180 "state": "translated",
5181 "value": "Die Datenbank %1$@ kann nicht geöffnet werden: %2$@. orgstar kann Dateien nur in Ordnern öffnen, auf die es Zugriff hat."
5182 }
5183 },
5184 "es": {
5185 "stringUnit": {
5186 "state": "translated",
5187 "value": "No se puede abrir la base de datos %1$@: %2$@. orgstar solo puede abrir archivos en las carpetas a las que tiene acceso."
5188 }
5189 },
5190 "fr": {
5191 "stringUnit": {
5192 "state": "translated",
5193 "value": "Impossible d’ouvrir la base de données %1$@ : %2$@. orgstar ne peut ouvrir des fichiers que dans les dossiers auxquels il a accès."
5194 }
5195 },
5196 "ja": {
5197 "stringUnit": {
5198 "state": "translated",
5199 "value": "データベース %1$@ を開けません:%2$@。orgstar はアクセスできるフォルダ内のファイルしか開けません。"
5200 }
5201 },
5202 "pt-BR": {
5203 "stringUnit": {
5204 "state": "translated",
5205 "value": "Não é possível abrir o banco de dados %1$@: %2$@. O orgstar só pode abrir arquivos nas pastas às quais tem acesso."
5206 }
5207 }
5208 }
5209 },
5000 "Can't open the entry": { 5210 "Can't open the entry": {
5001 "localizations": { 5211 "localizations": {
5002 "de": { 5212 "de": {
@@ -10275,6 +10485,41 @@
10275 } 10485 }
10276 } 10486 }
10277 }, 10487 },
10488 "EXPLAIN statements": {
10489 "comment": "Why an sqlite block can't run here",
10490 "localizations": {
10491 "de": {
10492 "stringUnit": {
10493 "state": "translated",
10494 "value": "EXPLAIN-Anweisungen"
10495 }
10496 },
10497 "es": {
10498 "stringUnit": {
10499 "state": "translated",
10500 "value": "sentencias EXPLAIN"
10501 }
10502 },
10503 "fr": {
10504 "stringUnit": {
10505 "state": "translated",
10506 "value": "instructions EXPLAIN"
10507 }
10508 },
10509 "ja": {
10510 "stringUnit": {
10511 "state": "translated",
10512 "value": "EXPLAIN 文"
10513 }
10514 },
10515 "pt-BR": {
10516 "stringUnit": {
10517 "state": "translated",
10518 "value": "instruções EXPLAIN"
10519 }
10520 }
10521 }
10522 },
10278 "Earlier": { 10523 "Earlier": {
10279 "localizations": { 10524 "localizations": {
10280 "de": { 10525 "de": {
@@ -31215,6 +31460,41 @@
31215 } 31460 }
31216 } 31461 }
31217 }, 31462 },
31463 "This calc block can't be calculated here: %@.": {
31464 "comment": "A calc block orgstar can't calculate",
31465 "localizations": {
31466 "de": {
31467 "stringUnit": {
31468 "state": "translated",
31469 "value": "Dieser calc-Block kann hier nicht berechnet werden: %@."
31470 }
31471 },
31472 "es": {
31473 "stringUnit": {
31474 "state": "translated",
31475 "value": "Este bloque calc no se puede calcular aquí: %@."
31476 }
31477 },
31478 "fr": {
31479 "stringUnit": {
31480 "state": "translated",
31481 "value": "Ce bloc calc ne peut pas être calculé ici : %@."
31482 }
31483 },
31484 "ja": {
31485 "stringUnit": {
31486 "state": "translated",
31487 "value": "この calc ブロックはここでは計算できません:%@。"
31488 }
31489 },
31490 "pt-BR": {
31491 "stringUnit": {
31492 "state": "translated",
31493 "value": "Este bloco calc não pode ser calculado aqui: %@."
31494 }
31495 }
31496 }
31497 },
31218 "This file isn't in one of your folders. Choose where the export goes.": { 31498 "This file isn't in one of your folders. Choose where the export goes.": {
31219 "comment": "Save panel for an export outside the sidebar's folders", 31499 "comment": "Save panel for an export outside the sidebar's folders",
31220 "localizations": { 31500 "localizations": {
@@ -31250,6 +31530,76 @@
31250 } 31530 }
31251 } 31531 }
31252 }, 31532 },
31533 "This sqlite block can't run here: %@.": {
31534 "comment": "An sqlite block refused before it ran",
31535 "localizations": {
31536 "de": {
31537 "stringUnit": {
31538 "state": "translated",
31539 "value": "Dieser sqlite-Block kann hier nicht ausgeführt werden: %@."
31540 }
31541 },
31542 "es": {
31543 "stringUnit": {
31544 "state": "translated",
31545 "value": "Este bloque sqlite no se puede ejecutar aquí: %@."
31546 }
31547 },
31548 "fr": {
31549 "stringUnit": {
31550 "state": "translated",
31551 "value": "Ce bloc sqlite ne peut pas être exécuté ici : %@."
31552 }
31553 },
31554 "ja": {
31555 "stringUnit": {
31556 "state": "translated",
31557 "value": "この sqlite ブロックはここでは実行できません:%@。"
31558 }
31559 },
31560 "pt-BR": {
31561 "stringUnit": {
31562 "state": "translated",
31563 "value": "Este bloco sqlite não pode ser executado aqui: %@."
31564 }
31565 }
31566 }
31567 },
31568 "This sqlite block can't run here: %@. The statements before it ran.": {
31569 "comment": "An sqlite block refused partway",
31570 "localizations": {
31571 "de": {
31572 "stringUnit": {
31573 "state": "translated",
31574 "value": "Dieser sqlite-Block kann hier nicht ausgeführt werden: %@. Die Anweisungen davor wurden ausgeführt."
31575 }
31576 },
31577 "es": {
31578 "stringUnit": {
31579 "state": "translated",
31580 "value": "Este bloque sqlite no se puede ejecutar aquí: %@. Las sentencias anteriores se ejecutaron."
31581 }
31582 },
31583 "fr": {
31584 "stringUnit": {
31585 "state": "translated",
31586 "value": "Ce bloc sqlite ne peut pas être exécuté ici : %@. Les instructions précédentes ont été exécutées."
31587 }
31588 },
31589 "ja": {
31590 "stringUnit": {
31591 "state": "translated",
31592 "value": "この sqlite ブロックはここでは実行できません:%@。それより前の文は実行されました。"
31593 }
31594 },
31595 "pt-BR": {
31596 "stringUnit": {
31597 "state": "translated",
31598 "value": "Este bloco sqlite não pode ser executado aqui: %@. As instruções anteriores foram executadas."
31599 }
31600 }
31601 }
31602 },
31253 "This table needs Emacs, which runs on the Mac: %@.": { 31603 "This table needs Emacs, which runs on the Mac: %@.": {
31254 "comment": "Table formulas only Emacs can calculate", 31604 "comment": "Table formulas only Emacs can calculate",
31255 "localizations": { 31605 "localizations": {
@@ -34497,6 +34847,41 @@
34497 } 34847 }
34498 } 34848 }
34499 }, 34849 },
34850 "control characters in values": {
34851 "comment": "Why an sqlite block can't run here",
34852 "localizations": {
34853 "de": {
34854 "stringUnit": {
34855 "state": "translated",
34856 "value": "Steuerzeichen in Werten"
34857 }
34858 },
34859 "es": {
34860 "stringUnit": {
34861 "state": "translated",
34862 "value": "caracteres de control en valores"
34863 }
34864 },
34865 "fr": {
34866 "stringUnit": {
34867 "state": "translated",
34868 "value": "caractères de contrôle dans les valeurs"
34869 }
34870 },
34871 "ja": {
34872 "stringUnit": {
34873 "state": "translated",
34874 "value": "値に含まれる制御文字"
34875 }
34876 },
34877 "pt-BR": {
34878 "stringUnit": {
34879 "state": "translated",
34880 "value": "caracteres de controle em valores"
34881 }
34882 }
34883 }
34884 },
34500 "date %@": { 34885 "date %@": {
34501 "localizations": { 34886 "localizations": {
34502 "de": { 34887 "de": {
@@ -34668,6 +35053,41 @@
34668 } 35053 }
34669 } 35054 }
34670 }, 35055 },
35056 "dates in calc blocks": {
35057 "comment": "Why a table needs Emacs",
35058 "localizations": {
35059 "de": {
35060 "stringUnit": {
35061 "state": "translated",
35062 "value": "Datumsangaben in calc-Blöcken"
35063 }
35064 },
35065 "es": {
35066 "stringUnit": {
35067 "state": "translated",
35068 "value": "fechas en bloques calc"
35069 }
35070 },
35071 "fr": {
35072 "stringUnit": {
35073 "state": "translated",
35074 "value": "dates dans les blocs calc"
35075 }
35076 },
35077 "ja": {
35078 "stringUnit": {
35079 "state": "translated",
35080 "value": "calc ブロック内の日付"
35081 }
35082 },
35083 "pt-BR": {
35084 "stringUnit": {
35085 "state": "translated",
35086 "value": "datas em blocos calc"
35087 }
35088 }
35089 }
35090 },
34671 "daylight saving time": { 35091 "daylight saving time": {
34672 "localizations": { 35092 "localizations": {
34673 "de": { 35093 "de": {
@@ -35112,6 +35532,41 @@
35112 } 35532 }
35113 } 35533 }
35114 }, 35534 },
35535 "header arguments with shell syntax": {
35536 "comment": "Why an sqlite block can't run here",
35537 "localizations": {
35538 "de": {
35539 "stringUnit": {
35540 "state": "translated",
35541 "value": "Header-Argumente mit Shell-Syntax"
35542 }
35543 },
35544 "es": {
35545 "stringUnit": {
35546 "state": "translated",
35547 "value": "argumentos de cabecera con sintaxis de shell"
35548 }
35549 },
35550 "fr": {
35551 "stringUnit": {
35552 "state": "translated",
35553 "value": "arguments d’en-tête avec une syntaxe de shell"
35554 }
35555 },
35556 "ja": {
35557 "stringUnit": {
35558 "state": "translated",
35559 "value": "シェル構文を含むヘッダー引数"
35560 }
35561 },
35562 "pt-BR": {
35563 "stringUnit": {
35564 "state": "translated",
35565 "value": "argumentos de cabeçalho com sintaxe de shell"
35566 }
35567 }
35568 }
35569 },
35115 "infinite result": { 35570 "infinite result": {
35116 "localizations": { 35571 "localizations": {
35117 "de": { 35572 "de": {
@@ -35626,6 +36081,41 @@
35626 } 36081 }
35627 } 36082 }
35628 }, 36083 },
36084 "numeric :prologue or :epilogue": {
36085 "comment": "Why a table needs Emacs",
36086 "localizations": {
36087 "de": {
36088 "stringUnit": {
36089 "state": "translated",
36090 "value": "numerischer :prologue oder :epilogue"
36091 }
36092 },
36093 "es": {
36094 "stringUnit": {
36095 "state": "translated",
36096 "value": ":prologue o :epilogue numérico"
36097 }
36098 },
36099 "fr": {
36100 "stringUnit": {
36101 "state": "translated",
36102 "value": ":prologue ou :epilogue numérique"
36103 }
36104 },
36105 "ja": {
36106 "stringUnit": {
36107 "state": "translated",
36108 "value": "数値の :prologue または :epilogue"
36109 }
36110 },
36111 "pt-BR": {
36112 "stringUnit": {
36113 "state": "translated",
36114 "value": ":prologue ou :epilogue numérico"
36115 }
36116 }
36117 }
36118 },
35629 "open": { 36119 "open": {
35630 "localizations": { 36120 "localizations": {
35631 "de": { 36121 "de": {
@@ -36660,6 +37150,41 @@
36660 } 37150 }
36661 } 37151 }
36662 }, 37152 },
37153 "stack command %@": {
37154 "comment": "Why a calc block needs Emacs: a key it runs on the stack",
37155 "localizations": {
37156 "de": {
37157 "stringUnit": {
37158 "state": "translated",
37159 "value": "Stapelbefehl %@"
37160 }
37161 },
37162 "es": {
37163 "stringUnit": {
37164 "state": "translated",
37165 "value": "orden de pila %@"
37166 }
37167 },
37168 "fr": {
37169 "stringUnit": {
37170 "state": "translated",
37171 "value": "commande de pile %@"
37172 }
37173 },
37174 "ja": {
37175 "stringUnit": {
37176 "state": "translated",
37177 "value": "スタックコマンド %@"
37178 }
37179 },
37180 "pt-BR": {
37181 "stringUnit": {
37182 "state": "translated",
37183 "value": "comando de pilha %@"
37184 }
37185 }
37186 }
37187 },
36663 "string-width of %@": { 37188 "string-width of %@": {
36664 "localizations": { 37189 "localizations": {
36665 "de": { 37190 "de": {
@@ -36796,6 +37321,76 @@
36796 } 37321 }
36797 } 37322 }
36798 }, 37323 },
37324 "text other than plain ASCII in column or line mode": {
37325 "comment": "Why an sqlite block can't run here",
37326 "localizations": {
37327 "de": {
37328 "stringUnit": {
37329 "state": "translated",
37330 "value": "Text außer reinem ASCII im column- oder line-Modus"
37331 }
37332 },
37333 "es": {
37334 "stringUnit": {
37335 "state": "translated",
37336 "value": "texto que no es ASCII simple en el modo column o line"
37337 }
37338 },
37339 "fr": {
37340 "stringUnit": {
37341 "state": "translated",
37342 "value": "texte autre que de l’ASCII simple en mode column ou line"
37343 }
37344 },
37345 "ja": {
37346 "stringUnit": {
37347 "state": "translated",
37348 "value": "column または line モードでの ASCII 以外のテキスト"
37349 }
37350 },
37351 "pt-BR": {
37352 "stringUnit": {
37353 "state": "translated",
37354 "value": "texto que não é ASCII simples no modo column ou line"
37355 }
37356 }
37357 }
37358 },
37359 "text that isn't UTF-8": {
37360 "comment": "Why an sqlite block can't run here",
37361 "localizations": {
37362 "de": {
37363 "stringUnit": {
37364 "state": "translated",
37365 "value": "Text, der nicht UTF-8 ist"
37366 }
37367 },
37368 "es": {
37369 "stringUnit": {
37370 "state": "translated",
37371 "value": "texto que no es UTF-8"
37372 }
37373 },
37374 "fr": {
37375 "stringUnit": {
37376 "state": "translated",
37377 "value": "texte qui n’est pas en UTF-8"
37378 }
37379 },
37380 "ja": {
37381 "stringUnit": {
37382 "state": "translated",
37383 "value": "UTF-8 ではないテキスト"
37384 }
37385 },
37386 "pt-BR": {
37387 "stringUnit": {
37388 "state": "translated",
37389 "value": "texto que não é UTF-8"
37390 }
37391 }
37392 }
37393 },
36799 "the data of this error": { 37394 "the data of this error": {
36800 "localizations": { 37395 "localizations": {
36801 "de": { 37396 "de": {
@@ -36830,6 +37425,41 @@
36830 } 37425 }
36831 } 37426 }
36832 }, 37427 },
37428 "the dot-command %@": {
37429 "comment": "Why an sqlite block can't run here",
37430 "localizations": {
37431 "de": {
37432 "stringUnit": {
37433 "state": "translated",
37434 "value": "der Punktbefehl %@"
37435 }
37436 },
37437 "es": {
37438 "stringUnit": {
37439 "state": "translated",
37440 "value": "la orden de punto %@"
37441 }
37442 },
37443 "fr": {
37444 "stringUnit": {
37445 "state": "translated",
37446 "value": "la commande point %@"
37447 }
37448 },
37449 "ja": {
37450 "stringUnit": {
37451 "state": "translated",
37452 "value": "ドットコマンド %@"
37453 }
37454 },
37455 "pt-BR": {
37456 "stringUnit": {
37457 "state": "translated",
37458 "value": "o comando de ponto %@"
37459 }
37460 }
37461 }
37462 },
36833 "time string %@": { 37463 "time string %@": {
36834 "localizations": { 37464 "localizations": {
36835 "de": { 37465 "de": {
@@ -36933,6 +37563,41 @@
36933 } 37563 }
36934 } 37564 }
36935 }, 37565 },
37566 "value of :var %@": {
37567 "comment": "Why a calc block needs Emacs: a variable's value",
37568 "localizations": {
37569 "de": {
37570 "stringUnit": {
37571 "state": "translated",
37572 "value": "Wert von :var %@"
37573 }
37574 },
37575 "es": {
37576 "stringUnit": {
37577 "state": "translated",
37578 "value": "valor de :var %@"
37579 }
37580 },
37581 "fr": {
37582 "stringUnit": {
37583 "state": "translated",
37584 "value": "valeur de :var %@"
37585 }
37586 },
37587 "ja": {
37588 "stringUnit": {
37589 "state": "translated",
37590 "value": ":var %@ の値"
37591 }
37592 },
37593 "pt-BR": {
37594 "stringUnit": {
37595 "state": "translated",
37596 "value": "valor de :var %@"
37597 }
37598 }
37599 }
37600 },
36936 "value< on %@ and %@": { 37601 "value< on %@ and %@": {
36937 "localizations": { 37602 "localizations": {
36938 "de": { 37603 "de": {