Commit dd764a1db9

dd764a1db9c6495c09fa4fc20856a781d84441e4

parent: 76e3cf98ba

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 12:39 UTC

Babel: :post, and noweb references that run a block

:post resolves its reference after the block has run, with the block's
result as *this*, and inserts the reference's value. <<name()>> and
<<name(arg=value)>> expand to the result of the named block when :noweb
expands for running. Both go through the path :var references use: one
trust prompt for every block reached, :cache and :eval of the referenced
block, and cycles refused. Tangling refuses a noweb reference that would
run a block.

Without a program runner, a block whose references reach a language
that doesn't run in-process runs nothing. A referenced block with
:results file gives its file name, as in Org, and its file is written.

Closes #114

Layout: unified · split

Sources/OrgApp/DocumentSession.swift +25 −9
@@ -925,6 +925,7 @@ public final class DocumentSession {
925925 /// A program through `programs`; without it, Emacs Lisp in `Elisp` and js in
926926 /// JavaScriptCore, and nothing else.
927927 func run(_ job: BabelJob) async throws -> BabelOutput {
928 if let output = job.known { return output }
928929 if let programs { return try await programs.runBabel(job, fileDirectory: directory) }
929930 #if canImport(JavaScriptCore)
930931 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output }
@@ -949,8 +950,26 @@ public final class DocumentSession {
949950 }
950951 return output
951952 }
953 /// Writes the result to `:file`, when the block asks for that; a message when it can't.
954 func write(_ job: BabelJob, _ output: BabelOutput) -> String? {
955 guard let file = Babel.fileResult(job, output: output) else { return nil }
956 do {
957 try file.contents.write(to: Self.resultFile(file.path, job: job, directory: directory), atomically: true, encoding: .utf8)
958 return nil
959 } catch {
960 return "Can't write \(file.path): \(error.localizedDescription)"
961 }
962 }
963 // Without programs, a block that refers to one that can't run here runs nothing.
964 if programs == nil, !job.needs.isEmpty, let language = ([job.language] + job.referenced).first(where: { !Self.inProcess.contains($0) }) {
965 #if os(macOS)
966 return "This block needs a \(language) block, and \(language) blocks don't run in this version of orgstar; nothing was run."
967 #else
968 return "This block needs a \(language) block, and \(language) blocks need the Mac to run; nothing was run."
969 #endif
970 }
952971 do {
953 // Blocks the `:var`s refer to run first, one at a time.
972 // Blocks the `:var`s, `:post` and noweb references refer to run first, one at a time.
954973 // Each is one of the blocks agreed to, or the run stops: the text may have changed
955974 // while a block ran.
956975 var job = job
@@ -967,6 +986,7 @@ public final class DocumentSession {
967986 guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." }
968987 let output = try await run(need.job)
969988 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
989 if let message = write(need.job, output) { return message }
970990 let document = entry.buffer.document
971991 switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) {
972992 case .failure(.message(let message)): return message
@@ -976,14 +996,7 @@ public final class DocumentSession {
976996 guard agreed(job) else { return "The blocks changed while running; nothing more was run." }
977997 let output = try await run(job)
978998 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
979 if let file = Babel.fileResult(job, output: output) {
980 let target = Self.resultFile(file.path, job: job, directory: directory)
981 do {
982 try file.contents.write(to: target, atomically: true, encoding: .utf8)
983 } catch {
984 return "Can't write \(file.path): \(error.localizedDescription)"
985 }
986 }
999 if let message = write(job, output) { return message }
9871000 let current = entry.buffer
9881001 let document = current.document
9891002 let done = output.problem ?? "Code block evaluation complete."
@@ -1006,6 +1019,9 @@ public final class DocumentSession {
10061019 }
10071020 }
10081021
1022 /// The languages that run without programs.
1023 static let inProcess: Set<String> = ["emacs-lisp", "elisp", "js", "javascript", "calc", "sqlite", "dot", "mermaid"]
1024
10091025 /// Where a block's `:file` result goes: relative to `:dir`, itself relative to `directory`.
10101026 static func resultFile(_ name: String, job: BabelJob, directory: URL) -> URL {
10111027 let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
Sources/OrgCore/Compute/Babel.swift +74 −24
@@ -34,7 +34,7 @@ public struct BabelJob: Sendable, Equatable {
3434 public let blockText: String
3535 /// Asks every time (`:eval query`) rather than trusting by content.
3636 public let alwaysAsk: Bool
37 public let finish: Finish
37 public internal(set) var finish: Finish
3838 /// A named block a `:var` refers to: run it first, then `Babel.resume` with its output.
3939 public var needs: [Need] = []
4040 /// With `needs`: the text of every block the run may execute, the one asked about and
@@ -61,6 +61,10 @@ public struct BabelJob: Sendable, Equatable {
6161 public internal(set) var diagram: Babel.Diagram?
6262 /// Files the runner writes, each where its key stands in `input`: `:var` tables as CSV.
6363 public internal(set) var dataFiles: [String: String] = [:]
64 /// With `needs`: the languages of the blocks the references reach.
65 public internal(set) var referenced: [String] = []
66 /// The output of a block whose `:post` reference has given its result: nothing is left to run.
67 public var known: BabelOutput? { finish.post.map { BabelOutput(stdout: Babel.shellString($0)) } }
6468
6569 public struct Need: Sendable, Equatable {
6670 /// The `:var` value, `name` or `name(args)`.
@@ -105,6 +109,10 @@ public struct BabelJob: Sendable, Equatable {
105109 /// (`org-babel-reassemble-table`).
106110 var colnames: [String]?
107111 var rownames: [String]?
112 /// The value of the `:post` reference, which is the result.
113 var post: Babel.VarValue?
114 /// The value is a list of rows when it is a list, as a `:post` value is too.
115 var givesRows: Bool { post != nil || kind.givesRows }
108116 }
109117}
110118
@@ -165,7 +173,7 @@ public enum Babel {
165173 /// `need.job`, as `org-babel-ref-resolve` reads it.
166174 public static func resume(_ job: BabelJob, need: BabelJob.Need, output: BabelOutput, text: String, tree: OrgTree) -> Result<BabelJob, Failure> {
167175 var resolved = job.resolved
168 resolved[need.reference] = varValue(need.job.finish, output)
176 resolved[need.reference] = varValue(need.job.finish, output, this: need.reference.hasPrefix(thisPrefix))
169177 let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret])
170178 return plan(context, options: job.options, resolved: resolved)
171179 }
@@ -344,8 +352,15 @@ public enum Babel {
344352 var options: Options
345353 /// Blocks being planned for a reference, to stop cycles.
346354 var visiting: Set<String> = []
355 /// `*this*` while a `:post` reference is resolved, and the key of the run it came from,
356 /// which goes before the references that use it in `resolved`.
357 var this: VarValue?
358 var thisKey = ""
347359 }
348360
361 /// Starts the key in `References.resolved` of a block's result before its `:post`.
362 static let thisPrefix = "*this*\u{1}"
363
349364 /// A reference to a block that has to run first.
350365 struct Needed: Error {
351366 let need: BabelJob.Need
@@ -357,13 +372,65 @@ public enum Babel {
357372 evaluated.evaluateLisp(file: options.file)
358373 let needsFile = options.file == nil && evaluated.lisp.contains { evaluated.evaluated[$0] == nil }
359374 return planBlock(block, params: params, model: model, text: ns, options: options, location: location, name: name, inline: inline,
360 refs: refs, useCache: useCache).map { job in
375 refs: refs, useCache: useCache).flatMap { job in
376 guard let post = evaluated.single[":post"] else { return .success(job) }
377 return posted(job, post: post, block: block, params: evaluated, model: model, text: ns, refs: refs ?? References(resolved: [:], options: options))
378 }.map { job in
361379 var job = job
362380 job.needsFile = needsFile
363381 return job
364382 }
365383 }
366384
385 /// `:post` (`org-babel-execute-src-block`): the block runs first, as a need; then the
386 /// reference is resolved with the block's result as `*this*`, and its value is the result.
387 /// Before the block or anything it needs runs, the reference is resolved with an empty
388 /// `*this*`, so that one that can't be resolved stops the run.
389 static func posted(_ job: BabelJob, post: String, block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString,
390 refs: References) -> Result<BabelJob, Failure> {
391 let key = thisPrefix + refs.thisKey + job.blockText + "\u{1}" + params.vars.map { "\($0.name)=\($0.value)" }.joined(separator: " ")
392 let this = refs.resolved[key]
393 var inner = refs
394 (inner.this, inner.thisKey) = (this ?? .scalar(""), key)
395 var need = BabelJob.Need(reference: key, job: job)
396 do {
397 let value = try resolve(post, model: model, text: text, refs: inner, through: ":post")
398 if this != nil {
399 var done = job
400 done.finish.post = value
401 // The link to `:file` went to the reference as `*this*`.
402 if done.finish.file != nil { done.finish.params.removeAll { $0 == "file" } }
403 return .success(done)
404 }
405 } catch let needed as Needed {
406 if this != nil { need = needed.need }
407 } catch let error as Failure {
408 return .failure(error)
409 } catch {
410 return .failure(.message("\(error)"))
411 }
412 guard job.needs.isEmpty else { return .success(job) }
413 return .success(waiting(on: need, language: job.language, directory: job.directory, location: job.block, ask: job.alwaysAsk, finish: job.finish,
414 block: block, params: params, model: model, text: text))
415 }
416
417 /// A job that waits on `need`. It is asked about once, with every block the references
418 /// reach, and every time when any of them has `:eval query`.
419 static func waiting(on need: BabelJob.Need, language: String, directory: String?, location: Range<Int>, ask: Bool, finish: BabelJob.Finish,
420 block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString) -> BabelJob {
421 var seen: Set<Int> = []
422 let reached = referencedBlocks(block, params, model: model, text: ns, seen: &seen)
423 let texts = [ns.substring(with: NSRange(location))] + reached.map { ns.substring(with: NSRange($0.range)) }
424 let query = ask || reached.contains { (try? Params(block: $0, model: model, text: ns))?.single[":eval"]?.lowercased() == "query" }
425 var job = BabelJob(
426 language: language, runner: .process(executable: "", arguments: []), input: "", directory: directory,
427 block: location, blockText: texts.joined(separator: "\n"), alwaysAsk: query, finish: finish, needs: [need]
428 )
429 job.approved = texts
430 job.referenced = reached.compactMap(\.language)
431 return job
432 }
433
367434 static func planBlock(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
368435 location: Range<Int>, name: String?, inline: Bool, refs: References?, useCache: Bool) -> Result<BabelJob, Failure> {
369436 let refs = refs ?? References(resolved: [:], options: options)
@@ -380,7 +447,7 @@ public enum Babel {
380447 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
381448 }
382449 let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp", "calc", "sqlite"].contains(language) || generic[language] != nil
383 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
450 for key in [":prologue", ":epilogue", ":stdin", ":shebang"] where params.single[key] != nil
384451 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) {
385452 return .failure(.message("\(key) isn't supported yet; nothing was run."))
386453 }
@@ -390,15 +457,6 @@ public enum Babel {
390457 return .failure(.message(":session isn't supported for \(language) yet; nothing was run."))
391458 }
392459 var body = normalizedBody(block)
393 if nowebEvaluates(params.single[":noweb"]) {
394 do {
395 body = try expandNoweb(block, params: params, model: model, text: ns)
396 } catch let error as Failure {
397 return .failure(error)
398 } catch {
399 return .failure(.message("\(error)"))
400 }
401 }
402460 let output = params.results.contains("output")
403461 let file = params.single[":file"].map { name in
404462 params.single[":output-dir"].map { $0.hasSuffix("/") ? $0 + name : $0 + "/" + name } ?? name
@@ -414,21 +472,13 @@ public enum Babel {
414472 let vars: [(String, VarValue)]
415473 var stdin: VarValue?
416474 do {
475 if nowebEvaluates(params.single[":noweb"]) { body = try expandNoweb(block, params: params, model: model, text: ns, refs: refs) }
417476 tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns, refs: refs)) }, params: params)
418477 vars = tables.vars
419478 stdin = try params.single[":stdin"].map { try resolve($0, model: model, text: ns, refs: refs) }
420479 } catch let needed as Needed {
421 // Asked about once, with every block the references reach; asked every time when
422 // any of them has `:eval query`.
423 let reached = referencedBlocks(params, model: model, text: ns, seen: [])
424 let texts = [ns.substring(with: NSRange(location))] + reached.map { ns.substring(with: NSRange($0.range)) }
425 let query = eval == "query" || reached.contains { (try? Params(block: $0, model: model, text: ns))?.single[":eval"]?.lowercased() == "query" }
426 var job = BabelJob(
427 language: language, runner: .process(executable: "", arguments: []), input: "", directory: params.single[":dir"],
428 block: location, blockText: texts.joined(separator: "\n"), alwaysAsk: query, finish: finishBase(.generic), needs: [needed.need]
429 )
430 job.approved = texts
431 return .success(job)
480 return .success(waiting(on: needed.need, language: language, directory: params.single[":dir"], location: location, ask: eval == "query",
481 finish: finishBase(.generic), block: block, params: params, model: model, text: ns))
432482 } catch let error as Failure {
433483 return .failure(error)
434484 } catch {
Sources/OrgCore/Compute/BabelNoweb.swift +38 −5
@@ -20,8 +20,11 @@ extension Babel {
2020 /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as
2121 /// evaluation does.
2222 /// `links` gives a block's begin and end comments, for `:comments noweb` when tangling.
23 /// `<<name()>>` and `<<name(arg=value)>>` become the result of the block named so, which
24 /// `refs` resolves as it does a `:var` (`org-babel-ref-resolve`); without `refs` nothing
25 /// may run, and they are refused.
2326 static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0,
24 links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil) throws -> String {
27 links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil, refs: References? = nil) throws -> String {
2528 guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") }
2629 let body = normalizedBody(block)
2730 let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true
@@ -30,7 +33,7 @@ extension Babel {
3033 let otherParams = try Params(block: other, model: model, text: text)
3134 let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"])
3235 let b = expands
33 ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links)
36 ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links, refs: refs)
3437 : normalizedBody(other)
3538 guard commenting, let links else { return b }
3639 // `c-wrap`: commented in this block's language, trimmed.
@@ -49,18 +52,24 @@ extension Babel {
4952 guard let h = b.heading else { return false }
5053 return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
5154 }
52 let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
5355 let ns = body as NSString
5456 var out = ""
5557 var at = 0
56 for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
58 for m in nowebReference.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
5759 let prefix = ns.substring(with: m.range(at: 1))
5860 let id = ns.substring(with: m.range(at: 3))
5961 out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at))
6062 at = NSMaxRange(m.range)
6163 var expansion = ""
6264 if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
63 throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.")
65 guard let refs else {
66 throw Failure.message("The noweb reference <<\(id)>> would run a block while tangling, which isn't supported yet; nothing was tangled.")
67 }
68 // The value as it is when a string, else printed with `%S`.
69 switch try resolve(id, model: model, text: text, refs: refs, through: "a noweb reference") {
70 case .scalar(let s): expansion = s
71 case let value: expansion = lispLiteral(value)
72 }
6473 } else if let heading = model.headings.firstIndex(where: { h in
6574 h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) }
6675 }) {
@@ -86,6 +95,30 @@ extension Babel {
8695 return out + ns.substring(from: at)
8796 }
8897
98 /// `org-babel-noweb-wrap` after the text before it on its line.
99 static let nowebReference = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
100
101 /// The references that run a block in the body of `block`, and in the bodies its other
102 /// references bring in when evaluation expands them.
103 static func nowebCalls(_ block: SrcBlockInfo, model: DocumentModel, text: NSString, seen: inout Set<Int>) -> [String] {
104 guard seen.insert(block.range.lowerBound).inserted else { return [] }
105 var calls: [String] = []
106 let body = block.body as NSString
107 for m in nowebReference.matches(in: block.body, range: NSRange(location: 0, length: body.length)) {
108 let id = body.substring(with: m.range(at: 3))
109 if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
110 calls.append(id)
111 continue
112 }
113 for other in model.srcBlocks {
114 guard let params = try? Params(block: other, model: model, text: text), other.name == id || params.single[":noweb-ref"] == id,
115 nowebEvaluates(params.single[":noweb"]) else { continue }
116 calls += nowebCalls(other, model: model, text: text, seen: &seen)
117 }
118 }
119 return calls
120 }
121
89122 /// `org-babel-ref-headline-body`: the entry after its planning and drawers.
90123 static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String {
91124 let heading = model.headings[index]
Sources/OrgCore/Compute/BabelResults.swift +11 −3
@@ -43,6 +43,14 @@ extension Babel {
4343
4444 /// The language's result handling: `org-babel-result-cond` and the table import.
4545 static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
46 // The value of `:post` goes in as it is; a list is a table of one row.
47 if let post = finish.post, !finish.params.contains("file") {
48 switch post {
49 case .scalar(let s), .number(let s): return .string(s)
50 case .list(let items): return .table([items.map(cellText)])
51 case .table(let rows): return .table(rows.map { $0?.map(cellText) })
52 }
53 }
4654 let value = reassemble(rawValue(finish, output), finish)
4755 switch (finish.kind, value) {
4856 case (.calc, .string(let s)), (.sqlite, .string(let s)):
@@ -58,7 +66,7 @@ extension Babel {
5866 let params = finish.params
5967 if params.contains("file") {
6068 // `org-babel-result-to-file`: a link to `:file`, or to the result as a path.
61 let path = finish.file ?? rawResult(finish, output)
69 let path = finish.file ?? finish.post.map { shellString($0) } ?? rawResult(finish, output)
6270 var link = "[[file:" + path + "]"
6371 if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
6472 return .string(link + "]")
@@ -442,7 +450,7 @@ extension Babel {
442450 switch value {
443451 case .none:
444452 break
445 case .string(let s) where params.contains("list") && finish.kind.givesRows:
453 case .string(let s) where params.contains("list") && finish.givesRows:
446454 // `split-string` without empty lines, each an item; `org-trim` of the list.
447455 var items = s.components(separatedBy: "\n").filter { !$0.isEmpty }.map { "- " + $0 }.joined(separator: "\n")
448456 while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() }
@@ -451,7 +459,7 @@ extension Babel {
451459 if s.last != "\n" { s += "\n" }
452460 let items = s.split(separator: "\n", omittingEmptySubsequences: true)
453461 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
454 case .table(let rows) where params.contains("list") && finish.kind.givesRows:
462 case .table(let rows) where params.contains("list") && finish.givesRows:
455463 // Each row an item, its first cell the text and the others lines under it.
456464 listed = true
457465 var items = rows.map { row in
Sources/OrgCore/Compute/BabelVars.swift +31 −15
@@ -111,8 +111,14 @@ extension Babel {
111111
112112 // MARK: - Variables
113113
114 /// A referenced block's result as a `:var` value.
115 static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue {
114 /// A referenced block's result as `org-babel-execute-src-block` returns it: with
115 /// `:results file`, the name of `:file`, or without one the result as the program left it.
116 /// `this` gives the value of `*this*`, where `:file` is a link.
117 static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput, this: Bool = false) -> VarValue {
118 if finish.params.contains("file") {
119 guard let file = finish.file else { return .scalar(rawResult(finish, output)) }
120 if !this { return .scalar(file) }
121 }
116122 switch value(finish, output) {
117123 case .none: return .scalar("")
118124 case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s)
@@ -169,16 +175,21 @@ extension Babel {
169175 return (block, m.2.map(String.init))
170176 }
171177
172 /// The blocks `params`' references run, directly or through theirs.
173 static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] {
178 /// The blocks the references of `block` run, directly or through theirs: its `:var`,
179 /// `:stdin` and `:post`, and the noweb references that run a block.
180 static func referencedBlocks(_ block: SrcBlockInfo, _ params: Params, model: DocumentModel, text: NSString, seen: inout Set<Int>) -> [SrcBlockInfo] {
174181 var found: [SrcBlockInfo] = []
175 var seen = seen
176 for value in params.vars.map(\.value) + [params.single[":stdin"]].compactMap({ $0 }) {
177 guard let (block, arguments) = referencedBlock(value, model: model), let name = block.name, seen.insert(name).inserted else { continue }
178 found.append(block)
182 var values = params.vars.map(\.value) + [params.single[":stdin"], params.single[":post"]].compactMap { $0 }
183 if nowebEvaluates(params.single[":noweb"]) {
184 var included: Set<Int> = []
185 values += nowebCalls(block, model: model, text: text, seen: &included)
186 }
187 for value in values {
188 guard let (other, arguments) = referencedBlock(value, model: model), seen.insert(other.range.lowerBound).inserted else { continue }
189 found.append(other)
179190 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
180 if let inner = try? Params(block: block, model: model, text: text, extra: extra) {
181 found += referencedBlocks(inner, model: model, text: text, seen: seen)
191 if let inner = try? Params(block: other, model: model, text: text, extra: extra) {
192 found += referencedBlocks(other, inner, model: model, text: text, seen: &seen)
182193 }
183194 }
184195 return found
@@ -186,13 +197,17 @@ extension Babel {
186197
187198 /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src
188199 /// blocks, which run first (`Needed`) and give their result.
189 static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue {
200 /// `through` names the kind of reference when it leads back to its own block.
201 static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References, through: String = ":var") throws -> VarValue {
190202 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) }
191203 if let n = number(value) { return .number(n) }
192204 if let first = value.first, "('`[".contains(first) { return try lispValue(value) }
193 if let known = refs.resolved[value] { return known }
205 if value == "*this*", let this = refs.this { return this }
206 // A reference that passes `*this*` on has a value for each run `*this*` came from.
207 let key = value.contains("*this*") ? refs.thisKey + value : value
208 if let known = refs.resolved[key] { return known }
194209 if let (block, arguments) = referencedBlock(value, model: model), let name = block.name {
195 guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") }
210 guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through \(through)") }
196211 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
197212 var inner = refs
198213 inner.visiting.insert(name)
@@ -202,7 +217,7 @@ extension Babel {
202217 var useCache = true
203218 if params.single[":cache"] == "yes", let language = block.language {
204219 let tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: text, refs: inner)) }, params: params)
205 let body = nowebEvaluates(params.single[":noweb"]) ? try expandNoweb(block, params: params, model: model, text: text) : normalizedBody(block)
220 let body = nowebEvaluates(params.single[":noweb"]) ? try expandNoweb(block, params: params, model: model, text: text, refs: inner) : normalizedBody(block)
206221 let state = try cacheState(language: language, params: params, tables: tables, body: body, location: block.range, name: name, call: false, text: text, options: refs.options, model: model)
207222 if state.current {
208223 if let value = state.value { return value }
@@ -213,7 +228,8 @@ extension Babel {
213228 options: refs.options, location: block.range, name: name, refs: inner, useCache: useCache) {
214229 case .failure(let failure): throw failure
215230 case .success(let job):
216 throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job))
231 if let posted = job.finish.post, job.needs.isEmpty { return posted }
232 throw Needed(need: job.needs.first ?? BabelJob.Need(reference: key, job: job))
217233 }
218234 }
219235 if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
Sources/OrgCore/Compute/TableSbe.swift +2
@@ -139,6 +139,7 @@ extension Babel {
139139 throw sbeError(failure, text: text)
140140 }
141141 if params.single[":cache"] == "yes" { throw Elisp.Unsupported(what: "org-sbe with :cache") }
142 if params.single[":post"] != nil { throw Elisp.Unsupported(what: "org-sbe with :post") }
142143 var refs = References(resolved: [:], options: options)
143144 refs.visiting = [name]
144145 // The blocks its `:var`s refer to run first, as `DocumentSession.runBabel` runs them.
@@ -149,6 +150,7 @@ extension Babel {
149150 case .success(let job):
150151 if job.needsFile { throw Elisp.Unsupported(what: "org-sbe with Lisp that needs the file's name") }
151152 if let need = job.needs.first {
153 if need.reference.hasPrefix(thisPrefix) { throw Elisp.Unsupported(what: "org-sbe with :post") }
152154 refs.resolved[need.reference] = varValue(need.job.finish, try sbeRun(need.job))
153155 continue
154156 }
Tests/OrgAppTests/AppTests.swift +35
@@ -1034,6 +1034,41 @@ struct NativeProgramsTests {
10341034 #expect(await session.runBabel(js) == "Code block evaluation complete.")
10351035 #expect(session.document?.text.hasSuffix("#+RESULTS:\n: 5\n") == true)
10361036 }
1037
1038 /// A block whose `:post` or noweb reference runs a block that needs a program runs nothing;
1039 /// with blocks that run in-process, the reference's value is the result.
1040 @Test func refusesReferencesToBlocksThatNeedARunner() async throws {
1041 #expect(DocumentSession.runner == nil)
1042 let notes = try Folder()
1043 let helpers = "#+NAME: sh\n#+begin_src sh :var x=\"\"\necho hi\n#+end_src\n\n#+NAME: double\n#+begin_src emacs-lisp :var n=0\n(* 2 n)\n#+end_src\n\n"
1044 let blocks = [
1045 "#+begin_src emacs-lisp :post sh(x=*this*)\n(error \"ran\")\n#+end_src\n",
1046 "#+begin_src emacs-lisp :noweb yes\n(concat \"<<sh()>>\")\n#+end_src\n",
1047 "#+begin_src emacs-lisp :var v=double(n=1) :post sh(x=*this*)\n(error \"ran\")\n#+end_src\n",
1048 "#+begin_src js :post double(n=*this*)\nreturn 2 + 3\n#+end_src\n",
1049 "#+begin_src emacs-lisp :noweb yes\n(+ 1 <<double(n=4)>>)\n#+end_src\n",
1050 ]
1051 var messages: [String] = []
1052 var texts: [String] = []
1053 for block in blocks {
1054 let file = try notes.write("p\(messages.count).org", helpers + block)
1055 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1056 session.open(file.path)
1057 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: helpers.utf16.count + 3, expect: nil) else {
1058 Issue.record("not planned: \(block)")
1059 return
1060 }
1061 messages.append(await session.runBabel(job))
1062 texts.append(String((session.document?.text ?? "").dropFirst(helpers.count + block.count)))
1063 }
1064 #if os(macOS)
1065 let refusal = "This block needs a sh block, and sh blocks don't run in this version of orgstar; nothing was run."
1066 #else
1067 let refusal = "This block needs a sh block, and sh blocks need the Mac to run; nothing was run."
1068 #endif
1069 #expect(messages == [refusal, refusal, refusal, "Code block evaluation complete.", "Code block evaluation complete."])
1070 #expect(texts == ["", "", "", "\n#+RESULTS:\n: 10\n", "\n#+RESULTS:\n: 9\n"])
1071 }
10371072}
10381073
10391074@MainActor
Tests/OrgCoreTests/BabelPostTests.swift added +224
@@ -0,0 +1,224 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// `:post` with `*this*`, and noweb references that run a block.
6struct BabelPostTests {
7 static let helpers = """
8 #+NAME: wrap
9 #+begin_src emacs-lisp :var x="" :var y=">"
10 (format "<%s%s" x y)
11 #+end_src
12
13 #+NAME: double
14 #+begin_src emacs-lisp :var n=0
15 (* 2 n)
16 #+end_src
17
18 #+NAME: bump
19 #+begin_src emacs-lisp :var rows='()
20 (mapcar (lambda (row) (mapcar #'1+ row)) rows)
21 #+end_src
22
23 #+NAME: pair
24 #+begin_src emacs-lisp :var x=""
25 (list (list x (length x)))
26 #+end_src
27
28 #+NAME: twice
29 #+begin_src emacs-lisp :var n=0 :post double(n=*this*)
30 (* 2 n)
31 #+end_src
32
33 #+NAME: said
34 #+begin_src sh :results output :var x=""
35 echo "said $x"
36 #+end_src
37
38 #+NAME: greet
39 #+begin_src sh
40 echo hello
41 #+end_src
42
43 #+NAME: lines
44 #+begin_src sh :results output
45 printf 'a\\nb\\n'
46 #+end_src
47
48 #+NAME: grid
49 #+begin_src emacs-lisp
50 '((1 2) (3 4))
51 #+end_src
52
53 #+NAME: inc
54 #+begin_src sh :noweb yes
55 echo <<double(n=5)>>
56 #+end_src
57
58 #+NAME: drawn
59 #+begin_src sh :results file :file orgstar-post-ref.txt
60 echo drawn
61 #+end_src
62
63
64 """
65
66 /// Each ends with the block to run, which `MAIN` marks.
67 static let cases: [String] = [
68 "#+begin_src sh :post wrap(x=*this*)\necho hello\n#+end_src\n",
69 "#+begin_src sh :post double(n=*this*)\necho 21\n#+end_src\n",
70 "#+begin_src sh :post wrap(x=*this*, y=\"!\")\necho hello\n#+end_src\n",
71 "#+begin_src sh :post bump(rows=*this*)\nprintf '1 2\\n3 4\\n'\n#+end_src\n",
72 "#+begin_src sh :post pair(x=*this*)\necho hello\n#+end_src\n",
73 "#+begin_src sh :post twice(n=*this*)\necho 3\n#+end_src\n",
74 "#+begin_src sh :post said(x=*this*)\necho hello\n#+end_src\n",
75 "#+begin_src sh :post wrap(x=*this*) :results output\necho one; echo two\n#+end_src\n",
76 "#+begin_src sh :post wrap(x=*this*) :results file :file orgstar-post.txt\necho data\n#+end_src\n",
77 "#+begin_src sh :post wrap(x=*this*) :results file drawer :file orgstar-post.txt :file-desc out\necho data\n#+end_src\n",
78 "#+begin_src sh :post wrap(x=*this*) :results file\necho orgstar-post.txt\n#+end_src\n",
79 "#+begin_src sh :post wrap(x=*this*) :results raw\necho hello\n#+end_src\n",
80 "#+begin_src sh :post bump(rows=*this*) :results list\nprintf '1 2\\n3 4\\n'\n#+end_src\n",
81 "#+begin_src sh :post wrap(x=*this*)\necho new\n#+end_src\n\n#+RESULTS:\n: old\n",
82 "#+NAME: main\n#+begin_src sh :post double(n=*this*) :var a=double(n=2)\necho $a\n#+end_src\n",
83 "#+begin_src emacs-lisp :post double(n=*this*) :cache yes\n(+ 1 2)\n#+end_src\n",
84 "#+begin_src sh :post grid\necho gone\n#+end_src\n",
85 "#+begin_src sh :var p=drawn\necho $p\n#+end_src\n",
86 "Text src_sh[:post wrap(x=*this*)]{echo hello} here.\n",
87 "#+CALL: greet() :post wrap(x=*this*)\n",
88 "#+begin_src sh :noweb yes\necho <<double(n=4)>>\n#+end_src\n",
89 "#+begin_src sh :noweb yes\necho <<greet()>> world\n#+end_src\n",
90 "#+begin_src emacs-lisp :noweb yes\n(length '<<grid()>>)\n#+end_src\n",
91 "#+begin_src emacs-lisp :noweb yes\n(format \"%S\" '<<bump(rows=grid)>>)\n#+end_src\n",
92 "#+begin_src sh :noweb yes :results output\n# <<lines()>>\necho done\n#+end_src\n",
93 "#+begin_src sh :noweb yes :noweb-prefix no :results output\necho <<lines()>>\n#+end_src\n",
94 "#+begin_src sh :results output\necho '<<double(n=4)>>'\n#+end_src\n",
95 "#+begin_src sh :noweb eval\necho <<twice(n=2)>>\n#+end_src\n",
96 "#+begin_src sh :noweb tangle :results output\necho '<<double(n=4)>>'\n#+end_src\n",
97 "#+begin_src sh :noweb yes\n<<inc>>\n#+end_src\n",
98 "#+begin_src sh :var v=inc\necho $v\n#+end_src\n",
99 "#+begin_src sh :noweb yes\necho <<drawn()>>\n#+end_src\n",
100 "#+begin_src sh :noweb yes :post double(n=*this*)\necho <<double(n=1)>>\n#+end_src\n",
101 ]
102
103 static func caret(_ text: String) -> Int { helpers.utf16.count + (text.hasPrefix("#+NAME") ? 14 : text.hasPrefix("Text") ? 8 : 2) }
104
105 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
106 func matchesEmacs() throws {
107 let folder = FileManager.default.temporaryDirectory
108 var emacsCases: [EmacsOracle.Case] = []
109 var ours: [(text: String, failure: String?)] = []
110 for last in Self.cases {
111 let text = Self.helpers + last
112 ours.append(try TestBabelRunner.execute(text, caret: Self.caret(last), directory: folder))
113 emacsCases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(Self.caret(last), in: text), form: """
114 (progn
115 (require 'ob-shell)
116 (setq org-confirm-babel-evaluate nil
117 default-directory temporary-file-directory)
118 (org-ctrl-c-ctrl-c))
119 """))
120 }
121 let emacs = try EmacsOracle.run(emacsCases)
122 for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
123 #expect(mine.text == theirs.text && (mine.failure != nil) == !theirs.error.isEmpty,
124 "case \(i):\nours (\(mine.failure ?? "")):\n\(mine.text.dropFirst(Self.helpers.count))\nemacs (\(theirs.error)):\n\(theirs.text.dropFirst(Self.helpers.count))")
125 #expect(mine.text != Self.helpers + Self.cases[i], "case \(i) changed nothing")
126 }
127 }
128
129 /// Emacs Lisp in the interpreter, as on iOS and in the Mac App Store version.
130 @Test func runsInTheInterpreter() throws {
131 let folder = FileManager.default.temporaryDirectory
132 for (last, result) in [
133 ("#+begin_src emacs-lisp :post double(n=*this*)\n(+ 1 2)\n#+end_src\n", "#+RESULTS:\n: 6\n"),
134 ("#+begin_src emacs-lisp :post bump(rows=*this*)\n'((1 2) (3 4))\n#+end_src\n", "#+RESULTS:\n| 2 | 3 |\n| 4 | 5 |\n"),
135 ("#+begin_src emacs-lisp :noweb yes\n(+ 1 <<double(n=4)>>)\n#+end_src\n", "#+RESULTS:\n: 9\n"),
136 ] {
137 let ran = try TestBabelRunner.execute(Self.helpers + last, caret: Self.caret(last), directory: folder, native: true)
138 #expect(ran.failure == nil && ran.text.hasSuffix(result), "\(last)\n\(ran)")
139 }
140 }
141
142 static func plan(_ text: String, at marker: String = "#+begin_src") -> Result<BabelJob, Babel.Failure> {
143 let caret = (text as NSString).range(of: marker, options: .backwards).location + 2
144 return Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]))
145 }
146
147 @Test func refusesBeforeAnythingRuns() {
148 for (text, message) in [
149 ("#+NAME: a\n#+begin_src sh :post a()\necho\n#+end_src\n", "a refers to itself through :post"),
150 ("#+NAME: b\n#+begin_src sh :post a()\necho\n#+end_src\n#+NAME: a\n#+begin_src sh :post b()\necho\n#+end_src\n", "b refers to itself through :post"),
151 ("#+NAME: a\n#+begin_src sh :noweb yes\necho <<a()>>\n#+end_src\n", "a refers to itself through a noweb reference"),
152 ("#+NAME: b\n#+begin_src sh :var x=a\necho\n#+end_src\n#+NAME: a\n#+begin_src sh :noweb yes\necho <<b()>>\n#+end_src\n", "b refers to itself through a noweb reference"),
153 ("#+NAME: off\n#+begin_src sh :eval never\necho\n#+end_src\n#+begin_src sh :post off(x=*this*)\necho\n#+end_src\n",
154 "Evaluation of this sh code block (off) is disabled."),
155 ("#+NAME: off\n#+begin_src sh :eval never\necho\n#+end_src\n#+begin_src sh :noweb yes\necho <<off()>>\n#+end_src\n",
156 "Evaluation of this sh code block (off) is disabled."),
157 ("#+NAME: off\n#+begin_src sh :eval never\necho\n#+end_src\n#+NAME: gen\n#+begin_src sh\necho\n#+end_src\n#+begin_src sh :var v=gen :post off(x=*this*)\necho\n#+end_src\n",
158 "Evaluation of this sh code block (off) is disabled."),
159 ("#+begin_src sh :post missing(x=*this*)\necho\n#+end_src\n", "References like missing(x=*this*) aren't supported yet."),
160 ("#+begin_src sh :noweb yes\necho <<missing()>>\n#+end_src\n", "References like missing() aren't supported yet."),
161 ("#+NAME: other\n#+begin_src cobol\nDISPLAY\n#+end_src\n#+begin_src sh :post other()\necho\n#+end_src\n", "No way to run cobol blocks yet."),
162 ] {
163 guard case .failure(.message(let got)) = Self.plan(text) else {
164 Issue.record("planned: \(text)")
165 continue
166 }
167 #expect(got == message)
168 }
169 }
170
171 /// The trust prompt covers the block and every block its `:post` and noweb references run.
172 @Test func asksOnceForEveryBlockReached() throws {
173 let post = "#+NAME: p\n#+begin_src sh :var x=\"\" :noweb yes\necho <<q()>>\n#+end_src\n#+NAME: q\n#+begin_src sh\necho q\n#+end_src\n"
174 + "#+NAME: inc\n#+begin_src sh :noweb yes\necho <<r()>>\n#+end_src\n#+NAME: r\n#+begin_src sh :eval query\necho r\n#+end_src\n"
175 for main in ["#+begin_src sh :post p(x=*this*)\necho main\n#+end_src\n", "#+begin_src sh :noweb yes\necho <<p()>>\n#+end_src\n"] {
176 guard case .success(let job) = Self.plan(post + main), let need = job.needs.first else {
177 Issue.record("not planned: \(main)")
178 continue
179 }
180 #expect(job.approved.count == 3 && job.approved.contains(need.job.blockText) && job.referenced == ["sh", "sh"])
181 #expect(job.blockText.contains("echo main") || job.blockText.contains("echo <<p()>>"))
182 #expect(job.blockText.contains("echo <<q()>>") && job.blockText.contains("echo q") && !job.alwaysAsk)
183 }
184 // Through a reference that brings a body in, and `:eval query` on the block it runs.
185 guard case .success(let job) = Self.plan(post + "#+begin_src sh :noweb yes\n<<inc>>\n#+end_src\n") else {
186 Issue.record("not planned")
187 return
188 }
189 #expect(job.alwaysAsk && job.approved.count == 2 && job.blockText.contains("echo r"))
190 }
191
192 /// The block runs before its `:post` reference, which gets its result; a block that isn't
193 /// among those agreed to is not handed back as the next to run.
194 @Test func runsTheBlockThenItsPost() throws {
195 let text = Self.helpers + "#+begin_src sh :post double(n=*this*)\necho 21\n#+end_src\n"
196 let tree = OrgParser.parse(text)
197 guard case .success(let first) = Self.plan(text), let main = first.needs.first else {
198 Issue.record("not planned")
199 return
200 }
201 #expect(first.known == nil && main.job.input.contains("echo 21"))
202 guard case .success(let second) = Babel.resume(first, need: main, output: BabelOutput(stdout: "21\n"), text: text, tree: tree),
203 let post = second.needs.first else {
204 Issue.record("not resumed")
205 return
206 }
207 #expect(post.job.lispForm?.contains("(n '21)") == true && first.approved.contains(post.job.blockText))
208 let output = BabelOutput(stdout: #"{"s":"42","S":"42","string":false,"rows":null}"#)
209 guard case .success(let last) = Babel.resume(second, need: post, output: output, text: text, tree: tree) else {
210 Issue.record("not resumed")
211 return
212 }
213 #expect(last.needs.isEmpty && last.known == BabelOutput(stdout: "42") && first.approved.contains(last.blockText))
214 }
215
216 @Test func tanglingRefusesAReferenceThatRuns() throws {
217 let text = Self.helpers + "#+begin_src sh :noweb yes :tangle out.sh\necho <<double(n=4)>>\n#+end_src\n"
218 let model = DocumentModel(tree: OrgParser.parse(text))
219 let block = model.srcBlocks.last!
220 #expect(throws: Babel.Failure.message("The noweb reference <<double(n=4)>> would run a block while tangling, which isn't supported yet; nothing was tangled.")) {
221 try Babel.expandNoweb(block, params: try Babel.Params(block: block, model: model, text: text as NSString), model: model, text: text as NSString, tangling: true)
222 }
223 }
224}
Tests/OrgCoreTests/BabelTests.swift +6 −2
@@ -55,6 +55,7 @@ enum TestBabelRunner {
5555 /// `native` runs Emacs Lisp blocks with `Babel.evaluateNatively` instead of Emacs.
5656 static func execute(_ text: String, caret: Int, directory: URL, native: Bool = false) throws -> (text: String, failure: String?) {
5757 func run(_ job: BabelJob, directory: URL) throws -> BabelOutput {
58 if let output = job.known { return output }
5859 guard native else { return try TestBabelRunner.run(job, directory: directory) }
5960 if job.calc != nil { return try Babel.evaluateCalc(job) }
6061 guard let output = try Babel.evaluateNatively(job) else { throw NativeUnsupported() }
@@ -65,7 +66,11 @@ enum TestBabelRunner {
6566 case .failure(.message(let message)): return (text, message)
6667 case .success(var job):
6768 while let need = job.needs.first {
68 switch Babel.resume(job, need: need, output: try run(need.job, directory: directory), text: text, tree: context.tree) {
69 let output = try run(need.job, directory: directory)
70 if let file = Babel.fileResult(need.job, output: output) {
71 try file.contents.write(to: directory.appendingPathComponent(file.path), atomically: true, encoding: .utf8)
72 }
73 switch Babel.resume(job, need: need, output: output, text: text, tree: context.tree) {
6974 case .failure(.message(let message)): return (text, message)
7075 case .success(let next): job = next
7176 }
@@ -405,7 +410,6 @@ struct BabelTests {
405410 for (text, message) in [
406411 ("#+begin_src sh :eval never\necho\n#+end_src\n", "Evaluation of this sh code block is disabled."),
407412 ("#+begin_src awk :session s\nBEGIN { print 1 }\n#+end_src\n", ":session isn't supported for awk yet; nothing was run."),
408 ("#+begin_src sh :noweb yes\n<<x()>>\n#+end_src\n", "Noweb references that run a block (x()) aren't supported yet; nothing was run."),
409413 ("#+begin_src python :cmdline -x\nreturn 1\n#+end_src\n", ":cmdline isn't supported for python yet; nothing was run."),
410414 ("#+begin_src cobol\nDISPLAY\n#+end_src\n", "No way to run cobol blocks yet."),
411415 ("#+begin_src sh :var x=loop\necho\n#+end_src\n#+NAME: loop\n#+begin_src sh :var y=loop\necho\n#+end_src\n", "loop refers to itself through :var"),
docs/manual/guide/11-code-blocks.org +59 −4
@@ -395,6 +395,7 @@ A string or number takes the place of the form. Lisp that the interpreter cannot
395395| =:return= | expression | Python: the value to return. |
396396| =:cache= | =yes=, =no= | Skip the run when the result is current (see Caching below). |
397397| =:eval= | =never=, =no=, =query=, … | Whether and how to ask before running (see =:eval= above). |
398| =:post= | =name(arg=*this*)= | Passes the result through another block (see Post-processing below). |
398399| =:noweb= | see Noweb below | Expands =<<name>>= references. |
399400| =:noweb-ref= | name | Makes the block part of =<<name>>=. |
400401| =:noweb-sep= | text | Separator between blocks joined under one =:noweb-ref=; a newline by default. |
@@ -409,7 +410,6 @@ orgstar does not run a block whose arguments it would handle differently from Em
409410| Argument | Refused for | Message |
410411|-----------------------------+-------------------------------------------------+----------------------------------------------------------|
411412| =:prologue=, =:epilogue= | graphics (=dot=, =plantuml=, =mermaid=) | "=:prologue= isn't supported yet; nothing was run." |
412| =:post= | every language | "=:post= isn't supported yet; nothing was run." |
413413| =:stdin=, =:shebang= | languages other than shells | "=:stdin= isn't supported yet; nothing was run." |
414414| =:cmdline= | languages other than shells, graphics and the compiled languages | "=:cmdline= isn't supported for /language/ yet; nothing was run." |
415415| =:session= | =awk=, =calc=, =sqlite=, graphics and Emacs Lisp; the compiled languages ignore it | "=:session= isn't supported for /language/ yet; nothing was run." |
@@ -437,7 +437,9 @@ return [[c * scale for c in row] for row in t]
437437,#+end_src
438438#+END_SRC
439439
440A referenced block runs before the block that refers to it, after the one trust prompt that covers them all. A block with =:cache yes= and a current result gives that result without running. A chain that leads back to itself is refused with "/name/ refers to itself through :var".
440A referenced block runs before the block that refers to it, after the one trust prompt that covers them all. A block with =:cache yes= and a current result gives that result without running. A chain that leads back to itself is refused with "/name/ refers to itself through :var"; a chain through =:post= or a noweb reference names that instead.
441
442A referenced block with =:results file= gives the name of its =:file=, or without =:file= its result as text. The file is written when the block runs.
441443
442444These are not supported and are refused:
443445
@@ -537,6 +539,36 @@ Change the block or its arguments and it runs again. Results inserted with =appe
537539
538540The hash of a C, C++, D, Java, Fortran or Clojure block is taken over the body as the language expands it (see Tangling below), with the =IMPORTS=, =INCLUDES= and =DEFINES= properties where the block is, and Java's default header arguments, as Emacs does. A result Emacs wrote for such a block with =:cache yes= is recognised as current, and =C-c C-c= shows it.
539541
542* Post-processing
543
544=:post= names a reference that is resolved after the block has run (=org-babel-execute-src-block=). The block's result is bound to =*this*=, and the value of the reference becomes the block's result. The reference is usually a call to a named block that takes =*this*= as an argument; it can pass other arguments as well.
545
546#+BEGIN_SRC org
547,#+NAME: total
548,#+begin_src emacs-lisp :var rows='()
549(append rows (list 'hline (list "sum" (apply #'+ (mapcar #'cadr rows)))))
550,#+end_src
551
552,#+begin_src sh :post total(rows=*this*)
553printf 'a 1\nb 2\n'
554,#+end_src
555
556,#+RESULTS:
557| a | 1 |
558| b | 2 |
559|-----+---|
560| sum | 3 |
561#+END_SRC
562
563- =*this*= is the result as a =:var= would get it: a string, a number or a table.
564- With =:results file= and =:file=, the file is written first and =*this*= is the link to it, with its =:file-desc=. The value of the reference then goes in as text, not as a link; use =:results drawer= or =raw= when it is Org markup, such as an =#+ATTR_= line above the link. With =:results file= and no =:file=, =*this*= is the result as text, and the value of the reference becomes the link.
565- The value is inserted according to the block's own =:results=.
566- The block that =:post= calls can have its own =:post=, and =:var= references in it can use =*this*=.
567- With =:cache yes= and a current result, neither the block nor the reference runs.
568- =#+CALL:= lines, inline calls and inline source blocks take =:post= too.
569
570The one trust prompt covers the block and every block the reference runs, and asks every time when any of them has =:eval query=. Before anything runs, orgstar resolves the reference with an empty =*this*=; when that fails, the message says why and nothing runs. That covers a name that isn't a block in the file, a block with =:eval never=, a language orgstar can't run, and a reference that leads back to its own block ("/name/ refers to itself through :post").
571
540572* Noweb
541573
542574A noweb reference =<<name>>= in a block's body stands for other code. Whether references expand depends on =:noweb= and on what is happening:
@@ -575,7 +607,29 @@ echo world
575607,#+end_src
576608#+END_SRC
577609
578A reference that runs a block, =<<name()>>=, is refused: "Noweb references that run a block (…) aren't supported yet; nothing was run."
610** References that run a block
611
612=<<name()>>= stands for the result of the block named =name=, which runs first, and =<<name(arg=value)>>= runs it with arguments, as =:var x=name(arg=value)= does (=org-babel-ref-resolve=). A result that is a string goes in as it is; a number, list or table goes in as Emacs Lisp prints it, such as =42= or =((1 2) (3 4))=. Text before the reference is repeated before each line of a result of several lines, unless =:noweb-prefix no=.
613
614#+BEGIN_SRC org
615,#+NAME: port
616,#+begin_src emacs-lisp :var base=8000
617(+ base 80)
618,#+end_src
619
620,#+begin_src sh :noweb yes
621echo "listening on <<port(base=3000)>>"
622,#+end_src
623
624,#+RESULTS:
625: listening on 3080
626#+END_SRC
627
628These references expand when the others do for running: with =:noweb= =yes=, =eval=, =no-export=, =strip-export= or =strip-tangle=. With =no= or =tangle=, the text stays as written and nothing runs. A block brought in by =<<name>>= has its own references run in the same way, according to its own =:noweb=.
629
630The rules for =:var= references apply: one trust prompt covers every block that would run, a referenced block with =:cache yes= and a current result gives that result without running, =:eval never= on a referenced block stops the run, and a reference that leads back to its own block is refused with "/name/ refers to itself through a noweb reference".
631
632Export shows these references as written and runs nothing. Tangling does not run blocks; see What tangling refuses below.
579633
580634* Calls
581635
@@ -796,6 +850,7 @@ Comments need the language's comment syntax. orgstar knows it for: =emacs-lisp=,
796850Tangling stops, writes nothing and says why when:
797851
798852- =:var= refers to a source block, which would have to run: "would run a block while tangling".
853- A noweb reference runs a block, =<<name()>>=, in a block whose =:noweb= expands when tangling: "The noweb reference <<…>> would run a block while tangling, which isn't supported yet; nothing was tangled."
799854- A shell block's =:var= is a table or list.
800855- =:var= is used in a language other than shells, Python, Emacs Lisp, C, C++, D, Java, Fortran and Clojure.
801856- A C, C++, D or Fortran block's =:var= table keeps rules (with =:hlines yes=), or a value has no type the language takes.
@@ -816,7 +871,7 @@ See [[file:14-ios.org][iOS]] for the rest of the iOS app.
816871
817872* In the Mac App Store version
818873
819- Only Emacs Lisp blocks, in the same interpreter as on iOS, JavaScript blocks, in JavaScriptCore, and calc, sqlite, dot and mermaid blocks run. Any other language, compiled languages included, fails with "/language/ blocks don't run in this version of orgstar."
874- Only Emacs Lisp blocks, in the same interpreter as on iOS, JavaScript blocks, in JavaScriptCore, and calc, sqlite, dot and mermaid blocks run. Any other language, compiled languages included, fails with "/language/ blocks don't run in this version of orgstar." A block whose =:var=, =:post= or noweb reference runs a block in another language runs nothing: "This block needs a /language/ block, and /language/ blocks don't run in this version of orgstar; nothing was run."
820875- JavaScript blocks can use =:session=. There are no other sessions, and no graphics other than dot and mermaid.
821876- The trust prompt works the same way.
822877- 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 +1
@@ -348,6 +348,7 @@ Publishing works from Commands as on the Mac, with the =[[publish]]= projects in
348348On iOS, only Emacs Lisp, JavaScript, calc, sqlite, dot and mermaid 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, sqlite with the SQLite library, as =sqlite3= would, and dot and mermaid with Graphviz and mermaid built in, as SVG or PNG; see [[file:11-code-blocks.org][Code blocks]]. Other results:
349349
350350- A block in another language: "/language/ blocks need the Mac to run."
351- A block whose =:var=, =:post= or noweb reference runs a block in another language: "This block needs a /language/ block, and /language/ blocks need the Mac to run; nothing was run."
351352- Emacs Lisp the interpreter doesn't have: "This block uses Emacs Lisp that runs only in Emacs, on the Mac."
352353- JavaScript that uses something only node has, such as =Buffer=: "This block uses /name/, which runs only in node."
353354- 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/."
docs/manual/guide/15-alongside-emacs.org +6 −4
@@ -215,14 +215,16 @@ orgstar refuses some things with a message rather than doing something different
215215Code blocks (see [[file:11-code-blocks.org][Code blocks]]):
216216
217217- =:cmdline= is supported only for shells, =dot=, =plantuml=, =mermaid= and C, C++, D, Java, Fortran and Clojure.
218- =:post= isn't supported; =:prologue= and =:epilogue= aren't for =dot=, =plantuml= and =mermaid=; =:stdin= and =:shebang= only for shells.
218- =:prologue= and =:epilogue= aren't supported for =dot=, =plantuml= and =mermaid=; =:stdin= and =:shebang= only for shells.
219- =:post= and noweb references that run a block (=<<name()>>=) take a block in the same file, as =name= or =name(arg=value)=. =name[header arguments](…)=, an index such as =name()[0]=, and blocks in other files or the Library of Babel are refused: "References like … aren't supported yet."
220- A =:post= reference is resolved once with an empty =*this*= before the block runs, so one that can't be resolved stops the run before it starts; Org runs the block and then fails.
221- =org-sbe= in a table formula doesn't run a block that has =:post=; on the Mac download version the table is recalculated in Emacs.
219222- =:session= is supported only for shells, Python, Ruby, JavaScript and R; on iOS and in the Mac App Store version, only for JavaScript. C, C++, D, Java, Fortran and Clojure ignore it, as in Org.
220223- Clojure runs with babashka or the Clojure CLI only; other =:backend= values are refused.
221224- R blocks return their standard output, whatever =:results= says; ob-R returns the value with =:results value=.
222225- Header arguments, =:var= values and =:cache= that need Lisp evaluated by Emacs are refused when orgstar's interpreter can't evaluate them: "… is Lisp that only Emacs can evaluate; nothing was run."
223- Noweb references that run a block aren't supported.
224- Tangling refuses =:var= that would run a block, tables and lists in a shell block's =:var=, and =:var= in languages other than shells, Python, Emacs Lisp, C, C++, D, Java, Fortran and Clojure.
225- On iOS and in the Mac App Store version, only Emacs Lisp, JavaScript, calc, sqlite, dot and mermaid blocks run: Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore.
226- Tangling refuses =:var= and noweb references that would run a block, tables and lists in a shell block's =:var=, and =:var= in languages other than shells, Python, Emacs Lisp, C, C++, D, Java, Fortran and Clojure.
227- On iOS and in the Mac App Store version, only Emacs Lisp, JavaScript, calc, sqlite, dot and mermaid blocks run: Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore. A block whose =:var=, =:post= or noweb reference runs a block in another language runs nothing.
226228
227229Links (see [[file:09-links.org][Links]]):
228230