Run js blocks as node FILE and Babel commands through /bin/sh !426
7 files changed, +180 −32
Layout: unified · split
Sources/OrgApp/JavaScriptBlocks.swift +6 −5
| @@ -19,7 +19,7 @@ public enum JavaScriptBlocks { | ||
| 19 | 19 | switch job.runner { |
| 20 | 20 | case .process: |
| 21 | 21 | guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") } |
| 22 | return try await evaluate(timeout: timeout) { run in try Engine().main(job.input, run: run) } | |
| 22 | return try await evaluate(timeout: timeout) { run in try Engine().main(job.script ?? job.input, run: run) } | |
| 23 | 23 | case .session(let name, _, .node): |
| 24 | 24 | guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") } |
| 25 | 25 | // One context per file folder and session name; a stopped run's context is dropped. |
| @@ -41,19 +41,20 @@ public enum JavaScriptBlocks { | ||
| 41 | 41 | /// and is still running is refused without starting another. |
| 42 | 42 | public static func runHere(_ job: BabelJob, timeout: Duration = .seconds(5)) throws -> BabelOutput? { |
| 43 | 43 | guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil } |
| 44 | if abandoned.contains(job.input) { throw Stopped(description: "The block took too long before and is still running.") } | |
| 44 | let source = job.script ?? job.input | |
| 45 | if abandoned.contains(source) { throw Stopped(description: "The block took too long before and is still running.") } | |
| 45 | 46 | let run = Run() |
| 46 | 47 | let flag = Abandoned.Flag() |
| 47 | 48 | let thread = Thread { |
| 48 | run.end(Result { try Engine().main(job.input, run: run) }) | |
| 49 | abandoned.ended(job.input, flag) | |
| 49 | run.end(Result { try Engine().main(source, run: run) }) | |
| 50 | abandoned.ended(source, flag) | |
| 50 | 51 | } |
| 51 | 52 | thread.stackSize = 8 << 20 |
| 52 | 53 | thread.start() |
| 53 | 54 | do { |
| 54 | 55 | return try run.result(within: timeout) |
| 55 | 56 | } catch let error as Stopped { |
| 56 | abandoned.add(job.input, flag) | |
| 57 | abandoned.add(source, flag) | |
| 57 | 58 | throw error |
| 58 | 59 | } |
| 59 | 60 | } |
Sources/OrgCore/Compute/Babel.swift +8 −5
| @@ -585,11 +585,14 @@ public enum Babel { | ||
| 585 | 585 | input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true, session: true)) |
| 586 | 586 | )) |
| 587 | 587 | } |
| 588 | return .success(BabelJob( | |
| 589 | language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments), | |
| 590 | input: output ? full : jsWrapper(full), directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, | |
| 591 | finish: finishBase(.script(js: true)) | |
| 592 | )) | |
| 588 | // `org-babel-execute:js`: the program in a file, run as `:cmd FILE`, with the | |
| 589 | // newline `org-babel-eval` sends as its input. | |
| 590 | var job = BabelJob( | |
| 591 | language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: [scriptFileToken]), | |
| 592 | input: "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true)) | |
| 593 | ) | |
| 594 | job.script = output ? full : jsWrapper(full) | |
| 595 | return .success(job) | |
| 593 | 596 | case "awk": |
| 594 | 597 | // `org-babel-expand-body:awk`; the variables go on the command line. |
| 595 | 598 | let full = (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "") |
Sources/OrgPrograms/BabelRunner.swift +26 −16
| @@ -2,8 +2,8 @@ | ||
| 2 | 2 | import Foundation |
| 3 | 3 | import OrgCore |
| 4 | 4 | |
| 5 | /// Runs Babel jobs as processes: the interpreter reads the program on standard input, in the | |
| 6 | /// file's folder or `:dir`. | |
| 5 | /// Runs Babel jobs as processes, in the file's folder or `:dir`: the interpreter reads the | |
| 6 | /// program on standard input, or from the file `job.script` is written to. | |
| 7 | 7 | public enum BabelRunner { |
| 8 | 8 | public struct Failure: Error, CustomStringConvertible { |
| 9 | 9 | public let description: String |
| @@ -24,6 +24,24 @@ public enum BabelRunner { | ||
| 24 | 24 | return paths.contains { FileManager.default.isExecutableFile(atPath: $0) } |
| 25 | 25 | } |
| 26 | 26 | |
| 27 | /// The words `/bin/sh` makes of `command`, after expanding `~`, variables and quotes. Empty for | |
| 28 | /// a command substitution, which would otherwise run here as well as when the block runs. | |
| 29 | public static func words(_ command: String) -> [String] { | |
| 30 | if command.contains("$(") || command.contains("`") { return [] } | |
| 31 | guard command.contains(where: { "~$'\"`\\".contains($0) }) else { return command.split(whereSeparator: \.isWhitespace).map(String.init) } | |
| 32 | let process = Process() | |
| 33 | process.executableURL = URL(fileURLWithPath: "/bin/sh") | |
| 34 | process.arguments = ["-c", "printf '%s\\0' " + command] | |
| 35 | process.environment = environment | |
| 36 | let out = Pipe() | |
| 37 | process.standardOutput = out | |
| 38 | process.standardError = FileHandle.nullDevice | |
| 39 | guard (try? process.run()) != nil else { return [] } | |
| 40 | let data = out.fileHandleForReading.readDataToEndOfFile() | |
| 41 | process.waitUntilExit() | |
| 42 | return String(decoding: data, as: UTF8.self).split(separator: "\0").map(String.init) | |
| 43 | } | |
| 44 | ||
| 27 | 45 | public static func run(_ job: BabelJob, fileDirectory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput { |
| 28 | 46 | for programs in job.programs where !programs.contains(where: installed) { |
| 29 | 47 | let names = programs.count == 1 ? programs[0] : "Neither " + programs.joined(separator: " nor ") |
| @@ -42,7 +60,6 @@ public enum BabelRunner { | ||
| 42 | 60 | let process = Process() |
| 43 | 61 | process.executableURL = URL(fileURLWithPath: "/usr/bin/env") |
| 44 | 62 | process.environment = environment |
| 45 | let stdin = Pipe() | |
| 46 | 63 | switch job.runner { |
| 47 | 64 | case .process(let executable, var arguments): |
| 48 | 65 | if let script = job.script { |
| @@ -51,7 +68,8 @@ public enum BabelRunner { | ||
| 51 | 68 | try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path) |
| 52 | 69 | arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) } |
| 53 | 70 | } |
| 54 | process.arguments = [executable] + arguments | |
| 71 | // In the shell, as Org runs it, so `:cmd "node --no-warnings"` or `~/bin/node` works. | |
| 72 | process.arguments = ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments | |
| 55 | 73 | case .emacs: |
| 56 | 74 | guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") } |
| 57 | 75 | let script = folder.appendingPathComponent("babel.el") |
| @@ -71,7 +89,10 @@ public enum BabelRunner { | ||
| 71 | 89 | let stderr = folder.appendingPathComponent("stderr") |
| 72 | 90 | FileManager.default.createFile(atPath: stderr.path, contents: nil) |
| 73 | 91 | let err = try FileHandle(forWritingTo: stderr) |
| 74 | process.standardInput = stdin | |
| 92 | // The input from a file, as `org-babel-eval` gives it. | |
| 93 | let stdin = folder.appendingPathComponent("stdin") | |
| 94 | if case .process = job.runner { try input.write(to: stdin, atomically: true, encoding: .utf8) } else { FileManager.default.createFile(atPath: stdin.path, contents: nil) } | |
| 95 | process.standardInput = try FileHandle(forReadingFrom: stdin) | |
| 75 | 96 | process.standardOutput = out |
| 76 | 97 | process.standardError = err |
| 77 | 98 | do { |
| @@ -79,17 +100,6 @@ public enum BabelRunner { | ||
| 79 | 100 | } catch { |
| 80 | 101 | throw Failure(description: "Can't start \(process.arguments?.first ?? "the interpreter"): \(error.localizedDescription)") |
| 81 | 102 | } |
| 82 | if case .process = job.runner { | |
| 83 | let handle = stdin.fileHandleForWriting | |
| 84 | let data = Data(input.utf8) | |
| 85 | // Large programs would fill the pipe; write off the main thread. | |
| 86 | Task.detached { | |
| 87 | try? handle.write(contentsOf: data) | |
| 88 | try? handle.close() | |
| 89 | } | |
| 90 | } else { | |
| 91 | try stdin.fileHandleForWriting.close() | |
| 92 | } | |
| 93 | 103 | let deadline = ContinuousClock.now + timeout |
| 94 | 104 | while process.isRunning { |
| 95 | 105 | if ContinuousClock.now > deadline { |
Sources/OrgPrograms/Programs.swift +6 −1
| @@ -16,8 +16,13 @@ public struct Programs: ProgramRunning { | ||
| 16 | 16 | // js in JavaScriptCore when node (or `:cmd`) isn't installed. A `:cmd` with arguments runs |
| 17 | 17 | // as written, since JavaScriptCore can't take node's options. |
| 18 | 18 | switch job.runner { |
| 19 | case .process(let executable, _), .session(_, let executable, _): | |
| 19 | case .process(let executable, _) where job.language == "js" || job.language == "javascript": | |
| 20 | let words = BabelRunner.words(executable) | |
| 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, _): | |
| 20 | 23 | if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } |
| 24 | case .process: | |
| 25 | break | |
| 21 | 26 | case .emacs: |
| 22 | 27 | // Emacs Lisp in `Elisp` when Emacs isn't installed. |
| 23 | 28 | if emacs() == nil { |
Tests/OrgAppTests/JavaScriptBlocksTests.swift +1 −1
| @@ -88,7 +88,7 @@ struct JavaScriptBlocksTests { | ||
| 88 | 88 | + Self.programs.map { "#+begin_src js :results output\n\($0)\n#+end_src\n" } |
| 89 | 89 | for block in blocks { |
| 90 | 90 | let job = try Self.plan(block) |
| 91 | let theirs = try Self.node(job.input, in: folder) | |
| 91 | let theirs = try Self.node(try #require(job.script), in: folder) | |
| 92 | 92 | let ours = try await JavaScriptBlocks.run(job, directory: folder) |
| 93 | 93 | #expect(ours?.stdout == theirs.stdout && ours?.status == theirs.status, "\(block)\nours: \(ours?.stdout ?? "nil") \(ours?.stderr ?? "")\nnode: \(theirs.stdout)") |
| 94 | 94 | } |
Tests/OrgProgramsTests/ProgramsTests.swift +129
| @@ -254,6 +254,135 @@ struct JavaScriptFallbackTests { | ||
| 254 | 254 | func usesNodeWhenInstalled() async throws { |
| 255 | 255 | #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n") |
| 256 | 256 | } |
| 257 | ||
| 258 | /// A `:cmd` the shell expands, such as `~/../../opt/homebrew/bin/node`, runs node, as in Org. | |
| 259 | @Test(.enabled(if: BabelRunner.installed("node"))) | |
| 260 | func expandsTheCommandAsTheShellDoes() async throws { | |
| 261 | let node = try #require(BabelRunner.environment["PATH"]?.split(separator: ":").map { "\($0)/node" } | |
| 262 | .first { FileManager.default.isExecutableFile(atPath: $0) }) | |
| 263 | let home = NSHomeDirectory() | |
| 264 | let up = String(repeating: "../", count: home.split(separator: "/").count) | |
| 265 | for cmd in ["~/" + up + node.dropFirst(), "$HOME/" + up + node.dropFirst(), "'\(node)'"] { | |
| 266 | let output = try await run("#+begin_src js :cmd \"\(cmd)\" :results output\nconsole.log(typeof __filename)\n#+end_src\n") | |
| 267 | #expect(output.stdout == "string\n", "\(cmd)") | |
| 268 | } | |
| 269 | } | |
| 270 | ||
| 271 | /// An expanded `:cmd` that isn't installed runs in JavaScriptCore. | |
| 272 | @Test func expandedCommandFallsBack() async throws { | |
| 273 | #expect(try await run("#+begin_src js :cmd ~/no-such-node\nreturn [1, 2]\n#+end_src\n").stdout == "[ 1, 2 ]") | |
| 274 | } | |
| 275 | } | |
| 276 | ||
| 277 | /// Interpreters run through `/bin/sh`, as Org runs them. | |
| 278 | struct ShellCommandTests { | |
| 279 | @Test func words() { | |
| 280 | #expect(BabelRunner.words("node --no-warnings") == ["node", "--no-warnings"]) | |
| 281 | #expect(BabelRunner.words("~/bin/node") == [NSHomeDirectory() + "/bin/node"]) | |
| 282 | #expect(BabelRunner.words("'a b' \"$HOME\"") == ["a b", NSHomeDirectory()]) | |
| 283 | } | |
| 284 | ||
| 285 | /// A command substitution in the command runs once, when the block runs, as in Org. | |
| 286 | @Test(arguments: ["js :cmd", "python :python", "ruby :ruby"]) | |
| 287 | func substitutionRunsOnce(header: String) async throws { | |
| 288 | #expect(BabelRunner.words("$(echo node)").isEmpty) | |
| 289 | #expect(BabelRunner.words("`echo node`").isEmpty) | |
| 290 | let folder = try Folder() | |
| 291 | let count = folder.url.appendingPathComponent("count").path | |
| 292 | let text = "#+begin_src \(header) \"$(echo x >> '\(count)'; echo cat)\" :results output\n1\n#+end_src\n" | |
| 293 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2]) | |
| 294 | guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") } | |
| 295 | _ = try await Programs().runBabel(job, fileDirectory: folder.url) | |
| 296 | #expect(try String(contentsOfFile: count, encoding: .utf8) == "x\n") | |
| 297 | } | |
| 298 | ||
| 299 | @Test(.enabled(if: BabelRunner.installed("python3"))) | |
| 300 | func pythonWithOptions() async throws { | |
| 301 | let text = "#+begin_src python :python \"python3 -X utf8\" :results output\nimport sys\nprint(sys.flags.utf8_mode)\n#+end_src\n" | |
| 302 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2]) | |
| 303 | guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") } | |
| 304 | #expect(try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory).stdout == "1\n") | |
| 305 | } | |
| 306 | ||
| 307 | /// Standard input is a file, as `org-babel-eval` gives it. | |
| 308 | @Test(.enabled(if: BabelRunner.installed("node"))) | |
| 309 | func standardInputIsAFile() async throws { | |
| 310 | let text = "#+begin_src js :results output\nconst s = require('fs').fstatSync(0)\nconsole.log(s.isFile(), s.isFIFO(), process.stdin.constructor.name)\n#+end_src\n" | |
| 311 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2]) | |
| 312 | guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") } | |
| 313 | #expect(try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory).stdout == "true false ReadStream\n") | |
| 314 | } | |
| 315 | } | |
| 316 | ||
| 317 | /// js blocks without a session run as `node FILE`, as `org-babel-execute:js` runs them. | |
| 318 | @MainActor | |
| 319 | @Suite(.programs) | |
| 320 | struct NodeFileTests { | |
| 321 | static let cases = [ | |
| 322 | "#+begin_src js :results output\nconsole.log(typeof require, typeof module, typeof exports, process.argv.length, require.main === module)\n#+end_src\n", | |
| 323 | "#+begin_src js :results output\nconst path = require('path'), fs = require('fs')\nconsole.log(path.dirname(__filename) === __dirname, __dirname === process.cwd(), " | |
| 324 | + "path.dirname(__dirname) === fs.realpathSync(require('os').tmpdir()), path.basename(process.argv[1]) === path.basename(__filename))\n#+end_src\n", | |
| 325 | "#+begin_src js\nreturn [typeof require, typeof module, process.argv.length, this === module.exports]\n#+end_src\n", | |
| 326 | "#+begin_src js :results output\ntry { require('./helper'); console.log('found') } catch (e) { console.log(e.code) }\nconsole.log(require(process.cwd() + '/helper'))\n#+end_src\n", | |
| 327 | "#+begin_src js :results output\nimport os from 'os'\nconsole.log(typeof require, typeof os.tmpdir)\n#+end_src\n", | |
| 328 | "#+begin_src js :cmd \"node --no-warnings\" :results output\nconsole.log(process.argv.length, process.execArgv.join(' '))\n#+end_src\n", | |
| 329 | "#+begin_src js :results output\nconsole.log(JSON.stringify(require('fs').readFileSync(0, 'utf8')))\n#+end_src\n", | |
| 330 | "#+begin_src js :results output\nconsole.log('top'); return; console.log('not reached')\n#+end_src\n", | |
| 331 | "#+begin_src js :results output\nconst s = require('fs').fstatSync(0)\nconsole.log(s.isFile(), s.isFIFO(), process.stdin.constructor.name)\n#+end_src\n", | |
| 332 | ] | |
| 333 | ||
| 334 | /// The results Emacs inserts. `org-babel-temporary-directory` is set as interactive Emacs | |
| 335 | /// sets it; `--batch` leaves it nil and writes the file straight into the temporary folder. | |
| 336 | @Test(.enabled(if: EmacsRunner.executable() != nil && BabelRunner.installed("node") && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 337 | func resultsMatchEmacs() async throws { | |
| 338 | let folder = try Folder() | |
| 339 | try folder.write("helper.js", "module.exports = 1\n") | |
| 340 | var forms: [String] = [] | |
| 341 | var ours: [String] = [] | |
| 342 | for text in Self.cases { | |
| 343 | let file = try folder.write("b.org", text) | |
| 344 | let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r"))) | |
| 345 | session.open(file.path) | |
| 346 | guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 2, expect: nil) else { | |
| 347 | Issue.record("not planned: \(text)") | |
| 348 | return | |
| 349 | } | |
| 350 | _ = await session.runBabel(job) | |
| 351 | ours.append(session.document?.text ?? "") | |
| 352 | let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" | |
| 353 | forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char 3) (org-babel-execute-src-block) (princ (concat (buffer-string) \"\\f\")))") | |
| 354 | } | |
| 355 | let process = Process() | |
| 356 | process.executableURL = EmacsRunner.executable() | |
| 357 | process.currentDirectoryURL = folder.url | |
| 358 | process.arguments = ["-Q", "--batch", "--eval", """ | |
| 359 | (progn (require 'org) (require 'ob-js) | |
| 360 | (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node" org-babel-temporary-directory (make-temp-file "babel-" t)) | |
| 361 | \(forms.joined(separator: "\n")) | |
| 362 | (delete-directory org-babel-temporary-directory t)) | |
| 363 | """] | |
| 364 | let out = Pipe() | |
| 365 | process.standardOutput = out | |
| 366 | process.standardError = FileHandle.nullDevice | |
| 367 | try process.run() | |
| 368 | let emacs = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) | |
| 369 | .split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init) | |
| 370 | process.waitUntilExit() | |
| 371 | for (i, text) in Self.cases.enumerated() { | |
| 372 | #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])") | |
| 373 | } | |
| 374 | } | |
| 375 | ||
| 376 | /// The file is gone once the block has run. | |
| 377 | @Test(.enabled(if: BabelRunner.installed("node"))) | |
| 378 | func removesTheFile() async throws { | |
| 379 | let text = "#+begin_src js :results output\nconsole.log(__filename)\n#+end_src\n" | |
| 380 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2]) | |
| 381 | guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") } | |
| 382 | let output = try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory) | |
| 383 | let file = output.stdout.trimmingCharacters(in: .newlines) | |
| 384 | #expect(file.hasPrefix("/") && !FileManager.default.fileExists(atPath: file)) | |
| 385 | } | |
| 257 | 386 | } |
| 258 | 387 | |
| 259 | 388 | /// Emacs Lisp runs in `Elisp` when Emacs isn't installed. |
docs/manual/guide/11-code-blocks.org +4 −4
| @@ -82,7 +82,7 @@ The block's text is remembered when the run starts. If you edit the block while | ||
| 82 | 82 | |
| 83 | 83 | ** Languages that run |
| 84 | 84 | |
| 85 | On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an app opened from the Dock does not see your shell's =PATH=, orgstar adds =/opt/homebrew/bin=, =/usr/local/bin=, =/Library/TeX/texbin=, =/usr/bin= and =/bin= to the end of it. | |
| 85 | On the Mac, orgstar starts each interpreter outside a =:session= through =/bin/sh=, as Org does, with standard input read from a file. Because an app opened from the Dock does not see your shell's =PATH=, orgstar adds =/opt/homebrew/bin=, =/usr/local/bin=, =/Library/TeX/texbin=, =/usr/bin= and =/bin= to the end of it. | |
| 86 | 86 | |
| 87 | 87 | | Language | Program run | |
| 88 | 88 | |------------------------------------------------------------------+-----------------------------------------------------| |
| @@ -91,13 +91,13 @@ On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an a | ||
| 91 | 91 | | =python= | =python3=, or the program in =:python= | |
| 92 | 92 | | =emacs-lisp=, =elisp= | =emacs -Q --batch=, or the interpreter; see below | |
| 93 | 93 | | =ruby= | =ruby=, or the program in =:ruby= | |
| 94 | | =js=, =javascript= | =node=, or JavaScriptCore without it; see below | | |
| 94 | | =js=, =javascript= | =node FILE=, the program written to a file, or JavaScriptCore without node; see below | | |
| 95 | 95 | | =R= | =Rscript -= | |
| 96 | 96 | | =awk= | =awk -f=, the program written to a file | |
| 97 | 97 | | =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below | |
| 98 | 98 | | =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below | |
| 99 | 99 | |
| 100 | For =js=, =javascript= and =R=, =:cmd= names a different program. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads. | |
| 100 | For =js=, =javascript= and =R=, =:cmd= names a different program. Since it runs through =/bin/sh=, a program in =:cmd=, =:python= or =:ruby= can be given with options, such as =:cmd "node --no-warnings"= or =:python "python3 -X utf8"=, or with =~= or a variable, such as =:cmd "~/bin/node"=. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads. | |
| 101 | 101 | |
| 102 | 102 | Any other language is refused with "No way to run /language/ blocks yet." |
| 103 | 103 | |
| @@ -107,7 +107,7 @@ The [[file:../install.org][Mac App Store version]] starts no programs, so only E | ||
| 107 | 107 | |
| 108 | 108 | ** JavaScript in JavaScriptCore |
| 109 | 109 | |
| 110 | In the Mac App Store version and on iOS, =js= and =javascript= blocks run in JavaScriptCore, the JavaScript engine built into macOS and iOS. The download version uses it when =node=, or the program in =:cmd=, isn't installed; a =:cmd= with options, such as =node --no-warnings=, never runs in JavaScriptCore. A block runs as Emacs runs it, with =node= reading it from a file as a CommonJS module, where =this= is =module.exports= and top-level =var= declarations stay in the block. Its output and result are what node gives: | |
| 110 | In the Mac App Store version and on iOS, =js= and =javascript= blocks run in JavaScriptCore, the JavaScript engine built into macOS and iOS. The download version uses it when =node=, or the program in =:cmd= after =/bin/sh= expands it, isn't installed; a =:cmd= with options, such as =node --no-warnings=, or with a command substitution, such as =$(which node)=, never runs in JavaScriptCore. A block runs as Emacs runs it, with =node= reading it from a file as a CommonJS module, where =this= is =module.exports= and top-level =var= declarations stay in the block. Its output and result are what node gives: | |
| 111 | 111 | |
| 112 | 112 | - =console.log=, =console.info= and =console.debug= write to the output, =console.warn= and =console.error= to the error output, and =console.dir= prints with =util.inspect=. =process.stdout.write= and =process.stderr.write= write text. |
| 113 | 113 | - =require('util')= has =inspect=, =format= and =formatWithOptions=, which print values as Node 26 prints them. =require('process')= has =stdout= and =stderr=. |