Sources/OrgCore/Compute/Babel.swift

3ed8024d96095786cc5d67f2e876ba5e08b1c94f
orgstar/Sources/OrgCore/Compute/Babel.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form