Sources/OrgCore/Compute/Babel.swift

25d246e5dfa16b4faebd5370c41244b21f5d3fa1
orgstar/Sources/OrgCore/Compute/Babel.swift

1413 lines · 71105 bytes

   1import Foundation
   2
   3// Babel (ob-core.el, ob-shell.el, ob-python.el, ob-emacs-lisp.el, Org 9.8.7): executing a src
   4// block is planned here, run by the platform, and finished here. The plan resolves header
   5// arguments and refuses anything that would make the run differ from Emacs's; the finish turns
   6// the output into a result the way `org-babel-insert-result` writes it.
   7
   8/// A src block run for the platform to carry out.
   9public struct BabelJob: Sendable, Equatable {
  10    public enum Runner: Sendable, Equatable {
  11        /// An interpreter reading the program on standard input.
  12        case process(executable: String, arguments: [String])
  13        /// `emacs --batch` loading `input` as a script.
  14        case emacs
  15        /// A long-running interpreter named by `:session`: a shell gets `input` as commands, Python
  16        /// runs `input` as a program in its globals.
  17        case session(name: String, executable: String, python: Bool)
  18    }
  19
  20    public let language: String
  21    public let runner: Runner
  22    /// Standard input, or the Emacs script. `Babel.resultFileToken` stands for a file the runner
  23    /// creates; its contents come back as `BabelOutput.resultFile`.
  24    public let input: String
  25    /// `:dir`, relative to the file's folder; nil for the folder itself.
  26    public let directory: String?
  27    /// The block as it was planned, to find it again when the run ends.
  28    public let block: Range<Int>
  29    public let blockText: String
  30    /// Asks every time (`:eval query`) rather than trusting by content.
  31    public let alwaysAsk: Bool
  32    public let finish: Finish
  33    /// A named block a `:var` refers to: run it first, then `Babel.resume` with its output.
  34    public var needs: [Need] = []
  35    /// Values of the references resolved so far, and how to plan again.
  36    var resolved: [String: Babel.VarValue] = [:]
  37    var caret = 0
  38    var options = Babel.Options()
  39
  40    public struct Need: Sendable, Equatable {
  41        /// The `:var` value, `name` or `name(args)`.
  42        public let reference: String
  43        public let job: BabelJob
  44    }
  45
  46    public struct Finish: Sendable, Equatable {
  47        enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp }
  48        let kind: Kind
  49        var language = ""
  50        public internal(set) var params: [String]
  51        let output: Bool
  52        let wrap: String?
  53        let name: String?
  54        /// An inline block: the result goes after it, in `{{{results(…)}}}`.
  55        var inline = false
  56        /// `:file` (under `:output-dir`) with `:results file`, and `:file-desc`.
  57        var file: String?
  58        var fileDescription: String?
  59        /// The program writes `file` itself, as graphics languages do.
  60        var writesFile = false
  61    }
  62}
  63
  64public struct BabelOutput: Sendable, Equatable {
  65    public var stdout: String
  66    public var resultFile: String?
  67    /// What the program wrote to standard error, and its exit status: Emacs shows them in
  68    /// `*Org-Babel Error Output*` and still inserts the results.
  69    public var stderr: String
  70    public var status: Int32
  71    public init(stdout: String, resultFile: String? = nil, stderr: String = "", status: Int32 = 0) {
  72        self.stdout = stdout
  73        self.resultFile = resultFile
  74        self.stderr = stderr
  75        self.status = status
  76    }
  77
  78    /// A line for the message area when the program failed or complained, else nil.
  79    public var problem: String? {
  80        let first = stderr.split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)
  81        switch (status, first) {
  82        case (0, nil): return nil
  83        case (0, let line?): return line
  84        case (let code, nil): return "Exited with status \(code)"
  85        case (let code, let line?): return "Exited with status \(code): \(line)"
  86        }
  87    }
  88}
  89
  90public enum Babel {
  91    public static let resultFileToken = "__ORGSTAR_RESULT_FILE__"
  92    static let shells: Set<String> = ["sh", "bash", "zsh", "shell", "fish", "ksh", "dash", "ash", "csh", "mksh", "posh"]
  93    static let generic: [String: (String, [String])] = [
  94        "ruby": ("ruby", []), "js": ("node", []), "javascript": ("node", []), "R": ("Rscript", ["-"]),
  95        "awk": ("awk", ["-f", "/dev/stdin"]),
  96    ]
  97
  98    public struct Options: Sendable, Equatable {
  99        public var python = "python3"
 100        /// `shell-file-name`, for blocks in the `shell` language.
 101        public var shell = "/bin/sh"
 102        public init() {}
 103    }
 104
 105    // MARK: - Planning
 106
 107    /// The run for the src block at the caret, or why it can't run.
 108    public static func plan(_ context: EditContext, options: Options = Options()) -> Result<BabelJob, Failure> {
 109        plan(context, options: options, resolved: [:])
 110    }
 111
 112    /// Plans the block again with the value of the block `job` needed: the output of
 113    /// `need.job`, as `org-babel-ref-resolve` reads it.
 114    public static func resume(_ job: BabelJob, need: BabelJob.Need, output: BabelOutput, text: String, tree: OrgTree) -> Result<BabelJob, Failure> {
 115        var resolved = job.resolved
 116        resolved[need.reference] = varValue(need.job.finish, output)
 117        let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret])
 118        return plan(context, options: job.options, resolved: resolved)
 119    }
 120
 121    static func plan(_ context: EditContext, options: Options, resolved: [String: VarValue]) -> Result<BabelJob, Failure> {
 122        let text = context.text
 123        let ns = text as NSString
 124        let model = DocumentModel(tree: context.tree)
 125        let refs = References(resolved: resolved, options: options)
 126        func located(_ result: Result<BabelJob, Failure>) -> Result<BabelJob, Failure> {
 127            result.map { job in
 128                var job = job
 129                (job.caret, job.resolved, job.options) = (context.caret, resolved, options)
 130                return job
 131            }
 132        }
 133        do {
 134            if let block = model.srcBlocks.first(where: { $0.range.contains(context.caret) || $0.range.upperBound == context.caret }) {
 135                return located(plan(block, params: try Params(block: block, model: model, text: ns), model: model, text: ns, options: options,
 136                                    location: block.range, name: block.name, refs: refs))
 137            }
 138            if let call = try callAt(context.caret, model: model, text: ns) {
 139                return located(plan(call.block, params: call.params, model: model, text: ns, options: options, location: call.location, name: call.name, refs: refs))
 140            }
 141            if let inline = try inlineAt(context.caret, tree: context.tree, model: model, text: ns) {
 142                return located(plan(inline.block, params: inline.params, model: model, text: ns, options: options, location: inline.block.range, name: nil, inline: true, refs: refs))
 143            }
 144        } catch let error as Failure {
 145            return .failure(error)
 146        } catch {
 147            return .failure(.message("\(error)"))
 148        }
 149        return .failure(.message("Not in a source block"))
 150    }
 151
 152    /// The `#+CALL:` line at `offset`: the block it names, with the call's inside header, its
 153    /// arguments as `:var` and its end header over the block's own (`org-babel-lob-get-info`).
 154    static func callAt(_ offset: Int, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params, location: Range<Int>, name: String?)? {
 155        let lineRange = text.lineRange(for: NSRange(location: min(offset, text.length), length: 0))
 156        let line = text.substring(with: lineRange)
 157        guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+CALL:[ \t]*([^\s(\[]+)(?:\[([^\]]*)\])?\((.*?)\)[ \t]*(.*?)[ \t]*\n?$/#) else { return nil }
 158        let name = String(m.1)
 159        guard let block = model.srcBlocks.first(where: { $0.name == name }) else { throw Failure.message("Reference '\(name)' not found in this buffer") }
 160        var extra: [[(String, String)]] = []
 161        if let inside = m.2 { extra.append(Params.parse(String(inside))) }
 162        extra.append(splitArguments(String(m.3)).map { (":var", $0) })
 163        if !m.4.isEmpty { extra.append(Params.parse(String(m.4))) }
 164        // The call's own #+NAME names its results.
 165        var callName: String?
 166        if lineRange.location > 0 {
 167            let previous = text.substring(with: text.lineRange(for: NSRange(location: lineRange.location - 1, length: 0)))
 168            callName = previous.firstMatch(of: #/(?i)^[ \t]*#\+NAME:[ \t]*(\S+)/#).map { String($0.1) }
 169        }
 170        let location = lineRange.location..<NSMaxRange(lineRange)
 171        return (block, try Params(block: block, model: model, text: text, extra: extra), location, callName)
 172    }
 173
 174    /// Call arguments split on commas outside quotes and parentheses.
 175    static func splitArguments(_ s: String) -> [String] {
 176        var parts: [String] = []
 177        var current = ""
 178        var depth = 0
 179        var quoted = false
 180        for c in s {
 181            if c == "\"" { quoted.toggle() }
 182            if !quoted, c == "(" { depth += 1 }
 183            if !quoted, c == ")" { depth -= 1 }
 184            if c == ",", !quoted, depth == 0 {
 185                parts.append(current)
 186                current = ""
 187            } else {
 188                current.append(c)
 189            }
 190        }
 191        parts.append(current)
 192        return parts.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
 193    }
 194
 195    /// The inline `src_LANG[HEADERS]{BODY}` at `offset`.
 196    static func inlineAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params)? {
 197        var node = tree.root
 198        var found: SyntaxNode?
 199        while let child = node.child(containing: offset) {
 200            if child.kind == .inlineSourceBlock { found = child }
 201            node = child
 202        }
 203        guard let object = found, let m = object.text.firstMatch(of: /^src_([^\s\[{]+)(?:\[([^\]]*)\])?\{(.*)\}$/) else { return nil }
 204        let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= object.range.lowerBound }
 205        let block = SrcBlockInfo(range: object.range, heading: heading, name: nil, language: String(m.1), switches: [], body: String(m.3), headerArguments: [:])
 206        var extra: [[(String, String)]] = [[(":exports", "results"), (":hlines", "yes")]]
 207        if let headers = m.2 { extra.append(Params.parse(String(headers))) }
 208        return (block, try Params(block: block, model: model, text: text, extra: extra, inline: true))
 209    }
 210
 211    /// What `:var` references resolve to while planning.
 212    struct References {
 213        var resolved: [String: VarValue]
 214        var options: Options
 215        /// Blocks being planned for a reference, to stop cycles.
 216        var visiting: Set<String> = []
 217    }
 218
 219    /// A reference to a block that has to run first.
 220    struct Needed: Error {
 221        let need: BabelJob.Need
 222    }
 223
 224    static func plan(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
 225                     location: Range<Int>, name: String?, inline: Bool = false, refs: References? = nil) -> Result<BabelJob, Failure> {
 226        let refs = refs ?? References(resolved: [:], options: options)
 227        guard let language = block.language else { return .failure(.message("This block has no language")) }
 228        let eval = params.single[":eval"]?.lowercased()
 229        if eval == "never" || eval == "no" || eval == "never-export" || eval == "no-export" {
 230            return .failure(.message("Evaluation of this \(language) code block\(block.name.map { " (\($0)) " } ?? " ")is disabled."))
 231        }
 232        if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language) {
 233            return .failure(.message(":cmdline isn't supported yet; nothing was run."))
 234        }
 235        for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil {
 236            return .failure(.message("\(key) isn't supported yet; nothing was run."))
 237        }
 238        let session = params.single[":session"].flatMap { $0 == "none" ? nil : ($0.isEmpty ? "*\(language)*" : $0) }
 239        if session != nil, !shells.contains(language), language != "python" {
 240            return .failure(.message(":session isn't supported for \(language) yet; nothing was run."))
 241        }
 242        if params.single[":cache"] == "yes" { return .failure(.message(":cache isn't supported yet; nothing was run.")) }
 243
 244        var body = normalizedBody(block)
 245        if nowebEvaluates(params.single[":noweb"]) {
 246            do {
 247                body = try expandNoweb(block, params: params, model: model, text: ns)
 248            } catch let error as Failure {
 249                return .failure(error)
 250            } catch {
 251                return .failure(.message("\(error)"))
 252            }
 253        }
 254        let output = params.results.contains("output")
 255        let file = params.single[":file"].map { name in
 256            params.single[":output-dir"].map { $0.hasSuffix("/") ? $0 + name : $0 + "/" + name } ?? name
 257        }
 258        let toFile = params.results.contains("file")
 259        let finishBase = { (kind: BabelJob.Finish.Kind) in
 260            BabelJob.Finish(kind: kind, language: language, params: params.results, output: output, wrap: params.wrap, name: name, inline: inline,
 261                            file: toFile ? file : nil, fileDescription: params.single[":file-desc"])
 262        }
 263        let vars: [(String, VarValue)]
 264        do {
 265            vars = try params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns, refs: refs)) }
 266        } catch let needed as Needed {
 267            // Asked about once, with every block the references reach.
 268            let texts = [ns.substring(with: NSRange(location))] + referencedBlocks(params, model: model, text: ns, seen: []).map { ns.substring(with: NSRange($0.range)) }
 269            return .success(BabelJob(
 270                language: language, runner: .process(executable: "", arguments: []), input: "", directory: params.single[":dir"],
 271                block: location, blockText: texts.joined(separator: "\n"), alwaysAsk: eval == "query", finish: finishBase(.generic), needs: [needed.need]
 272            ))
 273        } catch let error as Failure {
 274            return .failure(error)
 275        } catch {
 276            return .failure(.message("\(error)"))
 277        }
 278        let blockText = ns.substring(with: NSRange(location))
 279        let dir = params.single[":dir"]
 280        let alwaysAsk = eval == "query"
 281
 282        if shells.contains(language) {
 283            let valueIsExitStatus = params.results.contains("value")
 284            var lines: [String] = []
 285            for (name, value) in vars {
 286                let s: String
 287                switch value {
 288                case .scalar(let v), .number(let v): s = v
 289                default: return .failure(.message("Tables and lists in :var aren't supported for \(language) yet."))
 290                }
 291                lines.append("\(name)='" + s.replacingOccurrences(of: "'", with: "'\"'\"'") + "'")
 292            }
 293            let full = (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "")
 294            let executable = language == "shell" ? options.shell : language
 295            return .success(BabelJob(
 296                language: language, runner: session.map { .session(name: $0, executable: executable, python: false) } ?? .process(executable: executable, arguments: []),
 297                input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir,
 298                block: location, blockText: blockText, alwaysAsk: alwaysAsk,
 299                finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
 300            ))
 301        }
 302        if language == "python", let session {
 303            // `org-babel-python--eval-ast`: the body at top level in the session, the value its
 304            // last expression's.
 305            let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
 306            let source = (lines + [body]).joined(separator: "\n")
 307            let literal = String(data: try! JSONSerialization.data(withJSONObject: [source]), encoding: .utf8)!.dropFirst().dropLast()
 308            let program: String
 309            if output {
 310                program = "exec(compile(\(literal), '<org-babel>', 'exec'), globals())\n"
 311            } else {
 312                program = pythonFormatter + """
 313                    import ast as __orgstar_ast
 314                    __orgstar_tree = __orgstar_ast.parse(\(literal))
 315                    __orgstar_last = None
 316                    if __orgstar_tree.body and isinstance(__orgstar_tree.body[-1], __orgstar_ast.Expr):
 317                        __orgstar_last = __orgstar_ast.Expression(__orgstar_tree.body.pop().value)
 318                    exec(compile(__orgstar_tree, '<org-babel>', 'exec'), globals())
 319                    __orgstar_format(eval(compile(__orgstar_last, '<org-babel>', 'eval'), globals()) if __orgstar_last else None, '\(resultFileToken)', [
 320                    """ + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
 321            }
 322            return .success(BabelJob(
 323                language: language, runner: .session(name: session, executable: params.single[":python"] ?? options.python, python: true),
 324                input: program, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.python)
 325            ))
 326        }
 327        if language == "python" {
 328            let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
 329            var full = (lines + [body]).joined(separator: "\n")
 330            if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" }
 331            let input: String
 332            if output {
 333                input = full + "\n"
 334            } else {
 335                input = pythonFormatter + "def main():\n" + shiftRight(full) + "\n\n__orgstar_format(main(), '\(resultFileToken)', ["
 336                    + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
 337            }
 338            return .success(BabelJob(
 339                language: language, runner: .process(executable: params.single[":python"] ?? options.python, arguments: []),
 340                input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
 341                finish: finishBase(.python)
 342            ))
 343        }
 344        if language == "emacs-lisp" || language == "elisp" {
 345            let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
 346            let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n      ")))\n\(body)\n)"
 347            let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)"
 348            return .success(BabelJob(
 349                language: language, runner: .emacs, input: emacsScript(form: form, params: params.results),
 350                directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.emacsLisp)
 351            ))
 352        }
 353        if ["dot", "plantuml", "mermaid"].contains(language) {
 354            // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`.
 355            guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) }
 356            let quoted = "'" + file.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
 357            let ext = (file as NSString).pathExtension.isEmpty ? "png" : (file as NSString).pathExtension
 358            let cmdline = params.single[":cmdline"].map { " " + $0 } ?? ""
 359            var input = body + "\n"
 360            let command: String
 361            switch language {
 362            case "dot":
 363                command = "dot\(cmdline) -T\(ext) -o \(quoted)"
 364            case "plantuml":
 365                if body.range(of: "^[ \\t]*@start", options: .regularExpression) == nil { input = "@startuml\n" + body + "\n@enduml\n" }
 366                command = "plantuml\(cmdline) -p -t\(ext) > \(quoted)"
 367            default:
 368                command = "f=$(mktemp).mmd; cat > \"$f\"; mmdc\(cmdline) -i \"$f\" -o \(quoted); s=$?; rm -f \"$f\"; exit $s"
 369            }
 370            var finish = finishBase(.generic)
 371            finish.file = file
 372            finish.writesFile = true
 373            finish.params = params.results.filter { !["table", "scalar", "verbatim", "list", "vector"].contains($0) } + (params.results.contains("file") ? [] : ["file"])
 374            return .success(BabelJob(
 375                language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", command]),
 376                input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish
 377            ))
 378        }
 379        if let (executable, arguments) = generic[language] {
 380            guard vars.isEmpty else { return .failure(.message(":var isn't supported for \(language) yet.")) }
 381            return .success(BabelJob(
 382                language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
 383                input: body + "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
 384                finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: name, inline: inline)
 385            ))
 386        }
 387        return .failure(.message("No way to run \(language) blocks yet."))
 388    }
 389
 390    public enum Failure: Error, Equatable {
 391        case message(String)
 392    }
 393
 394    // MARK: - Noweb
 395
 396    /// `org-babel-noweb-p` in the `:eval` context.
 397    static func nowebEvaluates(_ value: String?) -> Bool {
 398        (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "no-export", "strip-export", "eval", "strip-tangle"].contains(String($0)) }
 399    }
 400
 401    /// `org-babel-noweb-p` for `:tangle`.
 402    static func nowebTangles(_ value: String?) -> Bool {
 403        (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "tangle", "no-export", "strip-export", "strip-tangle"].contains(String($0)) }
 404    }
 405
 406    /// `org-babel-expand-noweb-references` for evaluation: each `<<name>>` becomes the body of
 407    /// the block named so, or of every block with that `:noweb-ref`, joined by `:noweb-sep`, or
 408    /// the contents of the heading with that ID; the text before it on its line goes before
 409    /// each line it brings.
 410    /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as
 411    /// evaluation does.
 412    static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0) throws -> String {
 413        guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") }
 414        let body = normalizedBody(block)
 415        let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true
 416        func expand(_ other: SrcBlockInfo) throws -> String {
 417            let otherParams = try Params(block: other, model: model, text: text)
 418            let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"])
 419            return expands
 420                ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1)
 421                : normalizedBody(other)
 422        }
 423        func inCommentedHeading(_ b: SrcBlockInfo) -> Bool {
 424            guard let h = b.heading else { return false }
 425            return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
 426        }
 427        let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
 428        let ns = body as NSString
 429        var out = ""
 430        var at = 0
 431        for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
 432            let prefix = ns.substring(with: m.range(at: 1))
 433            let id = ns.substring(with: m.range(at: 3))
 434            out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at))
 435            at = NSMaxRange(m.range)
 436            var expansion = ""
 437            if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
 438                throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.")
 439            } else if let heading = model.headings.firstIndex(where: { h in
 440                h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) }
 441            }) {
 442                expansion = headlineBody(heading, model: model, text: text)
 443            } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) {
 444                expansion = try expand(named)
 445            } else {
 446                var parts: [String] = []
 447                var separators: [String] = []
 448                for other in model.srcBlocks where !inCommentedHeading(other) {
 449                    let p = try Params(block: other, model: model, text: text)
 450                    guard p.single[":noweb-ref"] == id else { continue }
 451                    parts.append(try expand(other))
 452                    separators.append(p.single[":noweb-sep"] ?? "\n")
 453                }
 454                for (i, part) in parts.enumerated() {
 455                    if i > 0 { expansion += separators[i - 1] }
 456                    expansion += part
 457                }
 458            }
 459            out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion
 460        }
 461        return out + ns.substring(from: at)
 462    }
 463
 464    /// `org-babel-ref-headline-body`: the entry after its planning and drawers.
 465    static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String {
 466        let heading = model.headings[index]
 467        let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound)
 468        buffer.endOfMetaData()
 469        let start = buffer.point
 470        let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length
 471        return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : ""
 472    }
 473
 474    /// `org-babel--normalize-body`: without the final newline, and without the indentation
 475    /// common to its lines unless `-i` keeps it.
 476    static func normalizedBody(_ block: SrcBlockInfo) -> String {
 477        var lines = block.body.components(separatedBy: "\n")
 478        if lines.last == "" { lines.removeLast() }
 479        // Org escapes lines starting with `*` or `#+` inside blocks with a comma.
 480        lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
 481        if !block.switches.contains("-i") {
 482            let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
 483            let common = indents.min() ?? 0
 484            lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }
 485        }
 486        return lines.joined(separator: "\n")
 487    }
 488
 489    // MARK: - Header arguments
 490
 491    struct Params {
 492        var results: [String] = ["replace"]
 493        var single: [String: String] = [:]
 494        var vars: [(name: String, value: String)] = []
 495        var wrap: String?
 496
 497        static let resultGroups: [Set<String>] = [
 498            ["file", "list", "vector", "table", "scalar", "verbatim"],
 499            ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"],
 500            ["replace", "silent", "none", "discard", "append", "prepend"],
 501            ["output", "value"],
 502        ]
 503
 504        init(block: SrcBlockInfo, model: DocumentModel, text: NSString, extra: [[(String, String)]] = [], inline: Bool = false) throws {
 505            var layers: [[(String, String)]] = []
 506            let language = block.language ?? ""
 507            // `org-babel-params-from-properties`: the inherited `header-args`, then the inherited
 508            // `header-args:LANG`, each the nearest value with `+` additions after it.
 509            var levels = [model.fileProperties]
 510            if let heading = block.heading {
 511                levels += (model.ancestors(of: heading).reversed() + [heading]).map { model.headings[$0].properties }
 512            }
 513            for key in ["header-args", "header-args:\(language)"] {
 514                var value: String?
 515                for entries in levels {
 516                    for entry in entries where entry.key.lowercased() == key {
 517                        value = entry.additive ? [value, entry.value].compactMap { $0 }.joined(separator: " ") : entry.value
 518                    }
 519                }
 520                if let value { layers.append(Params.parse(value)) }
 521            }
 522            let firstLine = inline ? "" : text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0)))
 523            if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) {
 524                var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
 525                while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") {
 526                    rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces)
 527                }
 528                layers.append(Params.parse(rest))
 529            }
 530            // `#+HEADER:` lines above the block.
 531            var headers: [String] = []
 532            var location = block.range.lowerBound
 533            while !inline, location > 0 {
 534                let previous = text.lineRange(for: NSRange(location: location - 1, length: 0))
 535                let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines)
 536                guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break }
 537                if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) }
 538                location = previous.location
 539            }
 540            for header in headers { layers.append(Params.parse(header)) }
 541            layers += extra
 542
 543            for layer in layers {
 544                for (key, value) in layer {
 545                    switch key {
 546                    case ":results":
 547                        for word in value.split(whereSeparator: \.isWhitespace).map(String.init) {
 548                            if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } }
 549                            results.removeAll { $0 == word }
 550                            results.insert(word, at: 0)
 551                        }
 552                    case ":var":
 553                        for value in Params.splitVars(value) {
 554                            guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") }
 555                            let name = value[..<eq].trimmingCharacters(in: .whitespaces)
 556                            let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces)
 557                            vars.removeAll { $0.name == name }
 558                            vars.append((name, assigned))
 559                        }
 560                    case ":wrap":
 561                        wrap = value
 562                    default:
 563                        single[key] = value
 564                    }
 565                }
 566            }
 567        }
 568
 569        /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and
 570        /// parentheses.
 571        /// A Lisp string's contents as `read` gives them.
 572        static func unescape(_ s: String) -> String {
 573            var out = ""
 574            var escaped = false
 575            for c in s {
 576                if escaped {
 577                    switch c {
 578                    case "n": out.append("\n")
 579                    case "t": out.append("\t")
 580                    default: out.append(c)
 581                    }
 582                    escaped = false
 583                } else if c == "\\" {
 584                    escaped = true
 585                } else {
 586                    out.append(c)
 587                }
 588            }
 589            return out
 590        }
 591
 592        /// `org-babel-parse-multiple-vars`: one `:var` value holding several assignments split
 593        /// on spaces outside quotes and brackets, pieces split beside `=` joined again.
 594        static func splitVars(_ value: String) -> [String] {
 595            var pieces: [String] = []
 596            var current = ""
 597            var depth = 0
 598            var quoted = false
 599            var previous: Character = " "
 600            for c in value {
 601                if c == "\"", previous != "\\" { quoted.toggle() }
 602                previous = c
 603                if !quoted, "([{".contains(c) { depth += 1 }
 604                if !quoted, ")]}".contains(c) { depth = max(0, depth - 1) }
 605                if c == " ", !quoted, depth == 0 {
 606                    if !current.isEmpty { pieces.append(current) }
 607                    current = ""
 608                } else {
 609                    current.append(c)
 610                }
 611            }
 612            if !current.isEmpty { pieces.append(current) }
 613            var joined: [String] = []
 614            for piece in pieces {
 615                if let last = joined.last, last.hasSuffix("=") || piece.hasPrefix("=") {
 616                    joined[joined.count - 1] = last + piece
 617                } else {
 618                    joined.append(piece)
 619                }
 620            }
 621            return joined.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
 622        }
 623
 624        static func parse(_ text: String) -> [(String, String)] {
 625            var parts: [String] = []
 626            var current = ""
 627            var depth = 0
 628            var quoted = false
 629            var previous: Character = " "
 630            for c in text {
 631                if c == "\"", previous != "\\" { quoted.toggle() }
 632                if !quoted {
 633                    if c == "(" { depth += 1 }
 634                    if c == ")" { depth = max(0, depth - 1) }
 635                }
 636                if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" {
 637                    parts.append(current)
 638                    current = ""
 639                }
 640                current.append(c)
 641                previous = c
 642            }
 643            parts.append(current)
 644            var pairs: [(String, String)] = []
 645            for part in parts {
 646                let trimmed = part.trimmingCharacters(in: .whitespaces)
 647                guard trimmed.hasPrefix(":") else { continue }
 648                let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased()
 649                var value = trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces)
 650                if key != ":var", value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") {
 651                    value = Params.unescape(String(value.dropFirst().dropLast()))
 652                }
 653                pairs.append((key, value))
 654            }
 655            return pairs
 656        }
 657    }
 658
 659    // MARK: - Variables
 660
 661    /// A referenced block's result as a `:var` value.
 662    static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue {
 663        switch value(finish, output) {
 664        case .none: return .scalar("")
 665        case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s)
 666        case .table(let rows): return .table(rows.compactMap { $0?.map(cell) })
 667        }
 668    }
 669
 670    enum VarValue: Equatable, Sendable {
 671        case scalar(String)
 672        case number(String)
 673        case table([[Cell]])
 674        case list([Cell])
 675    }
 676
 677    enum Cell: Equatable, Sendable {
 678        case text(String)
 679        case number(String)
 680    }
 681
 682    /// `org-babel--string-to-number`, keeping Emacs's printed form.
 683    static func number(_ s: String) -> String? {
 684        let t = s.trimmingCharacters(in: .whitespaces)
 685        guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil }
 686        if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil {
 687            var digits = t.hasSuffix(".") ? String(t.dropLast()) : t
 688            let negative = digits.hasPrefix("-")
 689            if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() }
 690            digits = String(digits.drop { $0 == "0" })
 691            if digits.isEmpty { return "0" }
 692            return (negative ? "-" : "") + digits
 693        }
 694        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,
 695              let d = Double(t) else { return nil }
 696        return emacsFloat(d)
 697    }
 698
 699    /// How Emacs prints a float.
 700    static func emacsFloat(_ d: Double) -> String {
 701        if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) }
 702        return "\(d)"
 703    }
 704
 705    static func cell(_ s: String) -> Cell {
 706        var t = s
 707        if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) }
 708        return number(t).map(Cell.number) ?? .text(t)
 709    }
 710
 711    /// `name` or `name(args)` naming a src block in the file: the block and its call arguments.
 712    static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? {
 713        guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/),
 714              let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil }
 715        return (block, m.2.map(String.init))
 716    }
 717
 718    /// The blocks `params`' references run, directly or through theirs.
 719    static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] {
 720        var found: [SrcBlockInfo] = []
 721        var seen = seen
 722        for variable in params.vars {
 723            guard let (block, arguments) = referencedBlock(variable.value, model: model), let name = block.name, seen.insert(name).inserted else { continue }
 724            found.append(block)
 725            let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
 726            if let inner = try? Params(block: block, model: model, text: text, extra: extra) {
 727                found += referencedBlocks(inner, model: model, text: text, seen: seen)
 728            }
 729        }
 730        return found
 731    }
 732
 733    /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src
 734    /// blocks, which run first (`Needed`) and give their result.
 735    static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue {
 736        if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) }
 737        if let n = number(value) { return .number(n) }
 738        if let known = refs.resolved[value] { return known }
 739        if let (block, arguments) = referencedBlock(value, model: model), let name = block.name {
 740            guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") }
 741            let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
 742            var inner = refs
 743            inner.visiting.insert(name)
 744            switch plan(block, params: try Params(block: block, model: model, text: text, extra: extra), model: model, text: text,
 745                        options: refs.options, location: block.range, name: name, refs: inner) {
 746            case .failure(let failure): throw failure
 747            case .success(let job):
 748                throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job))
 749            }
 750        }
 751        if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
 752        // A named element: `#+NAME: value` above a table or list.
 753        let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
 754        guard let r = (text as String).range(of: pattern, options: .regularExpression) else {
 755            throw Failure.message("Can't find \(value) for :var.")
 756        }
 757        let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String)))
 758        var location = start
 759        var rows: [[Cell]] = []
 760        var items: [Cell] = []
 761        while location < text.length {
 762            let lineRange = text.lineRange(for: NSRange(location: location, length: 0))
 763            let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines)
 764            let trimmed = line.trimmingCharacters(in: .whitespaces)
 765            if trimmed.hasPrefix("|") {
 766                if trimmed.hasPrefix("|-") { throw Failure.message("Tables with rules in :var aren't supported yet.") }
 767                let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
 768                rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
 769            } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty {
 770                items.append(cell(String(m.1)))
 771            } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) {
 772                if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") {
 773                    throw Failure.message("Using a src block's result in :var isn't supported yet.")
 774                }
 775                break
 776            } else {
 777                break
 778            }
 779            location = NSMaxRange(lineRange)
 780        }
 781        if !rows.isEmpty { return .table(rows) }
 782        if !items.isEmpty { return .list(items) }
 783        throw Failure.message("\(value) isn't a table or list.")
 784    }
 785
 786    /// `org-babel-python-var-to-python`.
 787    static func pythonLiteral(_ value: VarValue) -> String {
 788        func cell(_ c: Cell) -> String {
 789            switch c {
 790            case .number(let n): return n
 791            case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
 792            }
 793        }
 794        switch value {
 795        case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
 796        case .number(let n): return n
 797        case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
 798        case .table(let rows): return "[" + rows.map { "[" + $0.map(cell).joined(separator: ", ") + "]" }.joined(separator: ", ") + "]"
 799        }
 800    }
 801
 802    /// `prin1` of a string.
 803    static func lispString(_ s: String, triple: Bool = false) -> String {
 804        let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
 805        return triple ? "\"\"" + quoted + "\"\"" : quoted
 806    }
 807
 808    static func lispLiteral(_ value: VarValue) -> String {
 809        func cell(_ c: Cell) -> String {
 810            switch c {
 811            case .number(let n): return n
 812            case .text(let s): return lispString(s)
 813            }
 814        }
 815        switch value {
 816        case .scalar(let s): return lispString(s)
 817        case .number(let n): return n
 818        case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")"
 819        case .table(let rows): return "(" + rows.map { "(" + $0.map(cell).joined(separator: " ") + ")" }.joined(separator: " ") + ")"
 820        }
 821    }
 822
 823    // MARK: - Python
 824
 825    /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint`
 826    /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables,
 827    /// otherwise `str`.
 828    static let pythonFormatter = """
 829    def __orgstar_format(value, path, params):
 830        def rows(v):
 831            if isinstance(v, dict):
 832                return [(k, rows(x)) for k, x in v.items()]
 833            if isinstance(v, (list, tuple)):
 834                return [rows(x) for x in v]
 835            return v
 836        with open(path, 'w') as out:
 837            if 'pp' in params:
 838                import pprint
 839                out.write(pprint.pformat(value))
 840            elif 'list' in params and isinstance(value, dict):
 841                out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()]))
 842            else:
 843                if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params:
 844                    value = rows(value)
 845                out.write(str(value))
 846
 847    """
 848
 849    /// `org-babel-python--shift-right`: four spaces more on every line outside strings.
 850    static func shiftRight(_ body: String) -> String {
 851        var inString: String?
 852        var lines: [String] = []
 853        for line in body.components(separatedBy: "\n") {
 854            lines.append(inString == nil ? "    " + line : line)
 855            var i = line.startIndex
 856            while i < line.endIndex {
 857                if let delimiter = inString {
 858                    if line[i...].hasPrefix(delimiter) {
 859                        inString = nil
 860                        i = line.index(i, offsetBy: 3)
 861                        continue
 862                    }
 863                } else if line[i] == "#" {
 864                    break
 865                } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") {
 866                    inString = String(line[i...].prefix(3))
 867                    i = line.index(i, offsetBy: 3)
 868                    continue
 869                } else if line[i] == "\"" || line[i] == "'" {
 870                    let quote = line[i]
 871                    i = line.index(after: i)
 872                    while i < line.endIndex, line[i] != quote {
 873                        if line[i] == "\\" { i = line.index(after: i) }
 874                        if i < line.endIndex { i = line.index(after: i) }
 875                    }
 876                }
 877                if i < line.endIndex { i = line.index(after: i) }
 878            }
 879        }
 880        return lines.joined(separator: "\n")
 881    }
 882
 883    // MARK: - Emacs Lisp
 884
 885    /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows
 886    /// when it is a table.
 887    static func emacsScript(form: String, params: [String]) -> String {
 888        """
 889        ;;; -*- lexical-binding: t -*-
 890        (require 'cl-lib)
 891        (require 'json)
 892        (let* ((result \(form))
 893               (print-level nil)
 894               (print-length nil)
 895               (cell (lambda (c) (if (stringp c) c (format "%s" c))))
 896               (tabulable (and (proper-list-p result)
 897                               (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result)))
 898               (rows (and tabulable result
 899                          (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result)
 900                              (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result)
 901                            (list (vconcat (mapcar cell result)))))))
 902          (princ (json-encode `((s . ,(format "%s" result))
 903                                (S . ,(format "%S" result))
 904                                (string . ,(if (stringp result) t :json-false))
 905                                (rows . ,(if rows (vconcat rows) :json-null))))))
 906        """
 907    }
 908
 909    // MARK: - Finishing
 910
 911    /// What the run produced, as Babel holds it before inserting.
 912    enum Value: Equatable {
 913        case none
 914        case string(String)
 915        /// Rows of cells; nil rows are rules.
 916        case table([[String]?])
 917    }
 918
 919    /// The edit that writes the run's result under the block, or why it can't.
 920    public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> {
 921        let ns = text as NSString
 922        var blockRange = job.block
 923        if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText {
 924            let found = ns.range(of: job.blockText)
 925            guard found.location != NSNotFound,
 926                  ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else {
 927                return .failure(.message("The block changed while it ran; the result wasn't written."))
 928            }
 929            blockRange = found.location..<NSMaxRange(found)
 930        }
 931        let value = Self.value(job.finish, output)
 932        if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
 933        let buffer = EmacsBuffer(text, point: 0, settings: settings)
 934        if job.finish.inline {
 935            do {
 936                try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer)
 937            } catch let error as Failure {
 938                return .failure(error)
 939            } catch {
 940                return .failure(.message("\(error)"))
 941            }
 942            return .success(TextEdit.between(text, buffer.text as String))
 943        }
 944        insertResult(value, job.finish, block: blockRange, buffer: buffer)
 945        return .success(TextEdit.between(text, buffer.text as String))
 946    }
 947
 948    /// The language's result handling: `org-babel-result-cond` and the table import.
 949    static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
 950        let params = finish.params
 951        if params.contains("file") {
 952            // `org-babel-result-to-file`: a link to `:file`, or to the result as a path.
 953            let path = finish.file ?? rawResult(finish, output)
 954            var link = "[[file:" + path + "]"
 955            if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
 956            return .string(link + "]")
 957        }
 958        let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
 959            || params.contains("pp") || params.contains("file")
 960            || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
 961        switch finish.kind {
 962        case .shell(let valueIsExitStatus):
 963            var results = output.stdout
 964            if valueIsExitStatus {
 965                results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? ""
 966            }
 967            if scalar { return .string(results) }
 968            return importTable(results)
 969        case .generic:
 970            return .string(output.stdout)
 971        case .python:
 972            let raw = finish.output ? output.stdout : (output.resultFile ?? "")
 973            if scalar { return .string(raw) }
 974            return pythonValue(raw)
 975        case .emacsLisp:
 976            guard let data = output.stdout.data(using: .utf8),
 977                  let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) }
 978            if scalar {
 979                return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "")
 980            }
 981            if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") }
 982            if let rows = object["rows"] as? [Any] {
 983                return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) })
 984            }
 985            let printed = object["S"] as? String ?? ""
 986            return printed == "nil" ? .none : .string(printed)
 987        }
 988    }
 989
 990    /// The result as the program left it, before tables are read.
 991    static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String {
 992        switch finish.kind {
 993        case .python: return finish.output ? output.stdout : (output.resultFile ?? "")
 994        case .emacsLisp:
 995            guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
 996            return object["s"] as? String ?? ""
 997        case .shell(let valueIsExitStatus):
 998            return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
 999        case .generic: return output.stdout
1000        }
1001    }
1002
1003    /// With `:results file` and `:file`, what to write there, relative to the run's folder;
1004    /// nil when there's nothing to write or the program wrote it.
1005    public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? {
1006        guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil }
1007        return (file, rawResult(job.finish, output))
1008    }
1009
1010    /// `org-babel-import-elisp-from-file`.
1011    static func importTable(_ results: String) -> Value {
1012        guard !results.isEmpty else { return .none }
1013        var lines = results.components(separatedBy: "\n")
1014        if lines.last == "" { lines.removeLast() }
1015        let nonEmpty = lines.filter { !$0.isEmpty }
1016        let rows: [[String]]
1017        if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) {
1018            rows = lines.map { $0.components(separatedBy: "\t") }
1019        } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) {
1020            rows = lines.map(csvFields)
1021        } else if lines.count == 1 {
1022            rows = [[lines[0]]]
1023        } else {
1024            rows = lines.map { line in
1025                let trimmed = line.drop { $0 == " " }
1026                return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty
1027                    ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
1028            }
1029        }
1030        let cells = rows.map { row in row.map { field -> String in
1031            let trimmed = field.trimmingCharacters(in: .whitespaces)
1032            switch cell(trimmed) {
1033            case .number(let n): return n
1034            case .text(let t): return t
1035            }
1036        } }
1037        if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) }
1038        return .table(cells)
1039    }
1040
1041    static func csvFields(_ line: String) -> [String] {
1042        var fields: [String] = []
1043        var current = ""
1044        var quoted = false
1045        for c in line {
1046            if c == "\"" {
1047                quoted.toggle()
1048            } else if c == ",", !quoted {
1049                fields.append(current.trimmingCharacters(in: .whitespaces))
1050                current = ""
1051            } else {
1052                current.append(c)
1053            }
1054        }
1055        fields.append(current.trimmingCharacters(in: .whitespaces))
1056        return fields
1057    }
1058
1059    /// `org-babel-python-table-or-string`.
1060    static func pythonValue(_ raw: String) -> Value {
1061        guard let first = raw.first, let last = raw.last, raw.count >= 2,
1062              (first == "[" && last == "]") || (first == "(" && last == ")") else {
1063            if raw.isEmpty { return .string("") }
1064            if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) {
1065                return .string(String(raw.dropFirst().dropLast()))
1066            }
1067            if let n = number(raw) { return .string(n) }
1068            return .string(raw)
1069        }
1070        var parser = PythonLiteral(Array(raw))
1071        guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) }
1072        func text(_ v: PythonLiteral.Node) -> String {
1073            switch v {
1074            case .atom(let s): return s
1075            case .string(let s): return s
1076            case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")"
1077            }
1078        }
1079        if items.allSatisfy({ if case .list = $0 { return true }; if case .atom("None") = $0 { return true }; return false }) {
1080            return .table(items.map { item -> [String]? in
1081                if case .list(let cells) = item { return cells.map(text) }
1082                return nil
1083            })
1084        }
1085        return .table([items.map { if case .atom("None") = $0 { return "hline" }; return text($0) }])
1086    }
1087
1088    struct PythonLiteral {
1089        indirect enum Node: Equatable {
1090            case atom(String)
1091            case string(String)
1092            case list([Node])
1093        }
1094
1095        let chars: [Character]
1096        var i = 0
1097        init(_ chars: [Character]) { self.chars = chars }
1098        var atEnd: Bool { mutating get { skip(); return i == chars.count } }
1099
1100        mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } }
1101
1102        mutating func parse() -> Node? {
1103            skip()
1104            guard i < chars.count else { return nil }
1105            let c = chars[i]
1106            if c == "[" || c == "(" {
1107                let close: Character = c == "[" ? "]" : ")"
1108                i += 1
1109                var items: [Node] = []
1110                skip()
1111                if i < chars.count, chars[i] == close {
1112                    i += 1
1113                    return .list(items)
1114                }
1115                while true {
1116                    guard let item = parse() else { return nil }
1117                    items.append(item)
1118                    skip()
1119                    guard i < chars.count else { return nil }
1120                    if chars[i] == "," {
1121                        i += 1
1122                        skip()
1123                        if i < chars.count, chars[i] == close {
1124                            i += 1
1125                            return .list(items)
1126                        }
1127                        continue
1128                    }
1129                    if chars[i] == close {
1130                        i += 1
1131                        return .list(items)
1132                    }
1133                    return nil
1134                }
1135            }
1136            if c == "'" || c == "\"" {
1137                i += 1
1138                var s = ""
1139                while i < chars.count, chars[i] != c {
1140                    if chars[i] == "\\", i + 1 < chars.count {
1141                        i += 1
1142                        switch chars[i] {
1143                        case "n": s.append("\n")
1144                        case "t": s.append("\t")
1145                        default: s.append(chars[i])
1146                        }
1147                    } else {
1148                        s.append(chars[i])
1149                    }
1150                    i += 1
1151                }
1152                guard i < chars.count else { return nil }
1153                i += 1
1154                return .string(s)
1155            }
1156            var s = ""
1157            while i < chars.count, !",)] \n".contains(chars[i]) {
1158                s.append(chars[i])
1159                i += 1
1160            }
1161            guard !s.isEmpty else { return nil }
1162            return .atom(number(s) ?? s)
1163        }
1164    }
1165
1166    // MARK: - Inserting
1167
1168    static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:"
1169
1170    /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results
1171    /// keyword, added when there is none.
1172    static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int {
1173        let ns = buffer.text
1174        if let name = finish.name {
1175            let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
1176            let regex = try! NSRegularExpression(pattern: pattern)
1177            for m in regex.matches(in: ns as String, range: NSRange(location: 0, length: ns.length)) {
1178                // Not the name of another block.
1179                return m.range.location
1180            }
1181        } else {
1182            // The element after the block, past blank lines.
1183            var location = block.upperBound
1184            while location < ns.length {
1185                let line = ns.lineRange(for: NSRange(location: location, length: 0))
1186                let content = ns.substring(with: line)
1187                if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1188                    location = NSMaxRange(line)
1189                    continue
1190                }
1191                if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil {
1192                    return line.location
1193                }
1194                break
1195            }
1196        }
1197        // A new keyword after the block.
1198        buffer.point = min(block.upperBound, buffer.length)
1199        buffer.skipBackward([32, 9, 10, 13])
1200        buffer.forwardLine(1)
1201        if !buffer.bolp { buffer.insert("\n") }
1202        let indent = buffer.saveExcursion { () -> String in
1203            buffer.point = block.lowerBound
1204            let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
1205            return String(line.prefix { $0 == " " || $0 == "\t" })
1206        }
1207        buffer.insert("\n")
1208        let keywordLine = buffer.point
1209        buffer.insert(indent + "#+RESULTS:" + (finish.name.map { " " + $0 } ?? "") + "\n")
1210        if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
1211            buffer.saveExcursion { buffer.insert("\n") }
1212        }
1213        return keywordLine
1214    }
1215
1216    /// `org-babel-result-end` with point at the start of the result.
1217    static func resultEnd(_ buffer: EmacsBuffer) -> Int {
1218        let start = buffer.point
1219        let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start))
1220        if line.trimmingCharacters(in: .whitespaces).isEmpty { return start }
1221        if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil {
1222            return min(buffer.length, buffer.lineEnd(start) + 1)
1223        }
1224        let tree = OrgParser.parse(buffer.text as String)
1225        var node = tree.root
1226        var found: SyntaxNode?
1227        while let child = node.child(containing: start) {
1228            if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) {
1229                if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) {
1230                    found = child
1231                    break
1232                }
1233            }
1234            node = child
1235        }
1236        guard let element = found else { return start }
1237        var end = element.range.upperBound
1238        while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 }
1239        return min(buffer.length, buffer.lineEnd(end) + 1)
1240    }
1241
1242    /// `org-babel-insert-result` for a src block.
1243    /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already
1244    /// there; raw results go in as they are.
1245    static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws {
1246        var string: String
1247        switch value {
1248        case .none: string = ""
1249        case .string(let s): string = s
1250        case .table(let rows):
1251            let cells = rows.compactMap { $0 }
1252            guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") }
1253            string = cells[0][0]
1254        }
1255        buffer.point = object.upperBound
1256        if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") {
1257            buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound)
1258        }
1259        if finish.params.contains("raw") {
1260            buffer.insert(" " + string)
1261            return
1262        }
1263        if string.hasSuffix("\n") { string.removeLast() }
1264        guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") }
1265        buffer.insert(" {{{results(=" + string + "=)}}}")
1266    }
1267
1268    static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) {
1269        let params = finish.params
1270        let keyword = resultsLine(finish, block: block, buffer: buffer)
1271        buffer.point = keyword
1272        let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count
1273        buffer.forwardLine(1)
1274        if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") }
1275        var beg = buffer.point
1276        if params.contains("replace") {
1277            buffer.deleteRegion(beg, resultEnd(buffer))
1278            buffer.point = beg
1279        } else if params.contains("append") {
1280            buffer.point = resultEnd(buffer)
1281            beg = buffer.point
1282        }
1283        var tabulated = false
1284        switch value {
1285        case .none:
1286            break
1287        case .string(var s) where params.contains("list"):
1288            if s.last != "\n" { s += "\n" }
1289            let items = s.split(separator: "\n", omittingEmptySubsequences: true)
1290            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1291        case .table(let rows) where params.contains("list"):
1292            let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
1293            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1294        case .table(let rows):
1295            tabulated = true
1296            let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" }
1297            let start = buffer.point
1298            buffer.insert(lines.joined(separator: "\n") + "\n")
1299            buffer.point = start
1300            buffer.tableAlign()
1301            buffer.point = buffer.tableEnd()
1302        case .string(var s):
1303            if !s.isEmpty, s.last != "\n" { s += "\n" }
1304            buffer.insert(s)
1305        }
1306        let end = buffer.marker(buffer.point, advances: true)
1307        defer { buffer.release(end) }
1308        func wrap(_ open: String, _ close: String, escape: Bool) {
1309            buffer.point = end.position
1310            buffer.insert(close + "\n")
1311            buffer.point = beg
1312            buffer.insert(open + "\n")
1313            if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) }
1314        }
1315        if let wrapValue = finish.wrap {
1316            let full = wrapValue.isEmpty ? "results" : wrapValue
1317            let type = String(full.split(separator: " ").first ?? "results")
1318            if type.lowercased() != "nil", type.lowercased() != "no" {
1319                wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true)
1320            }
1321        } else if params.contains("html") {
1322            wrap("#+begin_export html", "#+end_export", escape: true)
1323        } else if params.contains("latex") {
1324            wrap("#+begin_export latex", "#+end_export", escape: true)
1325        } else if params.contains("org") {
1326            wrap("#+begin_src org", "#+end_src", escape: true)
1327        } else if params.contains("code") {
1328            wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true)
1329        } else if params.contains("raw") || params.contains("file") {
1330            // As inserted.
1331        } else if params.contains("drawer") {
1332            wrap(":results:", ":end:", escape: false)
1333        } else if !tabulated, !params.contains("list") {
1334            examplify(buffer, beg, end.position)
1335        }
1336        if indent > 0, !(tabulated && params.contains("append")) {
1337            buffer.point = beg
1338            while buffer.point < end.position {
1339                if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) }
1340                if buffer.forwardLine(1) != 0 { break }
1341            }
1342        }
1343    }
1344
1345    /// `org-escape-code-in-region`.
1346    static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) {
1347        buffer.point = start
1348        let stop = buffer.marker(end)
1349        defer { buffer.release(stop) }
1350        while buffer.point < stop.position {
1351            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
1352            if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) {
1353                buffer.point += line[..<m.1.startIndex].utf16.count
1354                buffer.insert(",")
1355            }
1356            if buffer.forwardLine(1) != 0 { break }
1357        }
1358    }
1359
1360    /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
1361    static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
1362        let text = buffer.substring(beg, end)
1363        var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0)
1364        if text.isEmpty { size = 0 }
1365        guard size > 0 else { return }
1366        if size < 10 {
1367            buffer.point = beg
1368            for _ in 0..<size {
1369                buffer.point = buffer.lineStart(buffer.point)
1370                buffer.insert(": ")
1371                buffer.forwardLine(1)
1372            }
1373            return
1374        }
1375        let endMarker = buffer.marker(end)
1376        defer { buffer.release(endMarker) }
1377        buffer.point = beg
1378        buffer.insert("#+begin_example\n")
1379        escapeCode(buffer, from: buffer.point, to: endMarker.position)
1380        buffer.point = endMarker.position
1381        if !buffer.bolp { buffer.insert("\n") }
1382        buffer.insert("#+end_example")
1383        if !buffer.eolp { buffer.insert("\n") }
1384    }
1385}
1386
1387/// C-c C-c in a src block: `org-babel-execute-src-block`.
1388public struct ExecuteSrcBlock: OrgCommand {
1389    public init() {}
1390    public var id: String { "org.babel.execute" }
1391    public var title: String { "Run Source Block" }
1392    public func applies(in context: EditContext) -> Bool { KeyContext.holds("src", in: context) || Self.atCallOrInline(context) }
1393
1394    /// On a `#+CALL:` line or an inline `src_` block.
1395    static func atCallOrInline(_ context: EditContext) -> Bool {
1396        let ns = context.text as NSString
1397        let line = ns.substring(with: ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0)))
1398        if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil { return true }
1399        var node = context.tree.root
1400        while let child = node.child(containing: context.caret) {
1401            if child.kind == .inlineSourceBlock { return true }
1402            node = child
1403        }
1404        return false
1405    }
1406
1407    public func run(in context: EditContext) -> CommandStep {
1408        switch Babel.plan(context) {
1409        case .success(let job): return .external(.babel(job))
1410        case .failure(.message(let message)): return .failed(message)
1411        }
1412    }
1413}
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