Sources/OrgCore/Compute/Babel.swift

d84591dd4402f983173a2d86d65eef6b24957599
orgstar/Sources/OrgCore/Compute/Babel.swift

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