Sources/OrgCore/Compute/Babel.swift

3e80720dbff31d31d0bb2f4b66335e8b8b81f78e
orgstar/Sources/OrgCore/Compute/Babel.swift history · blame · raw

1925 lines · 100695 bytes

   1import CryptoKit
   2import Foundation
   3
   4// Babel (ob-core.el, ob-shell.el, ob-python.el, ob-emacs-lisp.el, Org 9.8.7): executing a src
   5// block is planned here, run by the platform, and finished here. The plan resolves header
   6// arguments and refuses anything that would make the run differ from Emacs's; the finish turns
   7// the output into a result the way `org-babel-insert-result` writes it.
   8
   9/// A src block run for the platform to carry out.
  10public struct BabelJob: Sendable, Equatable {
  11    public enum Runner: Sendable, Equatable {
  12        /// An interpreter reading the program on standard input.
  13        case process(executable: String, arguments: [String])
  14        /// `emacs --batch` loading `input` as a script.
  15        case emacs
  16        /// A long-running interpreter named by `:session`: a shell gets `input` as commands, Python
  17        /// runs `input` as a program in its globals.
  18        case session(name: String, executable: String, python: Bool)
  19    }
  20
  21    public let language: String
  22    public let runner: Runner
  23    /// Standard input, or the Emacs script. `Babel.resultFileToken` stands for a file the runner
  24    /// creates; its contents come back as `BabelOutput.resultFile`.
  25    public let input: String
  26    /// `:dir`, relative to the file's folder; nil for the folder itself.
  27    public let directory: String?
  28    /// The block as it was planned, to find it again when the run ends.
  29    public let block: Range<Int>
  30    public let blockText: String
  31    /// Asks every time (`:eval query`) rather than trusting by content.
  32    public let alwaysAsk: Bool
  33    public let finish: Finish
  34    /// A named block a `:var` refers to: run it first, then `Babel.resume` with its output.
  35    public var needs: [Need] = []
  36    /// With `needs`: the text of every block the run may execute, the one asked about and
  37    /// those its references reach. A later job for a block not among them is refused.
  38    public internal(set) var approved: [String] = []
  39    /// Values of the references resolved so far, and how to plan again.
  40    var resolved: [String: Babel.VarValue] = [:]
  41    var caret = 0
  42    var options = Babel.Options()
  43    /// A script for the runner to write to an executable file, for `Babel.scriptFileToken`.
  44    public internal(set) var script: String?
  45    /// An Emacs Lisp block's form, for `Babel.evaluateNatively`.
  46    public internal(set) var lispForm: String?
  47    /// A Lisp header value couldn't be evaluated without the file's path: plan again with
  48    /// `Babel.replan` before running.
  49    public internal(set) var needsFile = false
  50
  51    public struct Need: Sendable, Equatable {
  52        /// The `:var` value, `name` or `name(args)`.
  53        public let reference: String
  54        public let job: BabelJob
  55    }
  56
  57    public struct Finish: Sendable, Equatable {
  58        enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp }
  59        let kind: Kind
  60        var language = ""
  61        public internal(set) var params: [String]
  62        let output: Bool
  63        let wrap: String?
  64        let name: String?
  65        /// An inline block: the result goes after it, in `{{{results(…)}}}`.
  66        var inline = false
  67        /// `:file` (under `:output-dir`) with `:results file`, and `:file-desc`.
  68        var file: String?
  69        var fileDescription: String?
  70        /// The program writes `file` itself, as graphics languages do.
  71        var writesFile = false
  72        /// `:cache yes`: the hash for the `#+RESULTS[…]:` line.
  73        var hash: String?
  74        /// Column and row names a table `:var` gave up, put back on a table result
  75        /// (`org-babel-reassemble-table`).
  76        var colnames: [String]?
  77        var rownames: [String]?
  78    }
  79}
  80
  81public struct BabelOutput: Sendable, Equatable {
  82    public var stdout: String
  83    public var resultFile: String?
  84    /// What the program wrote to standard error, and its exit status: Emacs shows them in
  85    /// `*Org-Babel Error Output*` and still inserts the results.
  86    public var stderr: String
  87    public var status: Int32
  88    public init(stdout: String, resultFile: String? = nil, stderr: String = "", status: Int32 = 0) {
  89        self.stdout = stdout
  90        self.resultFile = resultFile
  91        self.stderr = stderr
  92        self.status = status
  93    }
  94
  95    /// A line for the message area when the program failed or complained, else nil.
  96    public var problem: String? {
  97        let first = stderr.split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)
  98        switch (status, first) {
  99        case (0, nil): return nil
 100        case (0, let line?): return line
 101        case (let code, nil): return "Exited with status \(code)"
 102        case (let code, let line?): return "Exited with status \(code): \(line)"
 103        }
 104    }
 105}
 106
 107public enum Babel {
 108    public static let resultFileToken = "__ORGSTAR_RESULT_FILE__"
 109    /// Stands, in a job's arguments, for the executable file the runner writes `job.script` to.
 110    public static let scriptFileToken = "__ORGSTAR_SCRIPT_FILE__"
 111    static let shells: Set<String> = ["sh", "bash", "zsh", "shell", "fish", "ksh", "dash", "ash", "csh", "mksh", "posh"]
 112    static let generic: [String: (String, [String])] = [
 113        "ruby": ("ruby", []), "js": ("node", []), "javascript": ("node", []), "R": ("Rscript", ["-"]),
 114        "awk": ("awk", ["-f", "/dev/stdin"]),
 115    ]
 116
 117    public struct Options: Sendable, Equatable {
 118        public var python = "python3"
 119        /// `shell-file-name`, from `SHELL` as Emacs sets it: runs blocks in the `shell` language
 120        /// and chooses how variables are written in the `:cache` hash.
 121        public var shell = ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/sh"
 122        /// The file the block is in, for Lisp header values that use it.
 123        public var file: String?
 124        public init() {}
 125    }
 126
 127    // MARK: - Planning
 128
 129    /// The run for the src block at the caret, or why it can't run.
 130    public static func plan(_ context: EditContext, options: Options = Options()) -> Result<BabelJob, Failure> {
 131        plan(context, options: options, resolved: [:])
 132    }
 133
 134    /// Plans the block again with the value of the block `job` needed: the output of
 135    /// `need.job`, as `org-babel-ref-resolve` reads it.
 136    public static func resume(_ job: BabelJob, need: BabelJob.Need, output: BabelOutput, text: String, tree: OrgTree) -> Result<BabelJob, Failure> {
 137        var resolved = job.resolved
 138        resolved[need.reference] = varValue(need.job.finish, output)
 139        let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret])
 140        return plan(context, options: job.options, resolved: resolved)
 141    }
 142
 143    /// Plans `job`'s block again knowing the file it is in.
 144    public static func replan(_ job: BabelJob, file: String, text: String, tree: OrgTree) -> Result<BabelJob, Failure> {
 145        var options = job.options
 146        options.file = file
 147        let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret])
 148        return plan(context, options: options, resolved: job.resolved)
 149    }
 150
 151    static func plan(_ context: EditContext, options: Options, resolved: [String: VarValue]) -> Result<BabelJob, Failure> {
 152        let text = context.text
 153        let ns = text as NSString
 154        let model = DocumentModel(tree: context.tree)
 155        let refs = References(resolved: resolved, options: options)
 156        func located(_ result: Result<BabelJob, Failure>) -> Result<BabelJob, Failure> {
 157            result.map { job in
 158                var job = job
 159                (job.caret, job.resolved, job.options) = (context.caret, resolved, options)
 160                return job
 161            }
 162        }
 163        do {
 164            if let block = model.srcBlocks.first(where: { $0.range.contains(context.caret) || $0.range.upperBound == context.caret }) {
 165                return located(plan(block, params: try Params(block: block, model: model, text: ns), model: model, text: ns, options: options,
 166                                    location: block.range, name: block.name, refs: refs))
 167            }
 168            if let call = try callAt(context.caret, model: model, text: ns) {
 169                return located(plan(call.block, params: call.params, model: model, text: ns, options: options, location: call.location, name: call.name, refs: refs))
 170            }
 171            if let call = try inlineCallAt(context.caret, tree: context.tree, model: model, text: ns) {
 172                return located(plan(call.block, params: call.params, model: model, text: ns, options: options, location: call.location, name: nil, inline: true, refs: refs))
 173            }
 174            if let inline = try inlineAt(context.caret, tree: context.tree, model: model, text: ns) {
 175                return located(plan(inline.block, params: inline.params, model: model, text: ns, options: options, location: inline.block.range, name: nil, inline: true, refs: refs))
 176            }
 177        } catch let error as Failure {
 178            return .failure(error)
 179        } catch {
 180            return .failure(.message("\(error)"))
 181        }
 182        return .failure(.message("Not in a source block"))
 183    }
 184
 185    /// The `#+CALL:` line at `offset`: the block it names, with the call's inside header, its
 186    /// arguments as `:var` and its end header over the block's own (`org-babel-lob-get-info`).
 187    static func callAt(_ offset: Int, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params, location: Range<Int>, name: String?)? {
 188        let lineRange = text.lineRange(for: NSRange(location: min(offset, text.length), length: 0))
 189        let line = text.substring(with: lineRange)
 190        guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+CALL:[ \t]*([^\s(\[]+)(?:\[([^\]]*)\])?\((.*?)\)[ \t]*(.*?)[ \t]*\n?$/#) else { return nil }
 191        let name = String(m.1)
 192        guard let block = model.srcBlocks.first(where: { $0.name == name }) else { throw Failure.message("Reference '\(name)' not found in this buffer") }
 193        var extra: [[(String, String)]] = []
 194        if let inside = m.2 { extra.append(Params.parse(String(inside))) }
 195        extra.append(splitArguments(String(m.3)).map { (":var", $0) })
 196        if !m.4.isEmpty { extra.append(Params.parse(String(m.4))) }
 197        // The call's own #+NAME names its results.
 198        var callName: String?
 199        if lineRange.location > 0 {
 200            let previous = text.substring(with: text.lineRange(for: NSRange(location: lineRange.location - 1, length: 0)))
 201            callName = previous.firstMatch(of: #/(?i)^[ \t]*#\+NAME:[ \t]*(\S+)/#).map { String($0.1) }
 202        }
 203        let location = lineRange.location..<NSMaxRange(lineRange)
 204        return (block, try Params(block: block, model: model, text: text, extra: extra), location, callName)
 205    }
 206
 207    /// The inline `call_NAME[INSIDE](ARGS)[END]` at `offset`: like `#+CALL`, with the result
 208    /// after the call.
 209    static func inlineCallAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params, location: Range<Int>)? {
 210        var node = tree.root
 211        var found: SyntaxNode?
 212        while let child = node.child(containing: offset) {
 213            if child.kind == .inlineBabelCall { found = child }
 214            node = child
 215        }
 216        guard let object = found, let m = object.text.firstMatch(of: /^call_([^()\[\]\s]+)(?:\[([^\]]*)\])?\((.*?)\)(?:\[([^\]]*)\])?$/) else { return nil }
 217        let name = String(m.1)
 218        guard let block = model.srcBlocks.first(where: { $0.name == name }) else { throw Failure.message("Reference '\(name)' not found in this buffer") }
 219        var extra: [[(String, String)]] = []
 220        if let inside = m.2 { extra.append(Params.parse(String(inside))) }
 221        extra.append(splitArguments(String(m.3)).map { (":var", $0) })
 222        if let end = m.4 { extra.append(Params.parse(String(end))) }
 223        return (block, try Params(block: block, model: model, text: text, extra: extra), object.range)
 224    }
 225
 226    /// Call arguments split on commas outside quotes and parentheses.
 227    static func splitArguments(_ s: String) -> [String] {
 228        var parts: [String] = []
 229        var current = ""
 230        var depth = 0
 231        var quoted = false
 232        for c in s {
 233            if c == "\"" { quoted.toggle() }
 234            if !quoted, c == "(" { depth += 1 }
 235            if !quoted, c == ")" { depth -= 1 }
 236            if c == ",", !quoted, depth == 0 {
 237                parts.append(current)
 238                current = ""
 239            } else {
 240                current.append(c)
 241            }
 242        }
 243        parts.append(current)
 244        return parts.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
 245    }
 246
 247    /// The inline `src_LANG[HEADERS]{BODY}` at `offset`.
 248    static func inlineAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params)? {
 249        var node = tree.root
 250        var found: SyntaxNode?
 251        while let child = node.child(containing: offset) {
 252            if child.kind == .inlineSourceBlock { found = child }
 253            node = child
 254        }
 255        guard let object = found, let m = object.text.firstMatch(of: /^src_([^\s\[{]+)(?:\[([^\]]*)\])?\{(.*)\}$/) else { return nil }
 256        let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= object.range.lowerBound }
 257        let block = SrcBlockInfo(range: object.range, heading: heading, name: nil, language: String(m.1), switches: [], body: String(m.3), headerArguments: [:])
 258        var extra: [[(String, String)]] = [[(":exports", "results"), (":hlines", "yes")]]
 259        if let headers = m.2 { extra.append(Params.parse(String(headers))) }
 260        return (block, try Params(block: block, model: model, text: text, extra: extra, inline: true))
 261    }
 262
 263    /// What `:var` references resolve to while planning.
 264    struct References {
 265        var resolved: [String: VarValue]
 266        var options: Options
 267        /// Blocks being planned for a reference, to stop cycles.
 268        var visiting: Set<String> = []
 269    }
 270
 271    /// A reference to a block that has to run first.
 272    struct Needed: Error {
 273        let need: BabelJob.Need
 274    }
 275
 276    static func plan(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
 277                     location: Range<Int>, name: String?, inline: Bool = false, refs: References? = nil, useCache: Bool = true) -> Result<BabelJob, Failure> {
 278        var evaluated = params
 279        evaluated.evaluateLisp(file: options.file)
 280        let needsFile = options.file == nil && evaluated.lisp.contains { evaluated.evaluated[$0] == nil }
 281        return planBlock(block, params: params, model: model, text: ns, options: options, location: location, name: name, inline: inline,
 282                         refs: refs, useCache: useCache).map { job in
 283            var job = job
 284            job.needsFile = needsFile
 285            return job
 286        }
 287    }
 288
 289    static func planBlock(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
 290                          location: Range<Int>, name: String?, inline: Bool, refs: References?, useCache: Bool) -> Result<BabelJob, Failure> {
 291        let refs = refs ?? References(resolved: [:], options: options)
 292        var params = params
 293        params.evaluateLisp(file: options.file)
 294        let needsFile = options.file == nil && params.lisp.contains { params.evaluated[$0] == nil }
 295        guard let language = block.language else { return .failure(.message("This block has no language")) }
 296        let eval = params.single[":eval"]?.lowercased()
 297        if eval == "never" || eval == "no" || eval == "never-export" || eval == "no-export" {
 298            return .failure(.message("Evaluation of this \(language) code block\(block.name.map { " (\($0)) " } ?? " ")is disabled."))
 299        }
 300        if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language) {
 301            return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
 302        }
 303        for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
 304            && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) {
 305            return .failure(.message("\(key) isn't supported yet; nothing was run."))
 306        }
 307        let session = params.single[":session"].flatMap { $0 == "none" ? nil : ($0.isEmpty ? "*\(language)*" : $0) }
 308        if session != nil, !shells.contains(language), language != "python" {
 309            return .failure(.message(":session isn't supported for \(language) yet; nothing was run."))
 310        }
 311        var body = normalizedBody(block)
 312        if nowebEvaluates(params.single[":noweb"]) {
 313            do {
 314                body = try expandNoweb(block, params: params, model: model, text: ns)
 315            } catch let error as Failure {
 316                return .failure(error)
 317            } catch {
 318                return .failure(.message("\(error)"))
 319            }
 320        }
 321        let output = params.results.contains("output")
 322        let file = params.single[":file"].map { name in
 323            params.single[":output-dir"].map { $0.hasSuffix("/") ? $0 + name : $0 + "/" + name } ?? name
 324        }
 325        let toFile = params.results.contains("file")
 326        var hash: String?
 327        var tables = Tables()
 328        let finishBase = { (kind: BabelJob.Finish.Kind) in
 329            BabelJob.Finish(kind: kind, language: language, params: params.results, output: output, wrap: params.wrap, name: name, inline: inline,
 330                            file: toFile ? file : nil, fileDescription: params.single[":file-desc"], hash: hash,
 331                            colnames: tables.picked(tables.colnames, ":colnames", params), rownames: tables.picked(tables.rownames, ":rownames", params))
 332        }
 333        let vars: [(String, VarValue)]
 334        var stdin: VarValue?
 335        do {
 336            tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns, refs: refs)) }, params: params)
 337            vars = tables.vars
 338            stdin = try params.single[":stdin"].map { try resolve($0, model: model, text: ns, refs: refs) }
 339        } catch let needed as Needed {
 340            // Asked about once, with every block the references reach; asked every time when
 341            // any of them has `:eval query`.
 342            let reached = referencedBlocks(params, model: model, text: ns, seen: [])
 343            let texts = [ns.substring(with: NSRange(location))] + reached.map { ns.substring(with: NSRange($0.range)) }
 344            let query = eval == "query" || reached.contains { (try? Params(block: $0, model: model, text: ns))?.single[":eval"]?.lowercased() == "query" }
 345            var job = BabelJob(
 346                language: language, runner: .process(executable: "", arguments: []), input: "", directory: params.single[":dir"],
 347                block: location, blockText: texts.joined(separator: "\n"), alwaysAsk: query, finish: finishBase(.generic), needs: [needed.need]
 348            )
 349            job.approved = texts
 350            return .success(job)
 351        } catch let error as Failure {
 352            return .failure(error)
 353        } catch {
 354            return .failure(.message("\(error)"))
 355        }
 356        if useCache, !inline, !needsFile, params.single[":cache"] == "yes" {
 357            do {
 358                let state = try cacheState(language: language, params: params, tables: tables, body: body, location: location, name: name,
 359                                           call: location != block.range, text: ns, options: options)
 360                if state.current { return .failure(.message(cachedMessage(state.value))) }
 361                // Appended or prepended results accumulate, so they carry no hash.
 362                if params.results.contains("replace") { hash = state.hash }
 363            } catch let error as Failure {
 364                return .failure(error)
 365            } catch {
 366                return .failure(.message("\(error)"))
 367            }
 368        }
 369        let blockText = ns.substring(with: NSRange(location))
 370        let dir = params.single[":dir"]
 371        let alwaysAsk = eval == "query"
 372
 373        if shells.contains(language) {
 374            let valueIsExitStatus = params.results.contains("value")
 375            let executable = language == "shell" ? options.shell : language
 376            let lines = shellAssignments(vars, shell: executable, params: params)
 377            let cmdline = params.single[":cmdline"]
 378            let shebang = params.single[":shebang"].flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil }
 379            if session == nil, stdin != nil || cmdline != nil || shebang != nil {
 380                // `org-babel-sh-evaluate`: an executable script, run by the shell with the
 381                // command line after it and `:stdin` as its input; the value is its last line.
 382                var script = (shebang ?? "#!/usr/bin/env \(executable)") + "\n"
 383                if params.single[":padline"] != "no" { script += "\n" }
 384                script += (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "")
 385                let command = Babel.scriptFileToken + (stdin != nil || cmdline != nil ? " " + (cmdline ?? "") : "")
 386                var job = BabelJob(
 387                    language: language, runner: .process(executable: executable, arguments: ["-c", command]),
 388                    input: stdin.map { shellString($0) } ?? "", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
 389                    finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
 390                )
 391                job.script = script
 392                return .success(job)
 393            }
 394            let full = (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "")
 395            return .success(BabelJob(
 396                language: language, runner: session.map { .session(name: $0, executable: executable, python: false) } ?? .process(executable: executable, arguments: []),
 397                input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir,
 398                block: location, blockText: blockText, alwaysAsk: alwaysAsk,
 399                finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
 400            ))
 401        }
 402        if language == "python", let session {
 403            // `org-babel-python--eval-ast`: the body at top level in the session, the value its
 404            // last expression's.
 405            let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
 406            let source = (lines + [body]).joined(separator: "\n")
 407            let literal = String(data: try! JSONSerialization.data(withJSONObject: [source]), encoding: .utf8)!.dropFirst().dropLast()
 408            let program: String
 409            if output {
 410                program = "exec(compile(\(literal), '<org-babel>', 'exec'), globals())\n"
 411            } else {
 412                program = pythonFormatter + """
 413                    import ast as __orgstar_ast
 414                    __orgstar_tree = __orgstar_ast.parse(\(literal))
 415                    __orgstar_last = None
 416                    if __orgstar_tree.body and isinstance(__orgstar_tree.body[-1], __orgstar_ast.Expr):
 417                        __orgstar_last = __orgstar_ast.Expression(__orgstar_tree.body.pop().value)
 418                    exec(compile(__orgstar_tree, '<org-babel>', 'exec'), globals())
 419                    __orgstar_format(eval(compile(__orgstar_last, '<org-babel>', 'eval'), globals()) if __orgstar_last else None, '\(resultFileToken)', [
 420                    """ + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
 421            }
 422            return .success(BabelJob(
 423                language: language, runner: .session(name: session, executable: params.single[":python"] ?? options.python, python: true),
 424                input: program, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.python)
 425            ))
 426        }
 427        if language == "python" {
 428            let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
 429            var full = (lines + [body]).joined(separator: "\n")
 430            if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" }
 431            let input: String
 432            if output {
 433                input = full + "\n"
 434            } else {
 435                input = pythonFormatter + "def main():\n" + shiftRight(full) + "\n\n__orgstar_format(main(), '\(resultFileToken)', ["
 436                    + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
 437            }
 438            return .success(BabelJob(
 439                language: language, runner: .process(executable: params.single[":python"] ?? options.python, arguments: []),
 440                input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
 441                finish: finishBase(.python)
 442            ))
 443        }
 444        if language == "emacs-lisp" || language == "elisp" {
 445            let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
 446            let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n      ")))\n\(body)\n)"
 447            let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)"
 448            var job = BabelJob(
 449                language: language, runner: .emacs, input: emacsScript(form: form, params: params.results),
 450                directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.emacsLisp)
 451            )
 452            job.lispForm = form
 453            return .success(job)
 454        }
 455        if ["dot", "plantuml", "mermaid"].contains(language) {
 456            // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`.
 457            guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) }
 458            let quoted = "'" + file.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
 459            let ext = (file as NSString).pathExtension.isEmpty ? "png" : (file as NSString).pathExtension
 460            let cmdline = params.single[":cmdline"].map { " " + $0 } ?? ""
 461            var input = body + "\n"
 462            let command: String
 463            switch language {
 464            case "dot":
 465                command = "dot\(cmdline) -T\(ext) -o \(quoted)"
 466            case "plantuml":
 467                if body.range(of: "^[ \\t]*@start", options: .regularExpression) == nil { input = "@startuml\n" + body + "\n@enduml\n" }
 468                command = "plantuml\(cmdline) -p -t\(ext) > \(quoted)"
 469            default:
 470                command = "f=$(mktemp).mmd; cat > \"$f\"; mmdc\(cmdline) -i \"$f\" -o \(quoted); s=$?; rm -f \"$f\"; exit $s"
 471            }
 472            var finish = finishBase(.generic)
 473            finish.file = file
 474            finish.writesFile = true
 475            finish.params = params.results.filter { !["table", "scalar", "verbatim", "list", "vector"].contains($0) } + (params.results.contains("file") ? [] : ["file"])
 476            return .success(BabelJob(
 477                language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", command]),
 478                input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish
 479            ))
 480        }
 481        if let (executable, arguments) = generic[language] {
 482            guard vars.isEmpty else { return .failure(.message(":var isn't supported for \(language) yet.")) }
 483            return .success(BabelJob(
 484                language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
 485                input: body + "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
 486                finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: name, inline: inline, hash: hash)
 487            ))
 488        }
 489        return .failure(.message("No way to run \(language) blocks yet."))
 490    }
 491
 492    public enum Failure: Error, Equatable {
 493        case message(String)
 494    }
 495
 496    // MARK: - Noweb
 497
 498    /// `org-babel-noweb-p` in the `:eval` context.
 499    static func nowebEvaluates(_ value: String?) -> Bool {
 500        (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "no-export", "strip-export", "eval", "strip-tangle"].contains(String($0)) }
 501    }
 502
 503    /// `org-babel-noweb-p` for `:tangle`.
 504    static func nowebTangles(_ value: String?) -> Bool {
 505        (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "tangle", "no-export", "strip-export", "strip-tangle"].contains(String($0)) }
 506    }
 507
 508    /// `org-babel-expand-noweb-references` for evaluation: each `<<name>>` becomes the body of
 509    /// the block named so, or of every block with that `:noweb-ref`, joined by `:noweb-sep`, or
 510    /// the contents of the heading with that ID; the text before it on its line goes before
 511    /// each line it brings.
 512    /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as
 513    /// evaluation does.
 514    /// `links` gives a block's begin and end comments, for `:comments noweb` when tangling.
 515    static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0,
 516                            links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil) throws -> String {
 517        guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") }
 518        let body = normalizedBody(block)
 519        let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true
 520        let commenting = tangling && links != nil && params.single[":comments"] == "noweb"
 521        func expand(_ other: SrcBlockInfo) throws -> String {
 522            let otherParams = try Params(block: other, model: model, text: text)
 523            let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"])
 524            let b = expands
 525                ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links)
 526                : normalizedBody(other)
 527            guard commenting, let links else { return b }
 528            // `c-wrap`: commented in this block's language, trimmed.
 529            func wrap(_ s: String) throws -> String {
 530                try Tangle.commentRegion(s, language: block.language ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
 531            }
 532            var (begin, end) = try links(other.name == nil ? block : other, other.name == nil ? params : otherParams)
 533            // A `:noweb-ref` block without a name: the link is the including block's, the name empty.
 534            if other.name == nil {
 535                if let split = begin.range(of: "][") { begin = begin[..<split.lowerBound] + "][]]" }
 536                end = " ends here"
 537            }
 538            return try wrap(begin) + "\n" + b + "\n" + (try wrap(end)) + "\n"
 539        }
 540        func inCommentedHeading(_ b: SrcBlockInfo) -> Bool {
 541            guard let h = b.heading else { return false }
 542            return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
 543        }
 544        let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
 545        let ns = body as NSString
 546        var out = ""
 547        var at = 0
 548        for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
 549            let prefix = ns.substring(with: m.range(at: 1))
 550            let id = ns.substring(with: m.range(at: 3))
 551            out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at))
 552            at = NSMaxRange(m.range)
 553            var expansion = ""
 554            if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
 555                throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.")
 556            } else if let heading = model.headings.firstIndex(where: { h in
 557                h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) }
 558            }) {
 559                expansion = headlineBody(heading, model: model, text: text)
 560            } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) {
 561                expansion = try expand(named)
 562            } else {
 563                var parts: [String] = []
 564                var separators: [String] = []
 565                for other in model.srcBlocks where !inCommentedHeading(other) {
 566                    let p = try Params(block: other, model: model, text: text)
 567                    guard p.single[":noweb-ref"] == id else { continue }
 568                    parts.append(try expand(other))
 569                    separators.append(p.single[":noweb-sep"] ?? "\n")
 570                }
 571                for (i, part) in parts.enumerated() {
 572                    if i > 0 { expansion += separators[i - 1] }
 573                    expansion += part
 574                }
 575            }
 576            out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion
 577        }
 578        return out + ns.substring(from: at)
 579    }
 580
 581    /// `org-babel-ref-headline-body`: the entry after its planning and drawers.
 582    static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String {
 583        let heading = model.headings[index]
 584        let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound)
 585        buffer.endOfMetaData()
 586        let start = buffer.point
 587        let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length
 588        return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : ""
 589    }
 590
 591    /// `org-babel--normalize-body`: without the final newline, and without the indentation
 592    /// common to its lines unless `-i` keeps it.
 593    static func normalizedBody(_ block: SrcBlockInfo) -> String {
 594        var lines = block.body.components(separatedBy: "\n")
 595        if lines.last == "" { lines.removeLast() }
 596        // Org escapes lines starting with `*` or `#+` inside blocks with a comma.
 597        lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
 598        if !block.switches.contains("-i") {
 599            let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
 600            let common = indents.min() ?? 0
 601            lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }
 602        }
 603        return lines.joined(separator: "\n")
 604    }
 605
 606    // MARK: - Tables in variables
 607
 608    /// Variables after `org-babel-disassemble-tables`, with the names taken off their tables.
 609    struct Tables {
 610        var vars: [(String, VarValue)] = []
 611        var colnames: [(name: String, names: [Cell])] = []
 612        var rownames: [(name: String, names: [Cell])] = []
 613
 614        /// `org-babel-pick-name`: a Lisp list given as the header argument, or the last
 615        /// variable's names, unless the header argument is absent, whose `nil` selects none.
 616        func picked(_ names: [(name: String, names: [Cell])], _ key: String, _ params: Params) -> [String]? {
 617            if let list = params.evaluated[key].flatMap(Babel.lispNames) { return list }
 618            guard params.single[key] != nil, let last = names.last else { return nil }
 619            return last.names.map(Babel.cellText)
 620        }
 621    }
 622
 623    /// A Lisp list of strings and numbers, as names.
 624    static func lispNames(_ value: Sexp) -> [String]? {
 625        guard case .list(let items) = value else { return nil }
 626        return try? items.map { item in
 627            if let s = item.string { return s }
 628            let printed = Elisp.printed(item)
 629            guard number(printed) == printed else { throw Failure.message(printed) }
 630            return printed
 631        }
 632    }
 633
 634    static func cellText(_ c: Cell) -> String {
 635        switch c {
 636        case .number(let n): n
 637        case .text(let s): s
 638        }
 639    }
 640
 641    /// `org-babel-disassemble-tables`: a table's header row comes off when `:colnames` asks, or
 642    /// by default when only its second row is a rule; its first column with `:rownames`; its
 643    /// rules unless `:hlines yes`.
 644    static func disassemble(_ vars: [(String, VarValue)], params: Params) throws -> Tables {
 645        for key in [":colnames", ":rownames"] where params.lisp.contains(key) && params.evaluated[key].flatMap(lispNames) == nil {
 646            throw Failure.message("\(key) \(params.single[key] ?? "") is Lisp that only Emacs can evaluate; nothing was run.")
 647        }
 648        let colnames = params.single[":colnames"]
 649        let rownames = params.single[":rownames"]
 650        let hlines = params.single[":hlines"] ?? "no"
 651        var tables = Tables()
 652        for (name, value) in vars {
 653            guard case .table(var rows) = value else {
 654                tables.vars.append((name, value))
 655                continue
 656            }
 657            let auto = rows.count > 1 && rows[0] != nil && rows[1] == nil && !rows.dropFirst(2).contains(where: { $0 == nil })
 658            if colnames != "no", colnames != nil || auto {
 659                while let first = rows.first, first == nil { rows.removeFirst() }
 660                if let header = rows.first ?? nil {
 661                    rows.removeFirst(rows.count > 1 && rows[1] == nil ? 2 : 1)
 662                    tables.colnames.append((name, header))
 663                }
 664            }
 665            if let rownames, rownames != "no" {
 666                let kept = rows.compactMap { $0 }
 667                tables.rownames.append((name, kept.map { $0.first ?? .text("") }))
 668                rows = kept.map { Array($0.dropFirst()) }
 669            }
 670            if hlines != "yes" { rows = rows.filter { $0 != nil } }
 671            tables.vars.append((name, .table(rows)))
 672        }
 673        return tables
 674    }
 675
 676    /// `org-babel-reassemble-table` on a result.
 677    static func reassemble(_ value: Value, _ finish: BabelJob.Finish) -> Value {
 678        guard case .table(var rows) = value else { return value }
 679        if let names = finish.rownames, names.count == rows.count {
 680            var next = names.makeIterator()
 681            rows = rows.map { row in row.map { [next.next() ?? ""] + $0 } }
 682        }
 683        if let names = finish.colnames, let first = rows.first ?? nil, first.count == names.count {
 684            rows = [names, nil] + rows
 685        }
 686        return .table(rows)
 687    }
 688
 689    /// A `:var` value that is Lisp (`org-babel-read`): evaluated, as a number, string, list or
 690    /// table.
 691    static func lispValue(_ value: String) throws -> VarValue {
 692        let refusal = Failure.message(":var value \(value) is Lisp that only Emacs can evaluate.")
 693        guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form) else { throw refusal }
 694        func cell(_ v: Sexp) throws -> Cell {
 695            if let s = v.string { return .text(s) }
 696            if let n = number(Elisp.printed(v)), Elisp.printed(v) == n { return .number(n) }
 697            throw refusal
 698        }
 699        if let s = result.string { return .scalar(s) }
 700        if case .list(let items) = result, !items.isEmpty {
 701            if items.allSatisfy({ if case .list = $0 { return true }; return $0 == .symbol("hline") }) {
 702                return .table(try items.map { item in
 703                    if item == .symbol("hline") { return nil }
 704                    guard case .list(let cells) = item else { throw refusal }
 705                    return try cells.map(cell)
 706                })
 707            }
 708            return .list(try items.map(cell))
 709        }
 710        if case .number(let n) = try? cell(result) { return .number(n) }
 711        throw refusal
 712    }
 713
 714    // MARK: - Cache
 715
 716    /// `:cache yes` (`org-babel-execute-src-block`): the block's hash, and whether its results
 717    /// already carry it, with their value when it can be read.
 718    static func cacheState(language: String, params: Params, tables: Tables, body: String, location: Range<Int>, name: String?,
 719                           call: Bool, text: NSString, options: Options) throws -> (hash: String, current: Bool, value: VarValue?) {
 720        // The hash is taken outside the shell's own binding of `shell-file-name`, so its
 721        // variables are written for the user's shell whatever the block's language.
 722        let input = try cacheInput(language: language, params: params, tables: tables,
 723                                   expanded: expandedBody(language: language, vars: tables.vars, body: body, shell: options.shell, params: params), call: call)
 724        let hash = Insecure.SHA1.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined()
 725        guard let line = existingResults(name: name, block: location, text: text), resultsHash(at: line, text: text) == hash else {
 726            return (hash, false, nil)
 727        }
 728        return (hash, true, readResult(after: line, text: text))
 729    }
 730
 731    static func cachedMessage(_ value: VarValue?) -> String {
 732        value.map { "Cached: " + lispLiteral($0) } ?? "Cached; nothing was run."
 733    }
 734
 735    /// The body with its variables, as the language's `org-babel-expand-body:` writes it.
 736    static func expandedBody(language: String, vars: [(String, VarValue)], body: String, shell: String, params: Params) -> String {
 737        if shells.contains(language) {
 738            return (shellAssignments(vars, shell: shell, params: params) + [body]).joined(separator: "\n")
 739        }
 740        if language == "python" {
 741            return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n")
 742        }
 743        if language == "emacs-lisp" || language == "elisp" {
 744            let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
 745            return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n      ")))\n\(body)\n)"
 746        }
 747        return body
 748    }
 749
 750    /// What `org-babel-sha1-hash` hashes: the header arguments after `org-babel-process-params`,
 751    /// sorted by key and printed with `%S`, then the expanded body.
 752    static func cacheInput(language: String, params: Params, tables: Tables, expanded: String, call: Bool) throws -> String {
 753        if let key = params.lisp.first(where: { params.evaluated[$0] == nil }) {
 754            throw Failure.message(":cache with \(key) \(params.single[key] ?? "") needs Emacs to evaluate the Lisp; nothing was run.")
 755        }
 756        let ignored: Set<String> = ["replace", "silent", "none", "discard", "append", "prepend"]
 757        let drawsFile = language == "dot" || language == "plantuml"
 758        // `org-babel-default-header-args`, the language's and `org-babel-default-lob-header-args`.
 759        var defaults = [":session": "none", ":exports": call || drawsFile ? "results" : "code", ":cache": "no", ":noweb": "no", ":hlines": "no", ":tangle": "no"]
 760        if language == "emacs-lisp" || language == "elisp" { defaults[":lexical"] = "no" }
 761        var entries: [(key: String, printed: String)] = []
 762        for (key, value) in defaults.merging(params.single, uniquingKeysWith: { $1 }) {
 763            let printed: String
 764            if let evaluated = params.evaluated[key] {
 765                printed = Elisp.printed(evaluated, escape: true)
 766            } else if value.isEmpty {
 767                continue
 768            } else if key == ":exports" {
 769                printed = lispString(value.split(whereSeparator: \.isWhitespace).map(String.init).filter { !ignored.contains($0) }.sorted().joined(separator: " "))
 770            } else if params.single[key] != nil, !params.quoted.contains(key), let n = number(value) {
 771                printed = n
 772            } else {
 773                printed = lispString(value)
 774            }
 775            entries.append((key, printed))
 776        }
 777        var words = params.results
 778        if drawsFile, !words.contains(where: { Params.resultGroups[0].contains($0) }) { words.append("file") }
 779        let kept = words.filter { !ignored.contains($0) }.sorted()
 780        if !kept.isEmpty { entries.append((":result-params", "(" + kept.map { lispString($0) }.joined(separator: " ") + ")")) }
 781        entries.append((":result-type", words.contains("output") ? "output" : "value"))
 782        entries.append((":results", lispString(kept.joined(separator: " "))))
 783        if let wrap = params.wrap, !wrap.isEmpty { entries.append((":wrap", lispString(wrap))) }
 784        for (key, names) in [(":colname-names", tables.colnames), (":rowname-names", tables.rownames)] where !names.isEmpty {
 785            entries.append((key, "(" + names.map { "(\($0.name) " + lispLiteral(.list($0.names)).dropFirst() }.joined(separator: " ") + ")"))
 786        }
 787        for (name, value) in tables.vars {
 788            switch value {
 789            case .scalar, .number: entries.append((":var", "(\(name) . \(lispLiteral(value)))"))
 790            case .list, .table: entries.append((":var", "(\(name) " + lispLiteral(value).dropFirst()))
 791            }
 792        }
 793        let sorted = entries.enumerated().sorted { ($0.element.key, $0.offset) < ($1.element.key, $1.offset) }.map(\.element.printed)
 794        return sorted.joined(separator: ":") + "-" + expanded
 795    }
 796
 797    /// `org-babel-read-result` for fixed-width lines, a table or a plain list after the
 798    /// `#+RESULTS` line at `line`; nil for anything else.
 799    static func readResult(after line: Int, text ns: NSString) -> VarValue? {
 800        var location = NSMaxRange(ns.lineRange(for: NSRange(location: line, length: 0)))
 801        var lines: [String] = []
 802        while location < ns.length {
 803            let range = ns.lineRange(for: NSRange(location: location, length: 0))
 804            let content = ns.substring(with: range).trimmingCharacters(in: .newlines)
 805            if content.trimmingCharacters(in: .whitespaces).isEmpty { break }
 806            lines.append(content.trimmingCharacters(in: .whitespaces))
 807            location = NSMaxRange(range)
 808        }
 809        guard let first = lines.first else { return nil }
 810        if first == ":" || first.hasPrefix(": ") {
 811            var fixed: [String] = []
 812            for l in lines {
 813                guard l == ":" || l.hasPrefix(": ") else { break }
 814                fixed.append(String(l.dropFirst(2)))
 815            }
 816            let value = fixed.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
 817            return number(value).map(VarValue.number) ?? .scalar(value)
 818        }
 819        if first.hasPrefix("|") {
 820            var rows: [[Cell]?] = []
 821            for l in lines {
 822                guard l.hasPrefix("|") else { break }
 823                if l.hasPrefix("|-") {
 824                    rows.append(nil)
 825                    continue
 826                }
 827                let cells = l.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
 828                rows.append((l.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
 829            }
 830            return .table(rows)
 831        }
 832        if first.firstMatch(of: #/^[-+*] /#) != nil {
 833            var items: [Cell] = []
 834            for l in lines {
 835                guard let m = l.firstMatch(of: /^[-+*] (.*)$/) else { return nil }
 836                items.append(cell(String(m.1)))
 837            }
 838            return .list(items)
 839        }
 840        return nil
 841    }
 842
 843    // MARK: - Header arguments
 844
 845    struct Params {
 846        var results: [String] = ["replace"]
 847        var single: [String: String] = [:]
 848        var vars: [(name: String, value: String)] = []
 849        var wrap: String?
 850        /// Keys whose value is Lisp to evaluate (`org-babel-read`): unquoted, starting with `(`, `'`, `` ` `` or `[`.
 851        var lisp: Set<String> = []
 852        /// Keys whose value was a quoted string, which `org-babel-read` doesn't take for a number.
 853        var quoted: Set<String> = []
 854        /// Lisp values evaluated to something other than a string or number, such as a list of
 855        /// column names.
 856        var evaluated: [String: Sexp] = [:]
 857
 858        /// `org-babel-read` on the Lisp values the interpreter can evaluate: a string or number
 859        /// takes the form's place; other values are kept in `evaluated`.
 860        mutating func evaluateLisp(file: String?) {
 861            for key in lisp {
 862                guard let form = try? LispReader.readFirst(single[key] ?? "").sexp,
 863                      let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form) else { continue }
 864                let printed = Elisp.printed(value)
 865                if let s = value.string {
 866                    single[key] = s
 867                    quoted.insert(key)
 868                    lisp.remove(key)
 869                } else if Babel.number(printed) == printed {
 870                    single[key] = printed
 871                    lisp.remove(key)
 872                } else {
 873                    evaluated[key] = value
 874                }
 875            }
 876        }
 877
 878        static let resultGroups: [Set<String>] = [
 879            ["file", "list", "vector", "table", "scalar", "verbatim"],
 880            ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"],
 881            ["replace", "silent", "none", "discard", "append", "prepend"],
 882            ["output", "value"],
 883        ]
 884
 885        init(block: SrcBlockInfo, model: DocumentModel, text: NSString, extra: [[(String, String)]] = [], inline: Bool = false) throws {
 886            var layers: [[(String, String)]] = []
 887            let language = block.language ?? ""
 888            // `org-babel-params-from-properties`: the inherited `header-args`, then the inherited
 889            // `header-args:LANG`, each the nearest value with `+` additions after it.
 890            var levels = [model.fileProperties]
 891            if let heading = block.heading {
 892                levels += (model.ancestors(of: heading).reversed() + [heading]).map { model.headings[$0].properties }
 893            }
 894            for key in ["header-args", "header-args:\(language)"] {
 895                var value: String?
 896                for entries in levels {
 897                    for entry in entries where entry.key.lowercased() == key {
 898                        value = entry.additive ? [value, entry.value].compactMap { $0 }.joined(separator: " ") : entry.value
 899                    }
 900                }
 901                if let value { layers.append(Params.parse(value)) }
 902            }
 903            let firstLine = inline ? "" : text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0)))
 904            if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) {
 905                var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
 906                while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") {
 907                    rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces)
 908                }
 909                layers.append(Params.parse(rest))
 910            }
 911            // `#+HEADER:` lines above the block.
 912            var headers: [String] = []
 913            var location = block.range.lowerBound
 914            while !inline, location > 0 {
 915                let previous = text.lineRange(for: NSRange(location: location - 1, length: 0))
 916                let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines)
 917                guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break }
 918                if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) }
 919                location = previous.location
 920            }
 921            for header in headers { layers.append(Params.parse(header)) }
 922            layers += extra
 923
 924            for layer in layers {
 925                for (key, raw) in layer {
 926                    let quoted = key != ":var" && raw.count >= 2 && raw.hasPrefix("\"") && raw.hasSuffix("\"")
 927                    let value = quoted ? Params.unescape(String(raw.dropFirst().dropLast())) : raw
 928                    if key != ":var" {
 929                        if !quoted, let first = value.first, "('`[".contains(first) { lisp.insert(key) } else { lisp.remove(key) }
 930                        if quoted { self.quoted.insert(key) } else { self.quoted.remove(key) }
 931                    }
 932                    switch key {
 933                    case ":results":
 934                        for word in value.split(whereSeparator: \.isWhitespace).map(String.init) {
 935                            if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } }
 936                            results.removeAll { $0 == word }
 937                            results.insert(word, at: 0)
 938                        }
 939                    case ":var":
 940                        for value in Params.splitVars(value) {
 941                            guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") }
 942                            let name = value[..<eq].trimmingCharacters(in: .whitespaces)
 943                            let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces)
 944                            vars.removeAll { $0.name == name }
 945                            vars.append((name, assigned))
 946                        }
 947                    case ":wrap":
 948                        wrap = value
 949                    default:
 950                        single[key] = value
 951                    }
 952                }
 953            }
 954        }
 955
 956        /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and
 957        /// parentheses.
 958        /// A Lisp string's contents as `read` gives them.
 959        static func unescape(_ s: String) -> String {
 960            var out = ""
 961            var escaped = false
 962            for c in s {
 963                if escaped {
 964                    switch c {
 965                    case "n": out.append("\n")
 966                    case "t": out.append("\t")
 967                    default: out.append(c)
 968                    }
 969                    escaped = false
 970                } else if c == "\\" {
 971                    escaped = true
 972                } else {
 973                    out.append(c)
 974                }
 975            }
 976            return out
 977        }
 978
 979        /// `org-babel-parse-multiple-vars`: one `:var` value holding several assignments split
 980        /// on spaces outside quotes and brackets, pieces split beside `=` joined again.
 981        static func splitVars(_ value: String) -> [String] {
 982            var pieces: [String] = []
 983            var current = ""
 984            var depth = 0
 985            var quoted = false
 986            var previous: Character = " "
 987            for c in value {
 988                if c == "\"", previous != "\\" { quoted.toggle() }
 989                previous = c
 990                if !quoted, "([{".contains(c) { depth += 1 }
 991                if !quoted, ")]}".contains(c) { depth = max(0, depth - 1) }
 992                if c == " ", !quoted, depth == 0 {
 993                    if !current.isEmpty { pieces.append(current) }
 994                    current = ""
 995                } else {
 996                    current.append(c)
 997                }
 998            }
 999            if !current.isEmpty { pieces.append(current) }
1000            var joined: [String] = []
1001            for piece in pieces {
1002                if let last = joined.last, last.hasSuffix("=") || piece.hasPrefix("=") {
1003                    joined[joined.count - 1] = last + piece
1004                } else {
1005                    joined.append(piece)
1006                }
1007            }
1008            return joined.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
1009        }
1010
1011        static func parse(_ text: String) -> [(String, String)] {
1012            var parts: [String] = []
1013            var current = ""
1014            var depth = 0
1015            var quoted = false
1016            var previous: Character = " "
1017            for c in text {
1018                if c == "\"", previous != "\\" { quoted.toggle() }
1019                if !quoted {
1020                    if c == "(" { depth += 1 }
1021                    if c == ")" { depth = max(0, depth - 1) }
1022                }
1023                if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" {
1024                    parts.append(current)
1025                    current = ""
1026                }
1027                current.append(c)
1028                previous = c
1029            }
1030            parts.append(current)
1031            var pairs: [(String, String)] = []
1032            for part in parts {
1033                let trimmed = part.trimmingCharacters(in: .whitespaces)
1034                guard trimmed.hasPrefix(":") else { continue }
1035                let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased()
1036                // Quotes stay until the value is used, so a quoted string isn't taken for Lisp.
1037                pairs.append((key, trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces)))
1038            }
1039            return pairs
1040        }
1041    }
1042
1043    // MARK: - Variables
1044
1045    /// A referenced block's result as a `:var` value.
1046    static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue {
1047        switch value(finish, output) {
1048        case .none: return .scalar("")
1049        case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s)
1050        case .table(let rows): return .table(rows.map { $0?.map(cell) })
1051        }
1052    }
1053
1054    enum VarValue: Equatable, Sendable {
1055        case scalar(String)
1056        case number(String)
1057        /// Rows; nil is a rule (`hline`).
1058        case table([[Cell]?])
1059        case list([Cell])
1060    }
1061
1062    enum Cell: Equatable, Sendable {
1063        case text(String)
1064        case number(String)
1065    }
1066
1067    /// `org-babel--string-to-number`, keeping Emacs's printed form.
1068    static func number(_ s: String) -> String? {
1069        let t = s.trimmingCharacters(in: .whitespaces)
1070        guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil }
1071        if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil {
1072            var digits = t.hasSuffix(".") ? String(t.dropLast()) : t
1073            let negative = digits.hasPrefix("-")
1074            if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() }
1075            digits = String(digits.drop { $0 == "0" })
1076            if digits.isEmpty { return "0" }
1077            return (negative ? "-" : "") + digits
1078        }
1079        guard t.range(of: "^[-+]?([0-9]+\\.[0-9]+|[0-9]*\\.[0-9]+|[0-9]+(\\.[0-9]*)?e[-+]?[0-9]+|[0-9]*\\.[0-9]+e[-+]?[0-9]+)$", options: .regularExpression) != nil,
1080              let d = Double(t) else { return nil }
1081        return emacsFloat(d)
1082    }
1083
1084    /// How Emacs prints a float.
1085    static func emacsFloat(_ d: Double) -> String {
1086        if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) }
1087        return "\(d)"
1088    }
1089
1090    static func cell(_ s: String) -> Cell {
1091        var t = s
1092        if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) }
1093        return number(t).map(Cell.number) ?? .text(t)
1094    }
1095
1096    /// `name` or `name(args)` naming a src block in the file: the block and its call arguments.
1097    static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? {
1098        guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/),
1099              let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil }
1100        return (block, m.2.map(String.init))
1101    }
1102
1103    /// The blocks `params`' references run, directly or through theirs.
1104    static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] {
1105        var found: [SrcBlockInfo] = []
1106        var seen = seen
1107        for value in params.vars.map(\.value) + [params.single[":stdin"]].compactMap({ $0 }) {
1108            guard let (block, arguments) = referencedBlock(value, model: model), let name = block.name, seen.insert(name).inserted else { continue }
1109            found.append(block)
1110            let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
1111            if let inner = try? Params(block: block, model: model, text: text, extra: extra) {
1112                found += referencedBlocks(inner, model: model, text: text, seen: seen)
1113            }
1114        }
1115        return found
1116    }
1117
1118    /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src
1119    /// blocks, which run first (`Needed`) and give their result.
1120    static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue {
1121        if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) }
1122        if let n = number(value) { return .number(n) }
1123        if let first = value.first, "('`[".contains(first) { return try lispValue(value) }
1124        if let known = refs.resolved[value] { return known }
1125        if let (block, arguments) = referencedBlock(value, model: model), let name = block.name {
1126            guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") }
1127            let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
1128            var inner = refs
1129            inner.visiting.insert(name)
1130            var params = try Params(block: block, model: model, text: text, extra: extra)
1131            params.evaluateLisp(file: refs.options.file)
1132            // A cached block gives its result without running, as `org-babel-execute-src-block` does.
1133            var useCache = true
1134            if params.single[":cache"] == "yes", let language = block.language {
1135                let tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: text, refs: inner)) }, params: params)
1136                let body = nowebEvaluates(params.single[":noweb"]) ? try expandNoweb(block, params: params, model: model, text: text) : normalizedBody(block)
1137                let state = try cacheState(language: language, params: params, tables: tables, body: body, location: block.range, name: name, call: false, text: text, options: refs.options)
1138                if state.current {
1139                    if let value = state.value { return value }
1140                    useCache = false
1141                }
1142            }
1143            switch plan(block, params: params, model: model, text: text,
1144                        options: refs.options, location: block.range, name: name, refs: inner, useCache: useCache) {
1145            case .failure(let failure): throw failure
1146            case .success(let job):
1147                throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job))
1148            }
1149        }
1150        if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
1151        // A named element: `#+NAME: value` above a table or list.
1152        let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
1153        guard let r = (text as String).range(of: pattern, options: .regularExpression) else {
1154            throw Failure.message("Can't find \(value) for :var.")
1155        }
1156        let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String)))
1157        var location = start
1158        var rows: [[Cell]?] = []
1159        var items: [Cell] = []
1160        while location < text.length {
1161            let lineRange = text.lineRange(for: NSRange(location: location, length: 0))
1162            let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines)
1163            let trimmed = line.trimmingCharacters(in: .whitespaces)
1164            if trimmed.hasPrefix("|") {
1165                if trimmed.hasPrefix("|-") {
1166                    rows.append(nil)
1167                    location = NSMaxRange(lineRange)
1168                    continue
1169                }
1170                let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
1171                rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
1172            } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty {
1173                items.append(cell(String(m.1)))
1174            } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) {
1175                if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") {
1176                    throw Failure.message("Using a src block's result in :var isn't supported yet.")
1177                }
1178                break
1179            } else {
1180                break
1181            }
1182            location = NSMaxRange(lineRange)
1183        }
1184        if !rows.isEmpty { return .table(rows) }
1185        if !items.isEmpty { return .list(items) }
1186        throw Failure.message("\(value) isn't a table or list.")
1187    }
1188
1189    /// `org-babel-sh-var-to-string`: a table's rows as tab-separated lines, a list's items as
1190    /// lines.
1191    static func shellString(_ value: VarValue, separator: String? = nil, hline: String? = nil) -> String {
1192        switch value {
1193        case .scalar(let s), .number(let s): return s
1194        case .list(let items): return items.map(cellText).joined(separator: "\n")
1195        case .table(let rows): return rows.compactMap { $0?.map(cellText).joined(separator: separator ?? "\t") ?? hline }.joined(separator: "\n")
1196        }
1197    }
1198
1199    /// `org-babel-variable-assignments:shell`, by the shell's name: for bash, an array for a
1200    /// list and an associative array for a table of two or more columns; `set` for fish; a
1201    /// quoted string otherwise.
1202    static func shellAssignments(_ vars: [(String, VarValue)], shell: String, params: Params) -> [String] {
1203        let separator = params.single[":separator"]
1204        let hline = params.single[":hlines"] == "yes" ? params.single[":hline-string"] ?? "hline" : nil
1205        func quoted(_ value: VarValue) -> String {
1206            "'" + shellString(value, separator: separator, hline: hline).replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
1207        }
1208        return vars.map { name, value in
1209            if shell.hasSuffix("bash") {
1210                switch value {
1211                case .table(let rows) where (rows.first ?? nil).map({ $0.count >= 2 }) ?? false:
1212                    let entries = rows.compactMap { $0 }.map { row in
1213                        "\(name)[\(quoted(.scalar(cellText(row[0]))))]=\(quoted(.list(Array(row.dropFirst()))))"
1214                    }
1215                    return (["unset \(name)", "declare -A \(name)"] + entries).joined(separator: "\n")
1216                case .table(let rows):
1217                    let items = rows.map { $0.map { quoted(.list($0)) } ?? quoted(.scalar("hline")) }
1218                    return "unset \(name)\ndeclare -a \(name)=( \(items.joined(separator: " ")) )"
1219                case .list(let items):
1220                    return "unset \(name)\ndeclare -a \(name)=( \(items.map { quoted(.scalar(cellText($0))) }.joined(separator: " ")) )"
1221                case .scalar, .number:
1222                    break
1223                }
1224            }
1225            return (shell.hasSuffix("fish") ? "set \(name) " : "\(name)=") + quoted(value)
1226        }
1227    }
1228
1229    /// `org-babel-python-var-to-python`.
1230    static func pythonLiteral(_ value: VarValue) -> String {
1231        func cell(_ c: Cell) -> String {
1232            switch c {
1233            case .number(let n): return n
1234            case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
1235            }
1236        }
1237        switch value {
1238        case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
1239        case .number(let n): return n
1240        case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
1241        case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", ") + "]" } ?? "None" }.joined(separator: ", ") + "]"
1242        }
1243    }
1244
1245    /// `prin1` of a string.
1246    static func lispString(_ s: String, triple: Bool = false) -> String {
1247        let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
1248        return triple ? "\"\"" + quoted + "\"\"" : quoted
1249    }
1250
1251    static func lispLiteral(_ value: VarValue) -> String {
1252        func cell(_ c: Cell) -> String {
1253            switch c {
1254            case .number(let n): return n
1255            case .text(let s): return lispString(s)
1256            }
1257        }
1258        switch value {
1259        case .scalar(let s): return lispString(s)
1260        case .number(let n): return n
1261        case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")"
1262        case .table(let rows): return "(" + rows.map { $0.map { "(" + $0.map(cell).joined(separator: " ") + ")" } ?? "hline" }.joined(separator: " ") + ")"
1263        }
1264    }
1265
1266    // MARK: - Python
1267
1268    /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint`
1269    /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables,
1270    /// otherwise `str`.
1271    static let pythonFormatter = """
1272    def __orgstar_format(value, path, params):
1273        def rows(v):
1274            if isinstance(v, dict):
1275                return [(k, rows(x)) for k, x in v.items()]
1276            if isinstance(v, (list, tuple)):
1277                return [rows(x) for x in v]
1278            return v
1279        with open(path, 'w') as out:
1280            if 'pp' in params:
1281                import pprint
1282                out.write(pprint.pformat(value))
1283            elif 'list' in params and isinstance(value, dict):
1284                out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()]))
1285            else:
1286                if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params:
1287                    value = rows(value)
1288                out.write(str(value))
1289
1290    """
1291
1292    /// `org-babel-python--shift-right`: four spaces more on every line outside strings.
1293    static func shiftRight(_ body: String) -> String {
1294        var inString: String?
1295        var lines: [String] = []
1296        for line in body.components(separatedBy: "\n") {
1297            lines.append(inString == nil ? "    " + line : line)
1298            var i = line.startIndex
1299            while i < line.endIndex {
1300                if let delimiter = inString {
1301                    if line[i...].hasPrefix(delimiter) {
1302                        inString = nil
1303                        i = line.index(i, offsetBy: 3)
1304                        continue
1305                    }
1306                } else if line[i] == "#" {
1307                    break
1308                } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") {
1309                    inString = String(line[i...].prefix(3))
1310                    i = line.index(i, offsetBy: 3)
1311                    continue
1312                } else if line[i] == "\"" || line[i] == "'" {
1313                    let quote = line[i]
1314                    i = line.index(after: i)
1315                    while i < line.endIndex, line[i] != quote {
1316                        if line[i] == "\\" { i = line.index(after: i) }
1317                        if i < line.endIndex { i = line.index(after: i) }
1318                    }
1319                }
1320                if i < line.endIndex { i = line.index(after: i) }
1321            }
1322        }
1323        return lines.joined(separator: "\n")
1324    }
1325
1326    // MARK: - Emacs Lisp
1327
1328    /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows
1329    /// when it is a table.
1330    static func emacsScript(form: String, params: [String]) -> String {
1331        """
1332        ;;; -*- lexical-binding: t -*-
1333        (require 'cl-lib)
1334        (require 'json)
1335        (let* ((result \(form))
1336               (print-level nil)
1337               (print-length nil)
1338               (cell (lambda (c) (if (stringp c) c (format "%s" c))))
1339               (tabulable (and (proper-list-p result)
1340                               (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result)))
1341               (rows (and tabulable result
1342                          (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result)
1343                              (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result)
1344                            (list (vconcat (mapcar cell result)))))))
1345          (princ (json-encode `((s . ,(format "%s" result))
1346                                (S . ,(format "%S" result))
1347                                (string . ,(if (stringp result) t :json-false))
1348                                (rows . ,(if rows (vconcat rows) :json-null))))))
1349        """
1350    }
1351
1352    /// An Emacs Lisp job run by `Elisp` instead of Emacs: the output `emacsScript` would print.
1353    /// A Lisp error fails the run, as it does in Emacs; nil when the block uses what `Elisp`
1354    /// doesn't have.
1355    public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? {
1356        guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil }
1357        let lisp = Elisp()
1358        let result: Sexp
1359        do {
1360            result = try lisp.eval(sexp)
1361        } catch is Elisp.Unsupported {
1362            return nil
1363        } catch {
1364            throw .message("\(error)")
1365        }
1366        func cell(_ c: Sexp) -> String { Elisp.printed(c) }
1367        func isProper(_ v: Sexp) -> Bool {
1368            if case .list = v { return true }
1369            return Elisp.isNil(v)
1370        }
1371        func isAtom(_ v: Sexp) -> Bool {
1372            switch v {
1373            case .list(let items): items.isEmpty
1374            case .dotted: false
1375            default: true
1376            }
1377        }
1378        var rows: [Any] = []
1379        if case .list(let items) = result, items.allSatisfy({ isAtom($0) || isProper($0) }) {
1380            if items.allSatisfy({ $0 == .symbol("hline") || isProper($0) }) {
1381                rows = items.map { $0 == .symbol("hline") ? "hline" as Any : ((try? Elisp.elements($0)) ?? []).map(cell) as Any }
1382            } else {
1383                rows = [items.map(cell)]
1384            }
1385        }
1386        var object: [String: Any] = ["s": Elisp.printed(result), "S": Elisp.printed(result, escape: true), "string": result.string != nil]
1387        object["rows"] = rows.isEmpty ? NSNull() : rows
1388        guard let data = try? JSONSerialization.data(withJSONObject: object), let json = String(data: data, encoding: .utf8) else { return nil }
1389        return BabelOutput(stdout: lisp.standardOutput + json, stderr: lisp.messages)
1390    }
1391
1392    // MARK: - Finishing
1393
1394    /// What the run produced, as Babel holds it before inserting.
1395    enum Value: Equatable {
1396        case none
1397        case string(String)
1398        /// Rows of cells; nil rows are rules.
1399        case table([[String]?])
1400    }
1401
1402    /// The edit that writes the run's result under the block, or why it can't.
1403    public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> {
1404        let ns = text as NSString
1405        var blockRange = job.block
1406        if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText {
1407            let found = ns.range(of: job.blockText)
1408            guard found.location != NSNotFound,
1409                  ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else {
1410                return .failure(.message("The block changed while it ran; the result wasn't written."))
1411            }
1412            blockRange = found.location..<NSMaxRange(found)
1413        }
1414        let value = Self.value(job.finish, output)
1415        if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
1416        let buffer = EmacsBuffer(text, point: 0, settings: settings)
1417        if job.finish.inline {
1418            do {
1419                try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer)
1420            } catch let error as Failure {
1421                return .failure(error)
1422            } catch {
1423                return .failure(.message("\(error)"))
1424            }
1425            return .success(TextEdit.between(text, buffer.text as String))
1426        }
1427        insertResult(value, job.finish, block: blockRange, buffer: buffer)
1428        return .success(TextEdit.between(text, buffer.text as String))
1429    }
1430
1431    /// The language's result handling: `org-babel-result-cond` and the table import.
1432    static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
1433        reassemble(rawValue(finish, output), finish)
1434    }
1435
1436    static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
1437        let params = finish.params
1438        if params.contains("file") {
1439            // `org-babel-result-to-file`: a link to `:file`, or to the result as a path.
1440            let path = finish.file ?? rawResult(finish, output)
1441            var link = "[[file:" + path + "]"
1442            if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
1443            return .string(link + "]")
1444        }
1445        let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
1446            || params.contains("pp") || params.contains("file")
1447            || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
1448        switch finish.kind {
1449        case .shell(let valueIsExitStatus):
1450            var results = output.stdout
1451            if valueIsExitStatus {
1452                results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? ""
1453            }
1454            if scalar { return .string(results) }
1455            return importTable(results)
1456        case .generic:
1457            return .string(output.stdout)
1458        case .python:
1459            let raw = finish.output ? output.stdout : (output.resultFile ?? "")
1460            if scalar { return .string(raw) }
1461            return pythonValue(raw)
1462        case .emacsLisp:
1463            guard let data = output.stdout.data(using: .utf8),
1464                  let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) }
1465            if scalar {
1466                return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "")
1467            }
1468            if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") }
1469            if let rows = object["rows"] as? [Any] {
1470                return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) })
1471            }
1472            let printed = object["S"] as? String ?? ""
1473            return printed == "nil" ? .none : .string(printed)
1474        }
1475    }
1476
1477    /// The result as the program left it, before tables are read.
1478    static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String {
1479        switch finish.kind {
1480        case .python: return finish.output ? output.stdout : (output.resultFile ?? "")
1481        case .emacsLisp:
1482            guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
1483            return object["s"] as? String ?? ""
1484        case .shell(let valueIsExitStatus):
1485            return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
1486        case .generic: return output.stdout
1487        }
1488    }
1489
1490    /// With `:results file` and `:file`, what to write there, relative to the run's folder;
1491    /// nil when there's nothing to write or the program wrote it.
1492    public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? {
1493        guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil }
1494        return (file, rawResult(job.finish, output))
1495    }
1496
1497    /// `org-babel-import-elisp-from-file`.
1498    static func importTable(_ results: String) -> Value {
1499        guard !results.isEmpty else { return .none }
1500        var lines = results.components(separatedBy: "\n")
1501        if lines.last == "" { lines.removeLast() }
1502        let nonEmpty = lines.filter { !$0.isEmpty }
1503        let rows: [[String]]
1504        if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) {
1505            rows = lines.map { $0.components(separatedBy: "\t") }
1506        } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) {
1507            rows = lines.map(csvFields)
1508        } else if lines.count == 1 {
1509            rows = [[lines[0]]]
1510        } else {
1511            rows = lines.map { line in
1512                let trimmed = line.drop { $0 == " " }
1513                return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty
1514                    ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
1515            }
1516        }
1517        let cells = rows.map { row in row.map { field -> String in
1518            let trimmed = field.trimmingCharacters(in: .whitespaces)
1519            switch cell(trimmed) {
1520            case .number(let n): return n
1521            case .text(let t): return t
1522            }
1523        } }
1524        if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) }
1525        return .table(cells)
1526    }
1527
1528    static func csvFields(_ line: String) -> [String] {
1529        var fields: [String] = []
1530        var current = ""
1531        var quoted = false
1532        for c in line {
1533            if c == "\"" {
1534                quoted.toggle()
1535            } else if c == ",", !quoted {
1536                fields.append(current.trimmingCharacters(in: .whitespaces))
1537                current = ""
1538            } else {
1539                current.append(c)
1540            }
1541        }
1542        fields.append(current.trimmingCharacters(in: .whitespaces))
1543        return fields
1544    }
1545
1546    /// `org-babel-python-table-or-string`.
1547    static func pythonValue(_ raw: String) -> Value {
1548        guard let first = raw.first, let last = raw.last, raw.count >= 2,
1549              (first == "[" && last == "]") || (first == "(" && last == ")") else {
1550            if raw.isEmpty { return .string("") }
1551            if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) {
1552                return .string(String(raw.dropFirst().dropLast()))
1553            }
1554            if let n = number(raw) { return .string(n) }
1555            return .string(raw)
1556        }
1557        var parser = PythonLiteral(Array(raw))
1558        guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) }
1559        func text(_ v: PythonLiteral.Node) -> String {
1560            switch v {
1561            case .atom(let s): return s
1562            case .string(let s): return s
1563            case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")"
1564            }
1565        }
1566        if items.allSatisfy({ if case .list = $0 { return true }; if case .atom("None") = $0 { return true }; return false }) {
1567            return .table(items.map { item -> [String]? in
1568                if case .list(let cells) = item { return cells.map(text) }
1569                return nil
1570            })
1571        }
1572        return .table([items.map { if case .atom("None") = $0 { return "hline" }; return text($0) }])
1573    }
1574
1575    struct PythonLiteral {
1576        indirect enum Node: Equatable {
1577            case atom(String)
1578            case string(String)
1579            case list([Node])
1580        }
1581
1582        let chars: [Character]
1583        var i = 0
1584        init(_ chars: [Character]) { self.chars = chars }
1585        var atEnd: Bool { mutating get { skip(); return i == chars.count } }
1586
1587        mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } }
1588
1589        mutating func parse() -> Node? {
1590            skip()
1591            guard i < chars.count else { return nil }
1592            let c = chars[i]
1593            if c == "[" || c == "(" {
1594                let close: Character = c == "[" ? "]" : ")"
1595                i += 1
1596                var items: [Node] = []
1597                skip()
1598                if i < chars.count, chars[i] == close {
1599                    i += 1
1600                    return .list(items)
1601                }
1602                while true {
1603                    guard let item = parse() else { return nil }
1604                    items.append(item)
1605                    skip()
1606                    guard i < chars.count else { return nil }
1607                    if chars[i] == "," {
1608                        i += 1
1609                        skip()
1610                        if i < chars.count, chars[i] == close {
1611                            i += 1
1612                            return .list(items)
1613                        }
1614                        continue
1615                    }
1616                    if chars[i] == close {
1617                        i += 1
1618                        return .list(items)
1619                    }
1620                    return nil
1621                }
1622            }
1623            if c == "'" || c == "\"" {
1624                i += 1
1625                var s = ""
1626                while i < chars.count, chars[i] != c {
1627                    if chars[i] == "\\", i + 1 < chars.count {
1628                        i += 1
1629                        switch chars[i] {
1630                        case "n": s.append("\n")
1631                        case "t": s.append("\t")
1632                        default: s.append(chars[i])
1633                        }
1634                    } else {
1635                        s.append(chars[i])
1636                    }
1637                    i += 1
1638                }
1639                guard i < chars.count else { return nil }
1640                i += 1
1641                return .string(s)
1642            }
1643            var s = ""
1644            while i < chars.count, !",)] \n".contains(chars[i]) {
1645                s.append(chars[i])
1646                i += 1
1647            }
1648            guard !s.isEmpty else { return nil }
1649            return .atom(number(s) ?? s)
1650        }
1651    }
1652
1653    // MARK: - Inserting
1654
1655    static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:"
1656
1657    /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results
1658    /// keyword, added when there is none.
1659    /// The `#+RESULTS` line of a block's results (`org-babel-where-is-src-block-result`):
1660    /// the one naming `name`, or for an unnamed block an empty one right after it.
1661    static func existingResults(name: String?, block: Range<Int>, text ns: NSString) -> Int? {
1662        if let name {
1663            let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
1664            let regex = try! NSRegularExpression(pattern: pattern)
1665            return regex.firstMatch(in: ns as String, range: NSRange(location: 0, length: ns.length))?.range.location
1666        }
1667        // The element after the block, past blank lines.
1668        var location = block.upperBound
1669        while location < ns.length {
1670            let line = ns.lineRange(for: NSRange(location: location, length: 0))
1671            let content = ns.substring(with: line)
1672            if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1673                location = NSMaxRange(line)
1674                continue
1675            }
1676            if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil {
1677                return line.location
1678            }
1679            break
1680        }
1681        return nil
1682    }
1683
1684    /// The hash in the `#+RESULTS[…]:` line at `line` (`org-babel-result-regexp`).
1685    static func resultsHash(at line: Int, text ns: NSString) -> String? {
1686        let content = ns.substring(with: ns.lineRange(for: NSRange(location: line, length: 0)))
1687        return content.firstMatch(of: #/(?i)^[ \t]*#\+results\[(?:\(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\) )?([0-9a-f]+)\]:/#).map { String($0.1) }
1688    }
1689
1690    static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int {
1691        if let line = existingResults(name: finish.name, block: block, text: buffer.text) {
1692            // `org-babel--clear-results-maybe`: a different hash clears the results and
1693            // rewrites the keyword.
1694            if let hash = finish.hash, resultsHash(at: line, text: buffer.text) != hash {
1695                buffer.point = line
1696                let indent = String(buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == " " || $0 == "\t" })
1697                buffer.forwardLine(1)
1698                let contents = buffer.point
1699                buffer.deleteRegion(contents, max(contents, resultEnd(buffer)))
1700                buffer.deleteRegion(line, contents)
1701                buffer.point = line
1702                buffer.insert(indent + "#+RESULTS[\(hash)]:" + (finish.name.map { " " + $0 } ?? "") + "\n")
1703                if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
1704                    buffer.saveExcursion { buffer.insert("\n") }
1705                }
1706            }
1707            return line
1708        }
1709        // A new keyword after the block.
1710        buffer.point = min(block.upperBound, buffer.length)
1711        buffer.skipBackward([32, 9, 10, 13])
1712        buffer.forwardLine(1)
1713        if !buffer.bolp { buffer.insert("\n") }
1714        let indent = buffer.saveExcursion { () -> String in
1715            buffer.point = block.lowerBound
1716            let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
1717            return String(line.prefix { $0 == " " || $0 == "\t" })
1718        }
1719        buffer.insert("\n")
1720        let keywordLine = buffer.point
1721        buffer.insert(indent + "#+RESULTS" + (finish.hash.map { "[\($0)]" } ?? "") + ":" + (finish.name.map { " " + $0 } ?? "") + "\n")
1722        if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
1723            buffer.saveExcursion { buffer.insert("\n") }
1724        }
1725        return keywordLine
1726    }
1727
1728    /// `org-babel-result-end` with point at the start of the result.
1729    static func resultEnd(_ buffer: EmacsBuffer) -> Int {
1730        let start = buffer.point
1731        let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start))
1732        if line.trimmingCharacters(in: .whitespaces).isEmpty { return start }
1733        if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil {
1734            return min(buffer.length, buffer.lineEnd(start) + 1)
1735        }
1736        let tree = OrgParser.parse(buffer.text as String)
1737        var node = tree.root
1738        var found: SyntaxNode?
1739        while let child = node.child(containing: start) {
1740            if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) {
1741                if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) {
1742                    found = child
1743                    break
1744                }
1745            }
1746            node = child
1747        }
1748        guard let element = found else { return start }
1749        var end = element.range.upperBound
1750        while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 }
1751        return min(buffer.length, buffer.lineEnd(end) + 1)
1752    }
1753
1754    /// `org-babel-insert-result` for a src block.
1755    /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already
1756    /// there; raw results go in as they are.
1757    static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws {
1758        var string: String
1759        switch value {
1760        case .none: string = ""
1761        case .string(let s): string = s
1762        case .table(let rows):
1763            let cells = rows.compactMap { $0 }
1764            guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") }
1765            string = cells[0][0]
1766        }
1767        buffer.point = object.upperBound
1768        if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") {
1769            buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound)
1770        }
1771        if finish.params.contains("raw") {
1772            buffer.insert(" " + string)
1773            return
1774        }
1775        if string.hasSuffix("\n") { string.removeLast() }
1776        guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") }
1777        buffer.insert(" {{{results(=" + string + "=)}}}")
1778    }
1779
1780    static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) {
1781        let params = finish.params
1782        let keyword = resultsLine(finish, block: block, buffer: buffer)
1783        buffer.point = keyword
1784        let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count
1785        buffer.forwardLine(1)
1786        if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") }
1787        var beg = buffer.point
1788        if params.contains("replace") {
1789            buffer.deleteRegion(beg, resultEnd(buffer))
1790            buffer.point = beg
1791        } else if params.contains("append") {
1792            buffer.point = resultEnd(buffer)
1793            beg = buffer.point
1794        }
1795        var tabulated = false
1796        switch value {
1797        case .none:
1798            break
1799        case .string(var s) where params.contains("list"):
1800            if s.last != "\n" { s += "\n" }
1801            let items = s.split(separator: "\n", omittingEmptySubsequences: true)
1802            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1803        case .table(let rows) where params.contains("list"):
1804            let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
1805            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1806        case .table(let rows):
1807            tabulated = true
1808            let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" }
1809            let start = buffer.point
1810            buffer.insert(lines.joined(separator: "\n") + "\n")
1811            buffer.point = start
1812            buffer.tableAlign()
1813            buffer.point = buffer.tableEnd()
1814        case .string(var s):
1815            if !s.isEmpty, s.last != "\n" { s += "\n" }
1816            buffer.insert(s)
1817        }
1818        let end = buffer.marker(buffer.point, advances: true)
1819        defer { buffer.release(end) }
1820        func wrap(_ open: String, _ close: String, escape: Bool) {
1821            buffer.point = end.position
1822            buffer.insert(close + "\n")
1823            buffer.point = beg
1824            buffer.insert(open + "\n")
1825            if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) }
1826        }
1827        if let wrapValue = finish.wrap {
1828            let full = wrapValue.isEmpty ? "results" : wrapValue
1829            let type = String(full.split(separator: " ").first ?? "results")
1830            if type.lowercased() != "nil", type.lowercased() != "no" {
1831                wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true)
1832            }
1833        } else if params.contains("html") {
1834            wrap("#+begin_export html", "#+end_export", escape: true)
1835        } else if params.contains("latex") {
1836            wrap("#+begin_export latex", "#+end_export", escape: true)
1837        } else if params.contains("org") {
1838            wrap("#+begin_src org", "#+end_src", escape: true)
1839        } else if params.contains("code") {
1840            wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true)
1841        } else if params.contains("raw") || params.contains("file") {
1842            // As inserted.
1843        } else if params.contains("drawer") {
1844            wrap(":results:", ":end:", escape: false)
1845        } else if !tabulated, !params.contains("list") {
1846            examplify(buffer, beg, end.position)
1847        }
1848        if indent > 0, !(tabulated && params.contains("append")) {
1849            buffer.point = beg
1850            while buffer.point < end.position {
1851                if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) }
1852                if buffer.forwardLine(1) != 0 { break }
1853            }
1854        }
1855    }
1856
1857    /// `org-escape-code-in-region`.
1858    static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) {
1859        buffer.point = start
1860        let stop = buffer.marker(end)
1861        defer { buffer.release(stop) }
1862        while buffer.point < stop.position {
1863            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
1864            if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) {
1865                buffer.point += line[..<m.1.startIndex].utf16.count
1866                buffer.insert(",")
1867            }
1868            if buffer.forwardLine(1) != 0 { break }
1869        }
1870    }
1871
1872    /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
1873    static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
1874        let text = buffer.substring(beg, end)
1875        var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0)
1876        if text.isEmpty { size = 0 }
1877        guard size > 0 else { return }
1878        if size < 10 {
1879            buffer.point = beg
1880            for _ in 0..<size {
1881                buffer.point = buffer.lineStart(buffer.point)
1882                buffer.insert(": ")
1883                buffer.forwardLine(1)
1884            }
1885            return
1886        }
1887        let endMarker = buffer.marker(end)
1888        defer { buffer.release(endMarker) }
1889        buffer.point = beg
1890        buffer.insert("#+begin_example\n")
1891        escapeCode(buffer, from: buffer.point, to: endMarker.position)
1892        buffer.point = endMarker.position
1893        if !buffer.bolp { buffer.insert("\n") }
1894        buffer.insert("#+end_example")
1895        if !buffer.eolp { buffer.insert("\n") }
1896    }
1897}
1898
1899/// C-c C-c in a src block: `org-babel-execute-src-block`.
1900public struct ExecuteSrcBlock: OrgCommand {
1901    public init() {}
1902    public var id: String { "org.babel.execute" }
1903    public var title: String { "Run Source Block" }
1904    public func applies(in context: EditContext) -> Bool { KeyContext.holds("src", in: context) || Self.atCallOrInline(context) }
1905
1906    /// On a `#+CALL:` line or an inline `src_` block.
1907    static func atCallOrInline(_ context: EditContext) -> Bool {
1908        let ns = context.text as NSString
1909        let line = ns.substring(with: ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0)))
1910        if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil { return true }
1911        var node = context.tree.root
1912        while let child = node.child(containing: context.caret) {
1913            if child.kind == .inlineSourceBlock { return true }
1914            node = child
1915        }
1916        return false
1917    }
1918
1919    public func run(in context: EditContext) -> CommandStep {
1920        switch Babel.plan(context) {
1921        case .success(let job): return .external(.babel(job))
1922        case .failure(.message(let message)): return .failed(message)
1923        }
1924    }
1925}