Sources/OrgCore/Compute/Babel.swift

5bb13b85656f8b0461eb4d7208602b9838ef3eb3
orgstar/Sources/OrgCore/Compute/Babel.swift

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