Commit ed56474574
Verified · cmc
Layout: unified · split
Sources/OrgApp/JavaScriptBlocks.swift +7
| @@ -36,6 +36,13 @@ public enum JavaScriptBlocks { | ||
| 36 | 36 | } |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | /// Runs a js `job` without a session on the calling thread, as `org-sbe` in a table | |
| 40 | /// formula needs; nil for other jobs. | |
| 41 | public static func runHere(_ job: BabelJob) throws -> BabelOutput? { | |
| 42 | guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil } | |
| 43 | return try Engine().main(job.input, run: Run()) | |
| 44 | } | |
| 45 | ||
| 39 | 46 | struct Stopped: Error, CustomStringConvertible { |
| 40 | 47 | let description: String |
| 41 | 48 | } |
Sources/OrgApp/WorkspaceModel.swift +4
| @@ -64,6 +64,10 @@ public final class WorkspaceModel { | ||
| 64 | 64 | guard let path = (try? index.headings(withID: id))?.first?.path else { return nil } |
| 65 | 65 | return FileManager.default.contents(atPath: path).map { SourceText(bytes: [UInt8]($0)).text } |
| 66 | 66 | } |
| 67 | #if canImport(JavaScriptCore) | |
| 68 | // `org-sbe` in table formulas runs js blocks in JavaScriptCore. | |
| 69 | TableBlocks.javaScript = JavaScriptBlocks.runHere | |
| 70 | #endif | |
| 67 | 71 | } |
| 68 | 72 | |
| 69 | 73 | /// `~/Library/Application Support/Orgstar`, or `ORGSTAR_DATA_DIR` when set (for development). |
Sources/OrgCore/Compute/TableFormulas.swift +1
| @@ -652,6 +652,7 @@ extension EmacsBuffer { | ||
| 652 | 652 | let lisp = Elisp() |
| 653 | 653 | lisp.standardTime() |
| 654 | 654 | Self.defineLookups(lisp) |
| 655 | Babel.defineSbe(lisp) { [unowned self] in text as String } | |
| 655 | 656 | let value: Sexp |
| 656 | 657 | do { |
| 657 | 658 | value = try lisp.eval(try lisp.eval(try LispReader.readFirst(form).sexp)) |
Sources/OrgCore/Compute/TableSbe.swift added +216
| @@ -0,0 +1,216 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | // `org-sbe` (ob-table.el, Org 9.8.7) in Lisp table formulas. The named block runs in `Elisp`, | |
| 4 | // or for js through `TableBlocks.javaScript`, and named tables and lists are read from the | |
| 5 | // file. Other languages, and references this can't follow, throw `Elisp.Unsupported`, so the | |
| 6 | // table goes to Emacs. | |
| 7 | ||
| 8 | /// How `org-sbe` runs js blocks. | |
| 9 | public enum TableBlocks { | |
| 10 | /// Runs a js job to the end on the calling thread; nil when it can't. The app sets it. | |
| 11 | nonisolated(unsafe) public static var javaScript: ((BabelJob) throws -> BabelOutput?)? | |
| 12 | } | |
| 13 | ||
| 14 | extension Babel { | |
| 15 | /// Defines `org-sbe` for formulas in the file whose text `text` gives. | |
| 16 | static func defineSbe(_ lisp: Elisp, text: @escaping () -> String) { | |
| 17 | lisp.defineForm("org-sbe") { _, args in .string(try sbe(args, text: text())) } | |
| 18 | } | |
| 19 | ||
| 20 | /// The macro's value: `(org-trim (format "%S" result))`, or the result when it is a string. | |
| 21 | static func sbe(_ args: [Sexp], text: String) throws -> String { | |
| 22 | guard let first = args.first else { throw Elisp.Signal(message: "Wrong number of arguments: org-sbe, 0") } | |
| 23 | let name: String | |
| 24 | switch first { | |
| 25 | case .string(let s): name = s | |
| 26 | case .symbol(let s): name = s | |
| 27 | default: throw Elisp.Unsupported(what: "org-sbe with a block name that isn't a symbol") | |
| 28 | } | |
| 29 | var variables = Array(args.dropFirst()) | |
| 30 | var header = "" | |
| 31 | if case .string(let s)? = variables.first { | |
| 32 | header = s | |
| 33 | variables.removeFirst() | |
| 34 | } | |
| 35 | var specs: [String] = [] | |
| 36 | for variable in variables { | |
| 37 | guard case .list(let items) = variable, case .symbol(let variableName)? = items.first else { | |
| 38 | throw Elisp.Unsupported(what: "org-sbe with an argument that isn't (NAME VALUE)") | |
| 39 | } | |
| 40 | // A value after `$` is written as Lisp, so a string stays a string. | |
| 41 | var quote = false | |
| 42 | var values: [Sexp] = [] | |
| 43 | for item in items.dropFirst() { | |
| 44 | if item == .symbol("$") { | |
| 45 | quote = true | |
| 46 | continue | |
| 47 | } | |
| 48 | if quote { | |
| 49 | values.append(.string(Elisp.printed(item, escape: true))) | |
| 50 | } else if !Elisp.isNil(item) { | |
| 51 | values.append(item) | |
| 52 | } | |
| 53 | quote = false | |
| 54 | } | |
| 55 | if values.count > 1 { | |
| 56 | let read = try values.map { value -> Sexp in | |
| 57 | guard case .string(let s) = value else { throw Elisp.Unsupported(what: "org-sbe with values that aren't text") } | |
| 58 | do { return try LispReader.readFirst(s).sexp } catch { throw Elisp.Signal(message: "End of file during parsing") } | |
| 59 | } | |
| 60 | specs.append(variableName + "='" + Elisp.printed(.list(read), escape: true)) | |
| 61 | } else { | |
| 62 | specs.append(variableName + "=" + (try Elisp.format([.string("%s"), values.first ?? .nil]))) | |
| 63 | } | |
| 64 | } | |
| 65 | guard !name.isEmpty else { return "" } | |
| 66 | guard !name.contains(where: { "[]():\"".contains($0) }) else { throw Elisp.Unsupported(what: "org-sbe with the reference \(name)") } | |
| 67 | var value = try sbeReference(name, header: header, arguments: splitArguments(specs.joined(separator: ", ")), text: text) | |
| 68 | // `org-babel-ref-resolve` gives a symbol's name. | |
| 69 | if case .symbol(let s) = value, !Elisp.isNil(value) { value = .string(s) } | |
| 70 | // `:var results=` takes off a first row followed by a rule, as column names. | |
| 71 | if case .list(let rows) = value, rows.count > 1, rows[0] != .symbol("hline"), rows[1] == .symbol("hline"), | |
| 72 | !rows.dropFirst(2).contains(.symbol("hline")) { | |
| 73 | value = rows.count > 2 ? .list(Array(rows.dropFirst(2))) : .nil | |
| 74 | } | |
| 75 | let printed = value.string ?? Elisp.printed(value, escape: true) | |
| 76 | return printed.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | |
| 77 | } | |
| 78 | ||
| 79 | /// `org-babel-ref-resolve` for `name[header](arguments)`: a src block's value, or a named | |
| 80 | /// table or list. | |
| 81 | static func sbeReference(_ name: String, header: String, arguments: [String], text: String) throws -> Sexp { | |
| 82 | let ns = text as NSString | |
| 83 | let model = DocumentModel(tree: OrgParser.parse(text)) | |
| 84 | let options = Options() | |
| 85 | // The first `#+NAME:` line with the name: a src block's, or another element's. | |
| 86 | let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$" | |
| 87 | guard let named = text.range(of: pattern, options: .regularExpression) else { throw notFound(name, text: text) } | |
| 88 | let start = NSRange(named, in: text).location | |
| 89 | let block = model.srcBlocks.first { block in | |
| 90 | guard block.name == name, block.range.lowerBound > start else { return false } | |
| 91 | let between = ns.substring(with: NSRange(location: start, length: block.range.lowerBound - start)) | |
| 92 | return between.split(separator: "\n").allSatisfy { $0.trimmingCharacters(in: .whitespaces).hasPrefix("#+") } | |
| 93 | } | |
| 94 | guard let block else { | |
| 95 | do { | |
| 96 | return try sbeSexp(resolve(name, model: model, text: ns, refs: References(resolved: [:], options: options))) | |
| 97 | } catch let failure as Failure { | |
| 98 | throw sbeError(failure, text: text) | |
| 99 | } | |
| 100 | } | |
| 101 | let params: Params | |
| 102 | do { | |
| 103 | params = try Params(block: block, model: model, text: ns, extra: [Params.parse(header) + arguments.map { (":var", $0) }]) | |
| 104 | } catch let failure as Failure { | |
| 105 | throw sbeError(failure, text: text) | |
| 106 | } | |
| 107 | if params.single[":cache"] == "yes" { throw Elisp.Unsupported(what: "org-sbe with :cache") } | |
| 108 | var refs = References(resolved: [:], options: options) | |
| 109 | refs.visiting = [name] | |
| 110 | // The blocks its `:var`s refer to run first, as `DocumentSession.runBabel` runs them. | |
| 111 | while true { | |
| 112 | switch plan(block, params: params, model: model, text: ns, options: options, location: block.range, name: name, refs: refs, useCache: false) { | |
| 113 | case .failure(let failure): | |
| 114 | throw sbeError(failure, text: text) | |
| 115 | case .success(let job): | |
| 116 | if job.needsFile { throw Elisp.Unsupported(what: "org-sbe with Lisp that needs the file's name") } | |
| 117 | if let need = job.needs.first { | |
| 118 | refs.resolved[need.reference] = varValue(need.job.finish, try sbeRun(need.job)) | |
| 119 | continue | |
| 120 | } | |
| 121 | return try sbeValue(job, lexical: params.single[":lexical"] == "yes") | |
| 122 | } | |
| 123 | } | |
| 124 | } | |
| 125 | ||
| 126 | /// A block a reference needs, run as `Babel.evaluateNatively` or in JavaScriptCore. | |
| 127 | static func sbeRun(_ job: BabelJob) throws -> BabelOutput { | |
| 128 | if job.lispForm != nil { | |
| 129 | do { | |
| 130 | guard let output = try evaluateNatively(job) else { throw Elisp.Unsupported(what: "org-sbe with Lisp only Emacs runs") } | |
| 131 | return output | |
| 132 | } catch let Failure.message(message) { | |
| 133 | // An error in the block. | |
| 134 | throw Elisp.Signal(message: message) | |
| 135 | } | |
| 136 | } | |
| 137 | guard job.language == "js" || job.language == "javascript" else { throw Elisp.Unsupported(what: "org-sbe with \(job.language) blocks") } | |
| 138 | guard let output = try? TableBlocks.javaScript?(job), output.status == 0 else { throw Elisp.Unsupported(what: "org-sbe with js blocks") } | |
| 139 | return output | |
| 140 | } | |
| 141 | ||
| 142 | /// The block's value as `org-babel-execute-src-block` returns it. | |
| 143 | static func sbeValue(_ job: BabelJob, lexical: Bool) throws -> Sexp { | |
| 144 | let params = job.finish.params | |
| 145 | if params.contains("file") || job.finish.colnames != nil || job.finish.rownames != nil { | |
| 146 | throw Elisp.Unsupported(what: "org-sbe with this block's results") | |
| 147 | } | |
| 148 | let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code") | |
| 149 | || params.contains("pp") || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table")) | |
| 150 | var result: Sexp | |
| 151 | if let form = job.lispForm { | |
| 152 | // `org-babel-execute:emacs-lisp`: dynamic binding unless `:lexical yes`. | |
| 153 | let lisp = Elisp() | |
| 154 | lisp.lexical = lexical | |
| 155 | lisp.syntax = .emacsLisp | |
| 156 | lisp.standardTime() | |
| 157 | result = try lisp.eval(try LispReader.readFirst(form).sexp) | |
| 158 | if Elisp.containsClosure(result) { throw Elisp.Unsupported(what: "org-sbe with a closure") } | |
| 159 | if scalar { | |
| 160 | result = .string(params.contains("scalar") || params.contains("verbatim") ? Elisp.printed(result, escape: true) : try Elisp.format([.string("%s"), result])) | |
| 161 | } | |
| 162 | } else { | |
| 163 | // `org-babel-js-read`: a number, a string, or the symbol a quoted word reads as. | |
| 164 | let raw = rawResult(job.finish, try sbeRun(job)) | |
| 165 | if scalar { | |
| 166 | result = .string(raw) | |
| 167 | } else if raw.hasPrefix("(") || raw.hasPrefix("[") || raw.hasPrefix("`") || raw.contains("\\") { | |
| 168 | throw Elisp.Unsupported(what: "org-sbe with this js value") | |
| 169 | } else if raw.hasPrefix("'") { | |
| 170 | guard let m = raw.firstMatch(of: /^'([A-Za-z0-9_-]+)(?:'|\s)/) else { throw Elisp.Unsupported(what: "org-sbe with this js value") } | |
| 171 | result = try number(String(m.1)).map { try LispReader.readFirst($0).sexp } ?? .symbol(String(m.1)) | |
| 172 | } else if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 { | |
| 173 | result = .string(String(raw.dropFirst().dropLast())) | |
| 174 | } else { | |
| 175 | result = try number(raw).map { try LispReader.readFirst($0).sexp } ?? .string(raw) | |
| 176 | } | |
| 177 | } | |
| 178 | if params.contains("discard") { return .nil } | |
| 179 | if !job.finish.output, params.contains("vector") || params.contains("table") { | |
| 180 | if case .list = result {} else if !Elisp.isNil(result) { result = .list([.list([result])]) } | |
| 181 | } | |
| 182 | return result | |
| 183 | } | |
| 184 | ||
| 185 | /// A named table or list as `org-babel-read-element` reads it. | |
| 186 | static func sbeSexp(_ value: VarValue) throws -> Sexp { | |
| 187 | func cell(_ c: Cell) throws -> Sexp { | |
| 188 | switch c { | |
| 189 | case .text(let s): return .string(s) | |
| 190 | case .number(let n): return try LispReader.readFirst(n).sexp | |
| 191 | } | |
| 192 | } | |
| 193 | switch value { | |
| 194 | case .scalar(let s): return .string(s) | |
| 195 | case .number(let n): return try LispReader.readFirst(n).sexp | |
| 196 | case .list(let items): return .list(try items.map(cell)) | |
| 197 | case .table(let rows): return .list(try rows.map { row in try row.map { .list(try $0.map(cell)) } ?? .symbol("hline") }) | |
| 198 | } | |
| 199 | } | |
| 200 | ||
| 201 | /// A reference to nothing is an error; to an ID, which only Emacs looks up, unsupported. | |
| 202 | static func notFound(_ name: String, text: String) -> Error { | |
| 203 | let pattern = "(?im)^[ \\t]*:(custom_)?id:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$" | |
| 204 | if text.range(of: pattern, options: .regularExpression) != nil { return Elisp.Unsupported(what: "org-sbe with an ID reference") } | |
| 205 | return Elisp.Signal(message: "Reference ‘\(name)’ not found in this buffer") | |
| 206 | } | |
| 207 | ||
| 208 | /// What a planning failure is in Emacs: a reference to nothing is an error, the rest | |
| 209 | /// unsupported here. | |
| 210 | static func sbeError(_ failure: Failure, text: String) -> Error { | |
| 211 | guard case .message(let message) = failure, let m = message.firstMatch(of: /^Can't find (.+) for :var\.$/) else { | |
| 212 | return Elisp.Unsupported(what: "org-sbe with a block orgstar can't run") | |
| 213 | } | |
| 214 | return notFound(String(m.1), text: text) | |
| 215 | } | |
| 216 | } | |
Sources/OrgCore/Config/Elisp.swift +6
| @@ -68,6 +68,8 @@ public final class Elisp { | ||
| 68 | 68 | didSet { regexes = [:] } |
| 69 | 69 | } |
| 70 | 70 | private var functions: [String: Builtin] = [:] |
| 71 | /// Forms the host defines, given their arguments unevaluated. | |
| 72 | private var forms: [String: Builtin] = [:] | |
| 71 | 73 | var steps = 0 |
| 72 | 74 | static let stepLimit = 1_000_000 |
| 73 | 75 | /// Nested evaluations, as `max-lisp-eval-depth` limits them. |
| @@ -95,6 +97,9 @@ public final class Elisp { | ||
| 95 | 97 | /// Defines or replaces a function. |
| 96 | 98 | public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function } |
| 97 | 99 | |
| 100 | /// Defines a macro by its value: `form` gets the arguments unevaluated. | |
| 101 | public func defineForm(_ name: String, _ form: @escaping Builtin) { forms[name] = form } | |
| 102 | ||
| 98 | 103 | /// Sets a global variable, which is special. |
| 99 | 104 | public func set(_ name: String, _ value: Sexp) { |
| 100 | 105 | scopes[0].vars[name] = value |
| @@ -375,6 +380,7 @@ public final class Elisp { | ||
| 375 | 380 | } |
| 376 | 381 | let args = Array(items.dropFirst()) |
| 377 | 382 | if let value = try special(name, args) { return value } |
| 383 | if let form = forms[name] { return try form(self, args) } | |
| 378 | 384 | // The function first, so an unknown one, or a macro this evaluator lacks, is |
| 379 | 385 | // unsupported rather than an error from its arguments. |
| 380 | 386 | guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } |
Sources/OrgPrograms/EmacsRunner.swift +7
| @@ -36,11 +36,18 @@ public enum EmacsRunner { | ||
| 36 | 36 | let script = folder.appendingPathComponent("recalc.el") |
| 37 | 37 | try text.write(to: input, atomically: true, encoding: .utf8) |
| 38 | 38 | func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" } |
| 39 | // `org-sbe` runs blocks: the user agreed to the table's Lisp, and Babel needs the languages. | |
| 40 | let blocks = text.contains("org-sbe") ? """ | |
| 41 | (setq org-confirm-babel-evaluate nil) | |
| 42 | (dolist (language '(C awk clojure java js python R ruby shell)) | |
| 43 | (require (intern (format "ob-%s" language)) nil t)) | |
| 44 | """ : "" | |
| 39 | 45 | try """ |
| 40 | 46 | ;;; -*- lexical-binding: t -*- |
| 41 | 47 | (require 'org) |
| 42 | 48 | (require 'org-table) |
| 43 | 49 | (setq enable-local-variables :safe) |
| 50 | \(blocks) | |
| 44 | 51 | (with-temp-buffer |
| 45 | 52 | (let ((coding-system-for-read 'utf-8-unix)) |
| 46 | 53 | (insert-file-contents \(lisp(input.path)))) |
Tests/OrgAppTests/JavaScriptBlocksTests.swift +54
| @@ -266,4 +266,58 @@ struct JavaScriptBlocksTests { | ||
| 266 | 266 | let interval = try Self.plan("#+begin_src js :results output\nsetInterval(() => {}, 10)\n#+end_src\n") |
| 267 | 267 | await #expect(throws: JavaScriptBlocks.Stopped.self) { try await JavaScriptBlocks.run(interval, directory: folder, timeout: .milliseconds(100)) } |
| 268 | 268 | } |
| 269 | ||
| 270 | /// `org-sbe` on js blocks in a table formula, as Emacs runs them with node. | |
| 271 | @Test(.enabled(if: oracle && nodeInstalled)) | |
| 272 | func tableFormulasMatchEmacs() throws { | |
| 273 | TableBlocks.javaScript = JavaScriptBlocks.runHere | |
| 274 | let text = """ | |
| 275 | #+NAME: sq | |
| 276 | #+begin_src js :var n=2 | |
| 277 | return n*n | |
| 278 | #+end_src | |
| 279 | ||
| 280 | #+NAME: hi | |
| 281 | #+begin_src js :var who="x" | |
| 282 | return 'hi ' + who | |
| 283 | #+end_src | |
| 284 | ||
| 285 | #+NAME: quote | |
| 286 | #+begin_src js :var who="x" | |
| 287 | return who + "'s" | |
| 288 | #+end_src | |
| 289 | ||
| 290 | #+NAME: out | |
| 291 | #+begin_src js :results output :var n=1 | |
| 292 | console.log(' n is', n) | |
| 293 | #+end_src | |
| 294 | ||
| 295 | #+NAME: obj | |
| 296 | #+begin_src js | |
| 297 | return {a: 1} | |
| 298 | #+end_src | |
| 299 | ||
| 300 | | n | sq | hi | hi$ | quote | out | obj | | |
| 301 | |---+----+----+-----+-------+-----+-----| | |
| 302 | | 3 | | | | | | | | |
| 303 | | abc | | | | | | | | |
| 304 | | 2.5 | | | | | | | | |
| 305 | #+TBLFM: $2='(org-sbe sq (n $1))::$3='(org-sbe hi (who $1))::$4='(org-sbe hi (who $$1))::$5='(org-sbe quote (who $$1))::$6='(org-sbe out (n $1))::$7='(org-sbe obj) | |
| 306 | ||
| 307 | """ | |
| 308 | let caret = (text as NSString).range(of: "#+TBLFM").location + 3 | |
| 309 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) | |
| 310 | guard case .commit(let result) = TableRecalculate(all: true).run(in: context) else { | |
| 311 | Issue.record("not calculated: \(TableRecalculate(all: true).run(in: context))") | |
| 312 | return | |
| 313 | } | |
| 314 | let ours = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) } | |
| 315 | let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" | |
| 316 | let emacs = try DailiesTests.emacs(""" | |
| 317 | (progn (require 'org) (require 'ob-js) | |
| 318 | (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node") | |
| 319 | (with-temp-buffer (insert \(quoted)) (org-mode) (goto-char \(caret + 1)) (org-ctrl-c-ctrl-c) (princ (buffer-string)))) | |
| 320 | """) | |
| 321 | #expect(ours == emacs, "ours:\n\(ours)\nemacs:\n\(emacs)") | |
| 322 | } | |
| 269 | 323 | } |
Tests/OrgCoreTests/TableSbeTests.swift added +114
| @@ -0,0 +1,114 @@ | ||
| 1 | import Foundation | |
| 2 | import Testing | |
| 3 | @testable import OrgCore | |
| 4 | ||
| 5 | /// `org-sbe` in Lisp table formulas, compared with Emacs. | |
| 6 | struct TableSbeTests { | |
| 7 | static let blocks = """ | |
| 8 | #+NAME: square | |
| 9 | #+begin_src emacs-lisp :var n=2 | |
| 10 | (* n n) | |
| 11 | #+end_src | |
| 12 | ||
| 13 | #+NAME: greet | |
| 14 | #+begin_src emacs-lisp :var who="x" | |
| 15 | (concat "hi " who) | |
| 16 | #+end_src | |
| 17 | ||
| 18 | #+NAME: lst | |
| 19 | #+begin_src emacs-lisp | |
| 20 | '(a "b" 1 2.5) | |
| 21 | #+end_src | |
| 22 | ||
| 23 | #+NAME: sym | |
| 24 | #+begin_src emacs-lisp | |
| 25 | 'foo | |
| 26 | #+end_src | |
| 27 | ||
| 28 | #+NAME: tbl | |
| 29 | #+begin_src emacs-lisp | |
| 30 | '((1 2) hline (3 4)) | |
| 31 | #+end_src | |
| 32 | ||
| 33 | #+NAME: rules | |
| 34 | #+begin_src emacs-lisp | |
| 35 | '((1 2) hline (3 4) hline (5 6)) | |
| 36 | #+end_src | |
| 37 | ||
| 38 | #+NAME: two | |
| 39 | #+begin_src emacs-lisp :var a=1 b=2 | |
| 40 | (list a b) | |
| 41 | #+end_src | |
| 42 | ||
| 43 | #+NAME: out | |
| 44 | #+begin_src emacs-lisp :results output :var x=1 | |
| 45 | (princ (format " x is %s\\n" x)) | |
| 46 | #+end_src | |
| 47 | ||
| 48 | #+NAME: quad | |
| 49 | #+begin_src emacs-lisp :var x=square(n=3) | |
| 50 | (* x 2) | |
| 51 | #+end_src | |
| 52 | ||
| 53 | #+NAME: oops | |
| 54 | #+begin_src emacs-lisp | |
| 55 | (car 1) | |
| 56 | #+end_src | |
| 57 | ||
| 58 | #+NAME: data | |
| 59 | | k | v | | |
| 60 | |---+---| | |
| 61 | | a | 1 | | |
| 62 | | b | 2.5 | | |
| 63 | ||
| 64 | #+NAME: items | |
| 65 | - one | |
| 66 | - 2 | |
| 67 | ||
| 68 | ||
| 69 | """ | |
| 70 | ||
| 71 | static let tables = [ | |
| 72 | blocks + "| n | sq | sqN | g | g$ | lst | sym |\n|---+----+-----+---+----+-----+-----|\n| 3 | | | | | | |\n| abc | | | | | | |\n| 2.5 | | | | | | |\n" | |
| 73 | + "#+TBLFM: $2='(org-sbe \"square\" (n $1))::$3='(org-sbe square (n $1));N::$4='(org-sbe greet (who $1))::$5='(org-sbe greet (who $$1))::$6='(org-sbe lst)::$7='(org-sbe sym)\n", | |
| 74 | blocks + "| n | tbl | rules | none | str | noargs |\n|---+-----+-------+------+-----+--------|\n| 3 | | | | | | |\n| abc | | | | | | |\n" | |
| 75 | + "#+TBLFM: $2='(org-sbe tbl)::$3='(org-sbe rules)::$4='(org-sbe nope)::$5='(org-sbe greet (who \"\\\"q r\\\"\"))::$6='(org-sbe square)\n", | |
| 76 | blocks + "| n | out | quad | oops | data | items | verbatim | empty | two |\n|---+-----+------+------+------+-------+----------+-------+-----|\n| 4 | | | | | | | | |\n" | |
| 77 | + "#+TBLFM: $2='(org-sbe out (x $1))::$3='(org-sbe quad)::$4='(org-sbe oops)::$5='(org-sbe data)::$6='(org-sbe items)::$7='(org-sbe greet \":results verbatim\" (who $$1))::$8='(org-sbe \"\")::$9='(org-sbe two (a $1 $1) (b $$1))\n", | |
| 78 | blocks + "| n | sum |\n|---+-----|\n| 2 | |\n| 5 | |\n#+TBLFM: $2='(+ 1 (string-to-number (org-sbe square (n $1))))\n", | |
| 79 | ] | |
| 80 | ||
| 81 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 82 | func matchesEmacs() throws { | |
| 83 | var cases: [EmacsOracle.Case] = [] | |
| 84 | var ours: [(text: String, caret: Int, failure: String?)] = [] | |
| 85 | for text in Self.tables { | |
| 86 | let caret = (text as NSString).range(of: "#+TBLFM").location + 3 | |
| 87 | cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: "(let ((org-confirm-babel-evaluate nil)) (org-ctrl-c-ctrl-c))")) | |
| 88 | ours.append(TableFormulaTests.recalculate(TableRecalculate(all: true), text, caret: caret)) | |
| 89 | } | |
| 90 | let emacs = try EmacsOracle.run(cases) | |
| 91 | for (i, (mine, theirs)) in zip(ours, emacs).enumerated() { | |
| 92 | let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error) | |
| 93 | #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2, | |
| 94 | "case \(i)\nours:\n\(mine.text.components(separatedBy: "\n\n").last ?? "") \(mine.failure ?? "")\nemacs:\n\(theirs.text.components(separatedBy: "\n\n").last ?? "") \(theirs.error)") | |
| 95 | } | |
| 96 | } | |
| 97 | ||
| 98 | /// Other languages, and references only Emacs follows, go to Emacs. | |
| 99 | @Test func otherLanguagesNeedEmacs() { | |
| 100 | let python = "#+NAME: f\n#+begin_src python :var n=2\nreturn n\n#+end_src\n\n" | |
| 101 | let id = "* Data\n:PROPERTIES:\n:CUSTOM_ID: f\n:END:\n\n" | |
| 102 | for (head, expected) in [(python, "Lisp org-sbe with python blocks"), (id, "Lisp org-sbe with an ID reference")] { | |
| 103 | let text = head + "| n | f |\n|---+---|\n| 3 | |\n#+TBLFM: $2='(org-sbe f (n $1))\n" | |
| 104 | let caret = (text as NSString).range(of: "#+TBLFM").location + 3 | |
| 105 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) | |
| 106 | guard case .external(.emacsTable(_, _, _, let reason, let lisp, _, _)) = TableRecalculate(all: true).run(in: context) else { | |
| 107 | Issue.record("not sent to Emacs: \(expected)") | |
| 108 | continue | |
| 109 | } | |
| 110 | #expect(reason == expected) | |
| 111 | #expect(lisp) | |
| 112 | } | |
| 113 | } | |
| 114 | } | |
Tests/OrgProgramsTests/ProgramsTests.swift +19
| @@ -38,6 +38,25 @@ struct EmacsFallbackTests { | ||
| 38 | 38 | #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-----------|\n| x | a | sqrt(a) |\n| y | 2 | 1.4142136 |\n#+TBLFM: $3=sqrt($2)\n") |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | /// `org-sbe` on a block only Emacs runs: Emacs runs it without asking again. | |
| 42 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 43 | func runsOtherLanguagesForOrgSbe() async throws { | |
| 44 | let notes = try Folder() | |
| 45 | let text = "#+NAME: f\n#+begin_src sh :var n=2\necho $((n * 3))\n#+end_src\n\n| n | f |\n|---+---|\n| 3 | |\n#+TBLFM: $2='(org-sbe f (n $1))\n" | |
| 46 | let file = try notes.write("t.org", text) | |
| 47 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 48 | session.open(file.path) | |
| 49 | let step = session.perform(TableRecalculate(all: true), path: file.path, at: (text as NSString).range(of: "#+TBLFM").location + 3, expect: nil) | |
| 50 | guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp, _, _)) = step else { | |
| 51 | Issue.record("\(step)") | |
| 52 | return | |
| 53 | } | |
| 54 | #expect(reason == "Lisp org-sbe with sh blocks") | |
| 55 | #expect(lisp) | |
| 56 | #expect(await session.recalculateInEmacs(table: table, point: point, form: form) == "Recalculated in Emacs") | |
| 57 | #expect(session.document?.text.hasSuffix("| n | f |\n|---+---|\n| 3 | 9 |\n#+TBLFM: $2='(org-sbe f (n $1))\n") == true) | |
| 58 | } | |
| 59 | ||
| 41 | 60 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| 42 | 61 | func cancelingARecalculationLeavesTheTable() async throws { |
| 43 | 62 | let notes = try Folder() |
docs/manual/guide/10-tables.org +25
| @@ -573,6 +573,31 @@ widths; other codes need Emacs, as do float times in =time-add= and =time-subtra | ||
| 573 | 573 | Any other function, or a macro not listed, needs Emacs. An error inside a Lisp formula |
| 574 | 574 | writes =#ERROR= in the field, as does a Calc error. |
| 575 | 575 | |
| 576 | =org-sbe= writes the value of a named src block, run with the variables given: | |
| 577 | ||
| 578 | #+BEGIN_SRC org | |
| 579 | ,#+NAME: square | |
| 580 | ,#+begin_src emacs-lisp :var n=2 | |
| 581 | (* n n) | |
| 582 | ,#+end_src | |
| 583 | ||
| 584 | | n | square | | |
| 585 | |---+--------| | |
| 586 | | 3 | 9 | | |
| 587 | ,#+TBLFM: $2='(org-sbe square (n $1)) | |
| 588 | #+END_SRC | |
| 589 | ||
| 590 | As in Org, a field's text is read as a value, so =abc= names another block or table; | |
| 591 | write =$$1= instead of =$1= to pass the text as a string. A string before the variables | |
| 592 | holds header arguments, and the name may also be a named table or list in the file. | |
| 593 | Emacs Lisp blocks run in orgstar's interpreter, with dynamic binding unless the block | |
| 594 | has =:lexical yes=, and =js= blocks run in JavaScriptCore, everywhere and without asking, | |
| 595 | since neither can reach files or other programs. Blocks in other languages, blocks with | |
| 596 | =:cache yes=, =:file= results or column and row names, Lisp values with symbols in a | |
| 597 | variable with several values, references to an =ID= or =CUSTOM_ID=, and =js= values | |
| 598 | that are arrays need Emacs. When Emacs runs the table for =org-sbe=, it runs the | |
| 599 | blocks without asking again. | |
| 600 | ||
| 576 | 601 | * Entering formulas |
| 577 | 602 | |
| 578 | 603 | There are three ways to set a formula. |