Commit dd764a1db9
Verified · cmc
Layout: unified · split
Sources/OrgApp/DocumentSession.swift +25 −9
| @@ -925,6 +925,7 @@ public final class DocumentSession { | ||
| 925 | 925 | /// A program through `programs`; without it, Emacs Lisp in `Elisp` and js in |
| 926 | 926 | /// JavaScriptCore, and nothing else. |
| 927 | 927 | func run(_ job: BabelJob) async throws -> BabelOutput { |
| 928 | if let output = job.known { return output } | |
| 928 | 929 | if let programs { return try await programs.runBabel(job, fileDirectory: directory) } |
| 929 | 930 | #if canImport(JavaScriptCore) |
| 930 | 931 | if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output } |
| @@ -949,8 +950,26 @@ public final class DocumentSession { | ||
| 949 | 950 | } |
| 950 | 951 | return output |
| 951 | 952 | } |
| 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 | } | |
| 952 | 971 | 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. | |
| 954 | 973 | // Each is one of the blocks agreed to, or the run stops: the text may have changed |
| 955 | 974 | // while a block ran. |
| 956 | 975 | var job = job |
| @@ -967,6 +986,7 @@ public final class DocumentSession { | ||
| 967 | 986 | guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." } |
| 968 | 987 | let output = try await run(need.job) |
| 969 | 988 | 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 } | |
| 970 | 990 | let document = entry.buffer.document |
| 971 | 991 | switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) { |
| 972 | 992 | case .failure(.message(let message)): return message |
| @@ -976,14 +996,7 @@ public final class DocumentSession { | ||
| 976 | 996 | guard agreed(job) else { return "The blocks changed while running; nothing more was run." } |
| 977 | 997 | let output = try await run(job) |
| 978 | 998 | 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 } | |
| 987 | 1000 | let current = entry.buffer |
| 988 | 1001 | let document = current.document |
| 989 | 1002 | let done = output.problem ?? "Code block evaluation complete." |
| @@ -1006,6 +1019,9 @@ public final class DocumentSession { | ||
| 1006 | 1019 | } |
| 1007 | 1020 | } |
| 1008 | 1021 | |
| 1022 | /// The languages that run without programs. | |
| 1023 | static let inProcess: Set<String> = ["emacs-lisp", "elisp", "js", "javascript", "calc", "sqlite", "dot", "mermaid"] | |
| 1024 | ||
| 1009 | 1025 | /// Where a block's `:file` result goes: relative to `:dir`, itself relative to `directory`. |
| 1010 | 1026 | static func resultFile(_ name: String, job: BabelJob, directory: URL) -> URL { |
| 1011 | 1027 | 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 { | ||
| 34 | 34 | public let blockText: String |
| 35 | 35 | /// Asks every time (`:eval query`) rather than trusting by content. |
| 36 | 36 | public let alwaysAsk: Bool |
| 37 | public let finish: Finish | |
| 37 | public internal(set) var finish: Finish | |
| 38 | 38 | /// A named block a `:var` refers to: run it first, then `Babel.resume` with its output. |
| 39 | 39 | public var needs: [Need] = [] |
| 40 | 40 | /// 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 { | ||
| 61 | 61 | public internal(set) var diagram: Babel.Diagram? |
| 62 | 62 | /// Files the runner writes, each where its key stands in `input`: `:var` tables as CSV. |
| 63 | 63 | 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)) } } | |
| 64 | 68 | |
| 65 | 69 | public struct Need: Sendable, Equatable { |
| 66 | 70 | /// The `:var` value, `name` or `name(args)`. |
| @@ -105,6 +109,10 @@ public struct BabelJob: Sendable, Equatable { | ||
| 105 | 109 | /// (`org-babel-reassemble-table`). |
| 106 | 110 | var colnames: [String]? |
| 107 | 111 | 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 } | |
| 108 | 116 | } |
| 109 | 117 | } |
| 110 | 118 | |
| @@ -165,7 +173,7 @@ public enum Babel { | ||
| 165 | 173 | /// `need.job`, as `org-babel-ref-resolve` reads it. |
| 166 | 174 | public static func resume(_ job: BabelJob, need: BabelJob.Need, output: BabelOutput, text: String, tree: OrgTree) -> Result<BabelJob, Failure> { |
| 167 | 175 | 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)) | |
| 169 | 177 | let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret]) |
| 170 | 178 | return plan(context, options: job.options, resolved: resolved) |
| 171 | 179 | } |
| @@ -344,8 +352,15 @@ public enum Babel { | ||
| 344 | 352 | var options: Options |
| 345 | 353 | /// Blocks being planned for a reference, to stop cycles. |
| 346 | 354 | 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 = "" | |
| 347 | 359 | } |
| 348 | 360 | |
| 361 | /// Starts the key in `References.resolved` of a block's result before its `:post`. | |
| 362 | static let thisPrefix = "*this*\u{1}" | |
| 363 | ||
| 349 | 364 | /// A reference to a block that has to run first. |
| 350 | 365 | struct Needed: Error { |
| 351 | 366 | let need: BabelJob.Need |
| @@ -357,13 +372,65 @@ public enum Babel { | ||
| 357 | 372 | evaluated.evaluateLisp(file: options.file) |
| 358 | 373 | let needsFile = options.file == nil && evaluated.lisp.contains { evaluated.evaluated[$0] == nil } |
| 359 | 374 | 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 | |
| 361 | 379 | var job = job |
| 362 | 380 | job.needsFile = needsFile |
| 363 | 381 | return job |
| 364 | 382 | } |
| 365 | 383 | } |
| 366 | 384 | |
| 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 | ||
| 367 | 434 | static func planBlock(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options, |
| 368 | 435 | location: Range<Int>, name: String?, inline: Bool, refs: References?, useCache: Bool) -> Result<BabelJob, Failure> { |
| 369 | 436 | let refs = refs ?? References(resolved: [:], options: options) |
| @@ -380,7 +447,7 @@ public enum Babel { | ||
| 380 | 447 | return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run.")) |
| 381 | 448 | } |
| 382 | 449 | 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 | |
| 384 | 451 | && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) { |
| 385 | 452 | return .failure(.message("\(key) isn't supported yet; nothing was run.")) |
| 386 | 453 | } |
| @@ -390,15 +457,6 @@ public enum Babel { | ||
| 390 | 457 | return .failure(.message(":session isn't supported for \(language) yet; nothing was run.")) |
| 391 | 458 | } |
| 392 | 459 | 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 | } | |
| 402 | 460 | let output = params.results.contains("output") |
| 403 | 461 | let file = params.single[":file"].map { name in |
| 404 | 462 | params.single[":output-dir"].map { $0.hasSuffix("/") ? $0 + name : $0 + "/" + name } ?? name |
| @@ -414,21 +472,13 @@ public enum Babel { | ||
| 414 | 472 | let vars: [(String, VarValue)] |
| 415 | 473 | var stdin: VarValue? |
| 416 | 474 | do { |
| 475 | if nowebEvaluates(params.single[":noweb"]) { body = try expandNoweb(block, params: params, model: model, text: ns, refs: refs) } | |
| 417 | 476 | tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns, refs: refs)) }, params: params) |
| 418 | 477 | vars = tables.vars |
| 419 | 478 | stdin = try params.single[":stdin"].map { try resolve($0, model: model, text: ns, refs: refs) } |
| 420 | 479 | } 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)) | |
| 432 | 482 | } catch let error as Failure { |
| 433 | 483 | return .failure(error) |
| 434 | 484 | } catch { |
Sources/OrgCore/Compute/BabelNoweb.swift +38 −5
| @@ -20,8 +20,11 @@ extension Babel { | ||
| 20 | 20 | /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as |
| 21 | 21 | /// evaluation does. |
| 22 | 22 | /// `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. | |
| 23 | 26 | 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 { | |
| 25 | 28 | guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") } |
| 26 | 29 | let body = normalizedBody(block) |
| 27 | 30 | let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true |
| @@ -30,7 +33,7 @@ extension Babel { | ||
| 30 | 33 | let otherParams = try Params(block: other, model: model, text: text) |
| 31 | 34 | let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"]) |
| 32 | 35 | 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) | |
| 34 | 37 | : normalizedBody(other) |
| 35 | 38 | guard commenting, let links else { return b } |
| 36 | 39 | // `c-wrap`: commented in this block's language, trimmed. |
| @@ -49,18 +52,24 @@ extension Babel { | ||
| 49 | 52 | guard let h = b.heading else { return false } |
| 50 | 53 | return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") } |
| 51 | 54 | } |
| 52 | let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)") | |
| 53 | 55 | let ns = body as NSString |
| 54 | 56 | var out = "" |
| 55 | 57 | 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)) { | |
| 57 | 59 | let prefix = ns.substring(with: m.range(at: 1)) |
| 58 | 60 | let id = ns.substring(with: m.range(at: 3)) |
| 59 | 61 | out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at)) |
| 60 | 62 | at = NSMaxRange(m.range) |
| 61 | 63 | var expansion = "" |
| 62 | 64 | 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 | } | |
| 64 | 73 | } else if let heading = model.headings.firstIndex(where: { h in |
| 65 | 74 | h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) } |
| 66 | 75 | }) { |
| @@ -86,6 +95,30 @@ extension Babel { | ||
| 86 | 95 | return out + ns.substring(from: at) |
| 87 | 96 | } |
| 88 | 97 | |
| 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 | ||
| 89 | 122 | /// `org-babel-ref-headline-body`: the entry after its planning and drawers. |
| 90 | 123 | static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String { |
| 91 | 124 | let heading = model.headings[index] |
Sources/OrgCore/Compute/BabelResults.swift +11 −3
| @@ -43,6 +43,14 @@ extension Babel { | ||
| 43 | 43 | |
| 44 | 44 | /// The language's result handling: `org-babel-result-cond` and the table import. |
| 45 | 45 | 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 | } | |
| 46 | 54 | let value = reassemble(rawValue(finish, output), finish) |
| 47 | 55 | switch (finish.kind, value) { |
| 48 | 56 | case (.calc, .string(let s)), (.sqlite, .string(let s)): |
| @@ -58,7 +66,7 @@ extension Babel { | ||
| 58 | 66 | let params = finish.params |
| 59 | 67 | if params.contains("file") { |
| 60 | 68 | // `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) | |
| 62 | 70 | var link = "[[file:" + path + "]" |
| 63 | 71 | if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" } |
| 64 | 72 | return .string(link + "]") |
| @@ -442,7 +450,7 @@ extension Babel { | ||
| 442 | 450 | switch value { |
| 443 | 451 | case .none: |
| 444 | 452 | break |
| 445 | case .string(let s) where params.contains("list") && finish.kind.givesRows: | |
| 453 | case .string(let s) where params.contains("list") && finish.givesRows: | |
| 446 | 454 | // `split-string` without empty lines, each an item; `org-trim` of the list. |
| 447 | 455 | var items = s.components(separatedBy: "\n").filter { !$0.isEmpty }.map { "- " + $0 }.joined(separator: "\n") |
| 448 | 456 | while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() } |
| @@ -451,7 +459,7 @@ extension Babel { | ||
| 451 | 459 | if s.last != "\n" { s += "\n" } |
| 452 | 460 | let items = s.split(separator: "\n", omittingEmptySubsequences: true) |
| 453 | 461 | 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: | |
| 455 | 463 | // Each row an item, its first cell the text and the others lines under it. |
| 456 | 464 | listed = true |
| 457 | 465 | var items = rows.map { row in |
Sources/OrgCore/Compute/BabelVars.swift +31 −15
| @@ -111,8 +111,14 @@ extension Babel { | ||
| 111 | 111 | |
| 112 | 112 | // MARK: - Variables |
| 113 | 113 | |
| 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 | } | |
| 116 | 122 | switch value(finish, output) { |
| 117 | 123 | case .none: return .scalar("") |
| 118 | 124 | case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s) |
| @@ -169,16 +175,21 @@ extension Babel { | ||
| 169 | 175 | return (block, m.2.map(String.init)) |
| 170 | 176 | } |
| 171 | 177 | |
| 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] { | |
| 174 | 181 | 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) | |
| 179 | 190 | 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) | |
| 182 | 193 | } |
| 183 | 194 | } |
| 184 | 195 | return found |
| @@ -186,13 +197,17 @@ extension Babel { | ||
| 186 | 197 | |
| 187 | 198 | /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src |
| 188 | 199 | /// 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 { | |
| 190 | 202 | if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) } |
| 191 | 203 | if let n = number(value) { return .number(n) } |
| 192 | 204 | 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 } | |
| 194 | 209 | 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)") } | |
| 196 | 211 | let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? [] |
| 197 | 212 | var inner = refs |
| 198 | 213 | inner.visiting.insert(name) |
| @@ -202,7 +217,7 @@ extension Babel { | ||
| 202 | 217 | var useCache = true |
| 203 | 218 | if params.single[":cache"] == "yes", let language = block.language { |
| 204 | 219 | 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) | |
| 206 | 221 | 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) |
| 207 | 222 | if state.current { |
| 208 | 223 | if let value = state.value { return value } |
| @@ -213,7 +228,8 @@ extension Babel { | ||
| 213 | 228 | options: refs.options, location: block.range, name: name, refs: inner, useCache: useCache) { |
| 214 | 229 | case .failure(let failure): throw failure |
| 215 | 230 | 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)) | |
| 217 | 233 | } |
| 218 | 234 | } |
| 219 | 235 | 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 { | ||
| 139 | 139 | throw sbeError(failure, text: text) |
| 140 | 140 | } |
| 141 | 141 | 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") } | |
| 142 | 143 | var refs = References(resolved: [:], options: options) |
| 143 | 144 | refs.visiting = [name] |
| 144 | 145 | // The blocks its `:var`s refer to run first, as `DocumentSession.runBabel` runs them. |
| @@ -149,6 +150,7 @@ extension Babel { | ||
| 149 | 150 | case .success(let job): |
| 150 | 151 | if job.needsFile { throw Elisp.Unsupported(what: "org-sbe with Lisp that needs the file's name") } |
| 151 | 152 | if let need = job.needs.first { |
| 153 | if need.reference.hasPrefix(thisPrefix) { throw Elisp.Unsupported(what: "org-sbe with :post") } | |
| 152 | 154 | refs.resolved[need.reference] = varValue(need.job.finish, try sbeRun(need.job)) |
| 153 | 155 | continue |
| 154 | 156 | } |
Tests/OrgAppTests/AppTests.swift +35
| @@ -1034,6 +1034,41 @@ struct NativeProgramsTests { | ||
| 1034 | 1034 | #expect(await session.runBabel(js) == "Code block evaluation complete.") |
| 1035 | 1035 | #expect(session.document?.text.hasSuffix("#+RESULTS:\n: 5\n") == true) |
| 1036 | 1036 | } |
| 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 | } | |
| 1037 | 1072 | } |
| 1038 | 1073 | |
| 1039 | 1074 | @MainActor |
Tests/OrgCoreTests/BabelPostTests.swift added +224
| @@ -0,0 +1,224 @@ | ||
| 1 | import Foundation | |
| 2 | import Testing | |
| 3 | @testable import OrgCore | |
| 4 | ||
| 5 | /// `:post` with `*this*`, and noweb references that run a block. | |
| 6 | struct 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 { | ||
| 55 | 55 | /// `native` runs Emacs Lisp blocks with `Babel.evaluateNatively` instead of Emacs. |
| 56 | 56 | static func execute(_ text: String, caret: Int, directory: URL, native: Bool = false) throws -> (text: String, failure: String?) { |
| 57 | 57 | func run(_ job: BabelJob, directory: URL) throws -> BabelOutput { |
| 58 | if let output = job.known { return output } | |
| 58 | 59 | guard native else { return try TestBabelRunner.run(job, directory: directory) } |
| 59 | 60 | if job.calc != nil { return try Babel.evaluateCalc(job) } |
| 60 | 61 | guard let output = try Babel.evaluateNatively(job) else { throw NativeUnsupported() } |
| @@ -65,7 +66,11 @@ enum TestBabelRunner { | ||
| 65 | 66 | case .failure(.message(let message)): return (text, message) |
| 66 | 67 | case .success(var job): |
| 67 | 68 | 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) { | |
| 69 | 74 | case .failure(.message(let message)): return (text, message) |
| 70 | 75 | case .success(let next): job = next |
| 71 | 76 | } |
| @@ -405,7 +410,6 @@ struct BabelTests { | ||
| 405 | 410 | for (text, message) in [ |
| 406 | 411 | ("#+begin_src sh :eval never\necho\n#+end_src\n", "Evaluation of this sh code block is disabled."), |
| 407 | 412 | ("#+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."), | |
| 409 | 413 | ("#+begin_src python :cmdline -x\nreturn 1\n#+end_src\n", ":cmdline isn't supported for python yet; nothing was run."), |
| 410 | 414 | ("#+begin_src cobol\nDISPLAY\n#+end_src\n", "No way to run cobol blocks yet."), |
| 411 | 415 | ("#+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 | ||
| 395 | 395 | | =:return= | expression | Python: the value to return. | |
| 396 | 396 | | =:cache= | =yes=, =no= | Skip the run when the result is current (see Caching below). | |
| 397 | 397 | | =: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). | | |
| 398 | 399 | | =:noweb= | see Noweb below | Expands =<<name>>= references. | |
| 399 | 400 | | =:noweb-ref= | name | Makes the block part of =<<name>>=. | |
| 400 | 401 | | =: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 | ||
| 409 | 410 | | Argument | Refused for | Message | |
| 410 | 411 | |-----------------------------+-------------------------------------------------+----------------------------------------------------------| |
| 411 | 412 | | =: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." | | |
| 413 | 413 | | =:stdin=, =:shebang= | languages other than shells | "=:stdin= isn't supported yet; nothing was run." | |
| 414 | 414 | | =:cmdline= | languages other than shells, graphics and the compiled languages | "=:cmdline= isn't supported for /language/ yet; nothing was run." | |
| 415 | 415 | | =: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] | ||
| 437 | 437 | ,#+end_src |
| 438 | 438 | #+END_SRC |
| 439 | 439 | |
| 440 | A 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". | |
| 440 | A 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 | ||
| 442 | A 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. | |
| 441 | 443 | |
| 442 | 444 | These are not supported and are refused: |
| 443 | 445 | |
| @@ -537,6 +539,36 @@ Change the block or its arguments and it runs again. Results inserted with =appe | ||
| 537 | 539 | |
| 538 | 540 | The 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. |
| 539 | 541 | |
| 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*) | |
| 553 | printf '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 | ||
| 570 | The 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 | ||
| 540 | 572 | * Noweb |
| 541 | 573 | |
| 542 | 574 | A 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 | ||
| 575 | 607 | ,#+end_src |
| 576 | 608 | #+END_SRC |
| 577 | 609 | |
| 578 | A 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 | |
| 621 | echo "listening on <<port(base=3000)>>" | |
| 622 | ,#+end_src | |
| 623 | ||
| 624 | ,#+RESULTS: | |
| 625 | : listening on 3080 | |
| 626 | #+END_SRC | |
| 627 | ||
| 628 | These 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 | ||
| 630 | The 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 | ||
| 632 | Export shows these references as written and runs nothing. Tangling does not run blocks; see What tangling refuses below. | |
| 579 | 633 | |
| 580 | 634 | * Calls |
| 581 | 635 | |
| @@ -796,6 +850,7 @@ Comments need the language's comment syntax. orgstar knows it for: =emacs-lisp=, | ||
| 796 | 850 | Tangling stops, writes nothing and says why when: |
| 797 | 851 | |
| 798 | 852 | - =: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." | |
| 799 | 854 | - A shell block's =:var= is a table or list. |
| 800 | 855 | - =:var= is used in a language other than shells, Python, Emacs Lisp, C, C++, D, Java, Fortran and Clojure. |
| 801 | 856 | - 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. | ||
| 816 | 871 | |
| 817 | 872 | * In the Mac App Store version |
| 818 | 873 | |
| 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." | |
| 820 | 875 | - JavaScript blocks can use =:session=. There are no other sessions, and no graphics other than dot and mermaid. |
| 821 | 876 | - The trust prompt works the same way. |
| 822 | 877 | - 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 | ||
| 348 | 348 | On 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: |
| 349 | 349 | |
| 350 | 350 | - 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." | |
| 351 | 352 | - Emacs Lisp the interpreter doesn't have: "This block uses Emacs Lisp that runs only in Emacs, on the Mac." |
| 352 | 353 | - JavaScript that uses something only node has, such as =Buffer=: "This block uses /name/, which runs only in node." |
| 353 | 354 | - 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 | ||
| 215 | 215 | Code blocks (see [[file:11-code-blocks.org][Code blocks]]): |
| 216 | 216 | |
| 217 | 217 | - =: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. | |
| 219 | 222 | - =: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. |
| 220 | 223 | - Clojure runs with babashka or the Clojure CLI only; other =:backend= values are refused. |
| 221 | 224 | - R blocks return their standard output, whatever =:results= says; ob-R returns the value with =:results value=. |
| 222 | 225 | - 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. | |
| 226 | 228 | |
| 227 | 229 | Links (see [[file:09-links.org][Links]]): |
| 228 | 230 | |