Sources/OrgCore/Compute/Babel.swift

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

1435 lines · 72616 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    static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0) throws -> String {
 435        guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") }
 436        let body = normalizedBody(block)
 437        let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true
 438        func expand(_ other: SrcBlockInfo) throws -> String {
 439            let otherParams = try Params(block: other, model: model, text: text)
 440            let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"])
 441            return expands
 442                ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1)
 443                : normalizedBody(other)
 444        }
 445        func inCommentedHeading(_ b: SrcBlockInfo) -> Bool {
 446            guard let h = b.heading else { return false }
 447            return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
 448        }
 449        let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
 450        let ns = body as NSString
 451        var out = ""
 452        var at = 0
 453        for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
 454            let prefix = ns.substring(with: m.range(at: 1))
 455            let id = ns.substring(with: m.range(at: 3))
 456            out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at))
 457            at = NSMaxRange(m.range)
 458            var expansion = ""
 459            if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
 460                throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.")
 461            } else if let heading = model.headings.firstIndex(where: { h in
 462                h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) }
 463            }) {
 464                expansion = headlineBody(heading, model: model, text: text)
 465            } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) {
 466                expansion = try expand(named)
 467            } else {
 468                var parts: [String] = []
 469                var separators: [String] = []
 470                for other in model.srcBlocks where !inCommentedHeading(other) {
 471                    let p = try Params(block: other, model: model, text: text)
 472                    guard p.single[":noweb-ref"] == id else { continue }
 473                    parts.append(try expand(other))
 474                    separators.append(p.single[":noweb-sep"] ?? "\n")
 475                }
 476                for (i, part) in parts.enumerated() {
 477                    if i > 0 { expansion += separators[i - 1] }
 478                    expansion += part
 479                }
 480            }
 481            out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion
 482        }
 483        return out + ns.substring(from: at)
 484    }
 485
 486    /// `org-babel-ref-headline-body`: the entry after its planning and drawers.
 487    static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String {
 488        let heading = model.headings[index]
 489        let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound)
 490        buffer.endOfMetaData()
 491        let start = buffer.point
 492        let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length
 493        return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : ""
 494    }
 495
 496    /// `org-babel--normalize-body`: without the final newline, and without the indentation
 497    /// common to its lines unless `-i` keeps it.
 498    static func normalizedBody(_ block: SrcBlockInfo) -> String {
 499        var lines = block.body.components(separatedBy: "\n")
 500        if lines.last == "" { lines.removeLast() }
 501        // Org escapes lines starting with `*` or `#+` inside blocks with a comma.
 502        lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
 503        if !block.switches.contains("-i") {
 504            let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
 505            let common = indents.min() ?? 0
 506            lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }
 507        }
 508        return lines.joined(separator: "\n")
 509    }
 510
 511    // MARK: - Header arguments
 512
 513    struct Params {
 514        var results: [String] = ["replace"]
 515        var single: [String: String] = [:]
 516        var vars: [(name: String, value: String)] = []
 517        var wrap: String?
 518
 519        static let resultGroups: [Set<String>] = [
 520            ["file", "list", "vector", "table", "scalar", "verbatim"],
 521            ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"],
 522            ["replace", "silent", "none", "discard", "append", "prepend"],
 523            ["output", "value"],
 524        ]
 525
 526        init(block: SrcBlockInfo, model: DocumentModel, text: NSString, extra: [[(String, String)]] = [], inline: Bool = false) throws {
 527            var layers: [[(String, String)]] = []
 528            let language = block.language ?? ""
 529            // `org-babel-params-from-properties`: the inherited `header-args`, then the inherited
 530            // `header-args:LANG`, each the nearest value with `+` additions after it.
 531            var levels = [model.fileProperties]
 532            if let heading = block.heading {
 533                levels += (model.ancestors(of: heading).reversed() + [heading]).map { model.headings[$0].properties }
 534            }
 535            for key in ["header-args", "header-args:\(language)"] {
 536                var value: String?
 537                for entries in levels {
 538                    for entry in entries where entry.key.lowercased() == key {
 539                        value = entry.additive ? [value, entry.value].compactMap { $0 }.joined(separator: " ") : entry.value
 540                    }
 541                }
 542                if let value { layers.append(Params.parse(value)) }
 543            }
 544            let firstLine = inline ? "" : text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0)))
 545            if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) {
 546                var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
 547                while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") {
 548                    rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces)
 549                }
 550                layers.append(Params.parse(rest))
 551            }
 552            // `#+HEADER:` lines above the block.
 553            var headers: [String] = []
 554            var location = block.range.lowerBound
 555            while !inline, location > 0 {
 556                let previous = text.lineRange(for: NSRange(location: location - 1, length: 0))
 557                let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines)
 558                guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break }
 559                if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) }
 560                location = previous.location
 561            }
 562            for header in headers { layers.append(Params.parse(header)) }
 563            layers += extra
 564
 565            for layer in layers {
 566                for (key, value) in layer {
 567                    switch key {
 568                    case ":results":
 569                        for word in value.split(whereSeparator: \.isWhitespace).map(String.init) {
 570                            if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } }
 571                            results.removeAll { $0 == word }
 572                            results.insert(word, at: 0)
 573                        }
 574                    case ":var":
 575                        for value in Params.splitVars(value) {
 576                            guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") }
 577                            let name = value[..<eq].trimmingCharacters(in: .whitespaces)
 578                            let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces)
 579                            vars.removeAll { $0.name == name }
 580                            vars.append((name, assigned))
 581                        }
 582                    case ":wrap":
 583                        wrap = value
 584                    default:
 585                        single[key] = value
 586                    }
 587                }
 588            }
 589        }
 590
 591        /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and
 592        /// parentheses.
 593        /// A Lisp string's contents as `read` gives them.
 594        static func unescape(_ s: String) -> String {
 595            var out = ""
 596            var escaped = false
 597            for c in s {
 598                if escaped {
 599                    switch c {
 600                    case "n": out.append("\n")
 601                    case "t": out.append("\t")
 602                    default: out.append(c)
 603                    }
 604                    escaped = false
 605                } else if c == "\\" {
 606                    escaped = true
 607                } else {
 608                    out.append(c)
 609                }
 610            }
 611            return out
 612        }
 613
 614        /// `org-babel-parse-multiple-vars`: one `:var` value holding several assignments split
 615        /// on spaces outside quotes and brackets, pieces split beside `=` joined again.
 616        static func splitVars(_ value: String) -> [String] {
 617            var pieces: [String] = []
 618            var current = ""
 619            var depth = 0
 620            var quoted = false
 621            var previous: Character = " "
 622            for c in value {
 623                if c == "\"", previous != "\\" { quoted.toggle() }
 624                previous = c
 625                if !quoted, "([{".contains(c) { depth += 1 }
 626                if !quoted, ")]}".contains(c) { depth = max(0, depth - 1) }
 627                if c == " ", !quoted, depth == 0 {
 628                    if !current.isEmpty { pieces.append(current) }
 629                    current = ""
 630                } else {
 631                    current.append(c)
 632                }
 633            }
 634            if !current.isEmpty { pieces.append(current) }
 635            var joined: [String] = []
 636            for piece in pieces {
 637                if let last = joined.last, last.hasSuffix("=") || piece.hasPrefix("=") {
 638                    joined[joined.count - 1] = last + piece
 639                } else {
 640                    joined.append(piece)
 641                }
 642            }
 643            return joined.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
 644        }
 645
 646        static func parse(_ text: String) -> [(String, String)] {
 647            var parts: [String] = []
 648            var current = ""
 649            var depth = 0
 650            var quoted = false
 651            var previous: Character = " "
 652            for c in text {
 653                if c == "\"", previous != "\\" { quoted.toggle() }
 654                if !quoted {
 655                    if c == "(" { depth += 1 }
 656                    if c == ")" { depth = max(0, depth - 1) }
 657                }
 658                if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" {
 659                    parts.append(current)
 660                    current = ""
 661                }
 662                current.append(c)
 663                previous = c
 664            }
 665            parts.append(current)
 666            var pairs: [(String, String)] = []
 667            for part in parts {
 668                let trimmed = part.trimmingCharacters(in: .whitespaces)
 669                guard trimmed.hasPrefix(":") else { continue }
 670                let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased()
 671                var value = trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces)
 672                if key != ":var", value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") {
 673                    value = Params.unescape(String(value.dropFirst().dropLast()))
 674                }
 675                pairs.append((key, value))
 676            }
 677            return pairs
 678        }
 679    }
 680
 681    // MARK: - Variables
 682
 683    /// A referenced block's result as a `:var` value.
 684    static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue {
 685        switch value(finish, output) {
 686        case .none: return .scalar("")
 687        case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s)
 688        case .table(let rows): return .table(rows.compactMap { $0?.map(cell) })
 689        }
 690    }
 691
 692    enum VarValue: Equatable, Sendable {
 693        case scalar(String)
 694        case number(String)
 695        case table([[Cell]])
 696        case list([Cell])
 697    }
 698
 699    enum Cell: Equatable, Sendable {
 700        case text(String)
 701        case number(String)
 702    }
 703
 704    /// `org-babel--string-to-number`, keeping Emacs's printed form.
 705    static func number(_ s: String) -> String? {
 706        let t = s.trimmingCharacters(in: .whitespaces)
 707        guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil }
 708        if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil {
 709            var digits = t.hasSuffix(".") ? String(t.dropLast()) : t
 710            let negative = digits.hasPrefix("-")
 711            if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() }
 712            digits = String(digits.drop { $0 == "0" })
 713            if digits.isEmpty { return "0" }
 714            return (negative ? "-" : "") + digits
 715        }
 716        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,
 717              let d = Double(t) else { return nil }
 718        return emacsFloat(d)
 719    }
 720
 721    /// How Emacs prints a float.
 722    static func emacsFloat(_ d: Double) -> String {
 723        if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) }
 724        return "\(d)"
 725    }
 726
 727    static func cell(_ s: String) -> Cell {
 728        var t = s
 729        if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) }
 730        return number(t).map(Cell.number) ?? .text(t)
 731    }
 732
 733    /// `name` or `name(args)` naming a src block in the file: the block and its call arguments.
 734    static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? {
 735        guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/),
 736              let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil }
 737        return (block, m.2.map(String.init))
 738    }
 739
 740    /// The blocks `params`' references run, directly or through theirs.
 741    static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] {
 742        var found: [SrcBlockInfo] = []
 743        var seen = seen
 744        for variable in params.vars {
 745            guard let (block, arguments) = referencedBlock(variable.value, model: model), let name = block.name, seen.insert(name).inserted else { continue }
 746            found.append(block)
 747            let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
 748            if let inner = try? Params(block: block, model: model, text: text, extra: extra) {
 749                found += referencedBlocks(inner, model: model, text: text, seen: seen)
 750            }
 751        }
 752        return found
 753    }
 754
 755    /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src
 756    /// blocks, which run first (`Needed`) and give their result.
 757    static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue {
 758        if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) }
 759        if let n = number(value) { return .number(n) }
 760        if let known = refs.resolved[value] { return known }
 761        if let (block, arguments) = referencedBlock(value, model: model), let name = block.name {
 762            guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") }
 763            let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
 764            var inner = refs
 765            inner.visiting.insert(name)
 766            switch plan(block, params: try Params(block: block, model: model, text: text, extra: extra), model: model, text: text,
 767                        options: refs.options, location: block.range, name: name, refs: inner) {
 768            case .failure(let failure): throw failure
 769            case .success(let job):
 770                throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job))
 771            }
 772        }
 773        if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
 774        // A named element: `#+NAME: value` above a table or list.
 775        let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
 776        guard let r = (text as String).range(of: pattern, options: .regularExpression) else {
 777            throw Failure.message("Can't find \(value) for :var.")
 778        }
 779        let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String)))
 780        var location = start
 781        var rows: [[Cell]] = []
 782        var items: [Cell] = []
 783        while location < text.length {
 784            let lineRange = text.lineRange(for: NSRange(location: location, length: 0))
 785            let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines)
 786            let trimmed = line.trimmingCharacters(in: .whitespaces)
 787            if trimmed.hasPrefix("|") {
 788                if trimmed.hasPrefix("|-") { throw Failure.message("Tables with rules in :var aren't supported yet.") }
 789                let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
 790                rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
 791            } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty {
 792                items.append(cell(String(m.1)))
 793            } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) {
 794                if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") {
 795                    throw Failure.message("Using a src block's result in :var isn't supported yet.")
 796                }
 797                break
 798            } else {
 799                break
 800            }
 801            location = NSMaxRange(lineRange)
 802        }
 803        if !rows.isEmpty { return .table(rows) }
 804        if !items.isEmpty { return .list(items) }
 805        throw Failure.message("\(value) isn't a table or list.")
 806    }
 807
 808    /// `org-babel-python-var-to-python`.
 809    static func pythonLiteral(_ value: VarValue) -> String {
 810        func cell(_ c: Cell) -> String {
 811            switch c {
 812            case .number(let n): return n
 813            case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
 814            }
 815        }
 816        switch value {
 817        case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
 818        case .number(let n): return n
 819        case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
 820        case .table(let rows): return "[" + rows.map { "[" + $0.map(cell).joined(separator: ", ") + "]" }.joined(separator: ", ") + "]"
 821        }
 822    }
 823
 824    /// `prin1` of a string.
 825    static func lispString(_ s: String, triple: Bool = false) -> String {
 826        let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
 827        return triple ? "\"\"" + quoted + "\"\"" : quoted
 828    }
 829
 830    static func lispLiteral(_ value: VarValue) -> String {
 831        func cell(_ c: Cell) -> String {
 832            switch c {
 833            case .number(let n): return n
 834            case .text(let s): return lispString(s)
 835            }
 836        }
 837        switch value {
 838        case .scalar(let s): return lispString(s)
 839        case .number(let n): return n
 840        case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")"
 841        case .table(let rows): return "(" + rows.map { "(" + $0.map(cell).joined(separator: " ") + ")" }.joined(separator: " ") + ")"
 842        }
 843    }
 844
 845    // MARK: - Python
 846
 847    /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint`
 848    /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables,
 849    /// otherwise `str`.
 850    static let pythonFormatter = """
 851    def __orgstar_format(value, path, params):
 852        def rows(v):
 853            if isinstance(v, dict):
 854                return [(k, rows(x)) for k, x in v.items()]
 855            if isinstance(v, (list, tuple)):
 856                return [rows(x) for x in v]
 857            return v
 858        with open(path, 'w') as out:
 859            if 'pp' in params:
 860                import pprint
 861                out.write(pprint.pformat(value))
 862            elif 'list' in params and isinstance(value, dict):
 863                out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()]))
 864            else:
 865                if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params:
 866                    value = rows(value)
 867                out.write(str(value))
 868
 869    """
 870
 871    /// `org-babel-python--shift-right`: four spaces more on every line outside strings.
 872    static func shiftRight(_ body: String) -> String {
 873        var inString: String?
 874        var lines: [String] = []
 875        for line in body.components(separatedBy: "\n") {
 876            lines.append(inString == nil ? "    " + line : line)
 877            var i = line.startIndex
 878            while i < line.endIndex {
 879                if let delimiter = inString {
 880                    if line[i...].hasPrefix(delimiter) {
 881                        inString = nil
 882                        i = line.index(i, offsetBy: 3)
 883                        continue
 884                    }
 885                } else if line[i] == "#" {
 886                    break
 887                } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") {
 888                    inString = String(line[i...].prefix(3))
 889                    i = line.index(i, offsetBy: 3)
 890                    continue
 891                } else if line[i] == "\"" || line[i] == "'" {
 892                    let quote = line[i]
 893                    i = line.index(after: i)
 894                    while i < line.endIndex, line[i] != quote {
 895                        if line[i] == "\\" { i = line.index(after: i) }
 896                        if i < line.endIndex { i = line.index(after: i) }
 897                    }
 898                }
 899                if i < line.endIndex { i = line.index(after: i) }
 900            }
 901        }
 902        return lines.joined(separator: "\n")
 903    }
 904
 905    // MARK: - Emacs Lisp
 906
 907    /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows
 908    /// when it is a table.
 909    static func emacsScript(form: String, params: [String]) -> String {
 910        """
 911        ;;; -*- lexical-binding: t -*-
 912        (require 'cl-lib)
 913        (require 'json)
 914        (let* ((result \(form))
 915               (print-level nil)
 916               (print-length nil)
 917               (cell (lambda (c) (if (stringp c) c (format "%s" c))))
 918               (tabulable (and (proper-list-p result)
 919                               (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result)))
 920               (rows (and tabulable result
 921                          (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result)
 922                              (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result)
 923                            (list (vconcat (mapcar cell result)))))))
 924          (princ (json-encode `((s . ,(format "%s" result))
 925                                (S . ,(format "%S" result))
 926                                (string . ,(if (stringp result) t :json-false))
 927                                (rows . ,(if rows (vconcat rows) :json-null))))))
 928        """
 929    }
 930
 931    // MARK: - Finishing
 932
 933    /// What the run produced, as Babel holds it before inserting.
 934    enum Value: Equatable {
 935        case none
 936        case string(String)
 937        /// Rows of cells; nil rows are rules.
 938        case table([[String]?])
 939    }
 940
 941    /// The edit that writes the run's result under the block, or why it can't.
 942    public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> {
 943        let ns = text as NSString
 944        var blockRange = job.block
 945        if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText {
 946            let found = ns.range(of: job.blockText)
 947            guard found.location != NSNotFound,
 948                  ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else {
 949                return .failure(.message("The block changed while it ran; the result wasn't written."))
 950            }
 951            blockRange = found.location..<NSMaxRange(found)
 952        }
 953        let value = Self.value(job.finish, output)
 954        if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
 955        let buffer = EmacsBuffer(text, point: 0, settings: settings)
 956        if job.finish.inline {
 957            do {
 958                try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer)
 959            } catch let error as Failure {
 960                return .failure(error)
 961            } catch {
 962                return .failure(.message("\(error)"))
 963            }
 964            return .success(TextEdit.between(text, buffer.text as String))
 965        }
 966        insertResult(value, job.finish, block: blockRange, buffer: buffer)
 967        return .success(TextEdit.between(text, buffer.text as String))
 968    }
 969
 970    /// The language's result handling: `org-babel-result-cond` and the table import.
 971    static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
 972        let params = finish.params
 973        if params.contains("file") {
 974            // `org-babel-result-to-file`: a link to `:file`, or to the result as a path.
 975            let path = finish.file ?? rawResult(finish, output)
 976            var link = "[[file:" + path + "]"
 977            if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
 978            return .string(link + "]")
 979        }
 980        let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
 981            || params.contains("pp") || params.contains("file")
 982            || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
 983        switch finish.kind {
 984        case .shell(let valueIsExitStatus):
 985            var results = output.stdout
 986            if valueIsExitStatus {
 987                results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? ""
 988            }
 989            if scalar { return .string(results) }
 990            return importTable(results)
 991        case .generic:
 992            return .string(output.stdout)
 993        case .python:
 994            let raw = finish.output ? output.stdout : (output.resultFile ?? "")
 995            if scalar { return .string(raw) }
 996            return pythonValue(raw)
 997        case .emacsLisp:
 998            guard let data = output.stdout.data(using: .utf8),
 999                  let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) }
1000            if scalar {
1001                return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "")
1002            }
1003            if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") }
1004            if let rows = object["rows"] as? [Any] {
1005                return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) })
1006            }
1007            let printed = object["S"] as? String ?? ""
1008            return printed == "nil" ? .none : .string(printed)
1009        }
1010    }
1011
1012    /// The result as the program left it, before tables are read.
1013    static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String {
1014        switch finish.kind {
1015        case .python: return finish.output ? output.stdout : (output.resultFile ?? "")
1016        case .emacsLisp:
1017            guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
1018            return object["s"] as? String ?? ""
1019        case .shell(let valueIsExitStatus):
1020            return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
1021        case .generic: return output.stdout
1022        }
1023    }
1024
1025    /// With `:results file` and `:file`, what to write there, relative to the run's folder;
1026    /// nil when there's nothing to write or the program wrote it.
1027    public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? {
1028        guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil }
1029        return (file, rawResult(job.finish, output))
1030    }
1031
1032    /// `org-babel-import-elisp-from-file`.
1033    static func importTable(_ results: String) -> Value {
1034        guard !results.isEmpty else { return .none }
1035        var lines = results.components(separatedBy: "\n")
1036        if lines.last == "" { lines.removeLast() }
1037        let nonEmpty = lines.filter { !$0.isEmpty }
1038        let rows: [[String]]
1039        if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) {
1040            rows = lines.map { $0.components(separatedBy: "\t") }
1041        } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) {
1042            rows = lines.map(csvFields)
1043        } else if lines.count == 1 {
1044            rows = [[lines[0]]]
1045        } else {
1046            rows = lines.map { line in
1047                let trimmed = line.drop { $0 == " " }
1048                return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty
1049                    ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
1050            }
1051        }
1052        let cells = rows.map { row in row.map { field -> String in
1053            let trimmed = field.trimmingCharacters(in: .whitespaces)
1054            switch cell(trimmed) {
1055            case .number(let n): return n
1056            case .text(let t): return t
1057            }
1058        } }
1059        if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) }
1060        return .table(cells)
1061    }
1062
1063    static func csvFields(_ line: String) -> [String] {
1064        var fields: [String] = []
1065        var current = ""
1066        var quoted = false
1067        for c in line {
1068            if c == "\"" {
1069                quoted.toggle()
1070            } else if c == ",", !quoted {
1071                fields.append(current.trimmingCharacters(in: .whitespaces))
1072                current = ""
1073            } else {
1074                current.append(c)
1075            }
1076        }
1077        fields.append(current.trimmingCharacters(in: .whitespaces))
1078        return fields
1079    }
1080
1081    /// `org-babel-python-table-or-string`.
1082    static func pythonValue(_ raw: String) -> Value {
1083        guard let first = raw.first, let last = raw.last, raw.count >= 2,
1084              (first == "[" && last == "]") || (first == "(" && last == ")") else {
1085            if raw.isEmpty { return .string("") }
1086            if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) {
1087                return .string(String(raw.dropFirst().dropLast()))
1088            }
1089            if let n = number(raw) { return .string(n) }
1090            return .string(raw)
1091        }
1092        var parser = PythonLiteral(Array(raw))
1093        guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) }
1094        func text(_ v: PythonLiteral.Node) -> String {
1095            switch v {
1096            case .atom(let s): return s
1097            case .string(let s): return s
1098            case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")"
1099            }
1100        }
1101        if items.allSatisfy({ if case .list = $0 { return true }; if case .atom("None") = $0 { return true }; return false }) {
1102            return .table(items.map { item -> [String]? in
1103                if case .list(let cells) = item { return cells.map(text) }
1104                return nil
1105            })
1106        }
1107        return .table([items.map { if case .atom("None") = $0 { return "hline" }; return text($0) }])
1108    }
1109
1110    struct PythonLiteral {
1111        indirect enum Node: Equatable {
1112            case atom(String)
1113            case string(String)
1114            case list([Node])
1115        }
1116
1117        let chars: [Character]
1118        var i = 0
1119        init(_ chars: [Character]) { self.chars = chars }
1120        var atEnd: Bool { mutating get { skip(); return i == chars.count } }
1121
1122        mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } }
1123
1124        mutating func parse() -> Node? {
1125            skip()
1126            guard i < chars.count else { return nil }
1127            let c = chars[i]
1128            if c == "[" || c == "(" {
1129                let close: Character = c == "[" ? "]" : ")"
1130                i += 1
1131                var items: [Node] = []
1132                skip()
1133                if i < chars.count, chars[i] == close {
1134                    i += 1
1135                    return .list(items)
1136                }
1137                while true {
1138                    guard let item = parse() else { return nil }
1139                    items.append(item)
1140                    skip()
1141                    guard i < chars.count else { return nil }
1142                    if chars[i] == "," {
1143                        i += 1
1144                        skip()
1145                        if i < chars.count, chars[i] == close {
1146                            i += 1
1147                            return .list(items)
1148                        }
1149                        continue
1150                    }
1151                    if chars[i] == close {
1152                        i += 1
1153                        return .list(items)
1154                    }
1155                    return nil
1156                }
1157            }
1158            if c == "'" || c == "\"" {
1159                i += 1
1160                var s = ""
1161                while i < chars.count, chars[i] != c {
1162                    if chars[i] == "\\", i + 1 < chars.count {
1163                        i += 1
1164                        switch chars[i] {
1165                        case "n": s.append("\n")
1166                        case "t": s.append("\t")
1167                        default: s.append(chars[i])
1168                        }
1169                    } else {
1170                        s.append(chars[i])
1171                    }
1172                    i += 1
1173                }
1174                guard i < chars.count else { return nil }
1175                i += 1
1176                return .string(s)
1177            }
1178            var s = ""
1179            while i < chars.count, !",)] \n".contains(chars[i]) {
1180                s.append(chars[i])
1181                i += 1
1182            }
1183            guard !s.isEmpty else { return nil }
1184            return .atom(number(s) ?? s)
1185        }
1186    }
1187
1188    // MARK: - Inserting
1189
1190    static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:"
1191
1192    /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results
1193    /// keyword, added when there is none.
1194    static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int {
1195        let ns = buffer.text
1196        if let name = finish.name {
1197            let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
1198            let regex = try! NSRegularExpression(pattern: pattern)
1199            for m in regex.matches(in: ns as String, range: NSRange(location: 0, length: ns.length)) {
1200                // Not the name of another block.
1201                return m.range.location
1202            }
1203        } else {
1204            // The element after the block, past blank lines.
1205            var location = block.upperBound
1206            while location < ns.length {
1207                let line = ns.lineRange(for: NSRange(location: location, length: 0))
1208                let content = ns.substring(with: line)
1209                if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1210                    location = NSMaxRange(line)
1211                    continue
1212                }
1213                if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil {
1214                    return line.location
1215                }
1216                break
1217            }
1218        }
1219        // A new keyword after the block.
1220        buffer.point = min(block.upperBound, buffer.length)
1221        buffer.skipBackward([32, 9, 10, 13])
1222        buffer.forwardLine(1)
1223        if !buffer.bolp { buffer.insert("\n") }
1224        let indent = buffer.saveExcursion { () -> String in
1225            buffer.point = block.lowerBound
1226            let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
1227            return String(line.prefix { $0 == " " || $0 == "\t" })
1228        }
1229        buffer.insert("\n")
1230        let keywordLine = buffer.point
1231        buffer.insert(indent + "#+RESULTS:" + (finish.name.map { " " + $0 } ?? "") + "\n")
1232        if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
1233            buffer.saveExcursion { buffer.insert("\n") }
1234        }
1235        return keywordLine
1236    }
1237
1238    /// `org-babel-result-end` with point at the start of the result.
1239    static func resultEnd(_ buffer: EmacsBuffer) -> Int {
1240        let start = buffer.point
1241        let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start))
1242        if line.trimmingCharacters(in: .whitespaces).isEmpty { return start }
1243        if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil {
1244            return min(buffer.length, buffer.lineEnd(start) + 1)
1245        }
1246        let tree = OrgParser.parse(buffer.text as String)
1247        var node = tree.root
1248        var found: SyntaxNode?
1249        while let child = node.child(containing: start) {
1250            if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) {
1251                if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) {
1252                    found = child
1253                    break
1254                }
1255            }
1256            node = child
1257        }
1258        guard let element = found else { return start }
1259        var end = element.range.upperBound
1260        while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 }
1261        return min(buffer.length, buffer.lineEnd(end) + 1)
1262    }
1263
1264    /// `org-babel-insert-result` for a src block.
1265    /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already
1266    /// there; raw results go in as they are.
1267    static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws {
1268        var string: String
1269        switch value {
1270        case .none: string = ""
1271        case .string(let s): string = s
1272        case .table(let rows):
1273            let cells = rows.compactMap { $0 }
1274            guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") }
1275            string = cells[0][0]
1276        }
1277        buffer.point = object.upperBound
1278        if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") {
1279            buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound)
1280        }
1281        if finish.params.contains("raw") {
1282            buffer.insert(" " + string)
1283            return
1284        }
1285        if string.hasSuffix("\n") { string.removeLast() }
1286        guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") }
1287        buffer.insert(" {{{results(=" + string + "=)}}}")
1288    }
1289
1290    static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) {
1291        let params = finish.params
1292        let keyword = resultsLine(finish, block: block, buffer: buffer)
1293        buffer.point = keyword
1294        let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count
1295        buffer.forwardLine(1)
1296        if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") }
1297        var beg = buffer.point
1298        if params.contains("replace") {
1299            buffer.deleteRegion(beg, resultEnd(buffer))
1300            buffer.point = beg
1301        } else if params.contains("append") {
1302            buffer.point = resultEnd(buffer)
1303            beg = buffer.point
1304        }
1305        var tabulated = false
1306        switch value {
1307        case .none:
1308            break
1309        case .string(var s) where params.contains("list"):
1310            if s.last != "\n" { s += "\n" }
1311            let items = s.split(separator: "\n", omittingEmptySubsequences: true)
1312            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1313        case .table(let rows) where params.contains("list"):
1314            let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
1315            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1316        case .table(let rows):
1317            tabulated = true
1318            let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" }
1319            let start = buffer.point
1320            buffer.insert(lines.joined(separator: "\n") + "\n")
1321            buffer.point = start
1322            buffer.tableAlign()
1323            buffer.point = buffer.tableEnd()
1324        case .string(var s):
1325            if !s.isEmpty, s.last != "\n" { s += "\n" }
1326            buffer.insert(s)
1327        }
1328        let end = buffer.marker(buffer.point, advances: true)
1329        defer { buffer.release(end) }
1330        func wrap(_ open: String, _ close: String, escape: Bool) {
1331            buffer.point = end.position
1332            buffer.insert(close + "\n")
1333            buffer.point = beg
1334            buffer.insert(open + "\n")
1335            if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) }
1336        }
1337        if let wrapValue = finish.wrap {
1338            let full = wrapValue.isEmpty ? "results" : wrapValue
1339            let type = String(full.split(separator: " ").first ?? "results")
1340            if type.lowercased() != "nil", type.lowercased() != "no" {
1341                wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true)
1342            }
1343        } else if params.contains("html") {
1344            wrap("#+begin_export html", "#+end_export", escape: true)
1345        } else if params.contains("latex") {
1346            wrap("#+begin_export latex", "#+end_export", escape: true)
1347        } else if params.contains("org") {
1348            wrap("#+begin_src org", "#+end_src", escape: true)
1349        } else if params.contains("code") {
1350            wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true)
1351        } else if params.contains("raw") || params.contains("file") {
1352            // As inserted.
1353        } else if params.contains("drawer") {
1354            wrap(":results:", ":end:", escape: false)
1355        } else if !tabulated, !params.contains("list") {
1356            examplify(buffer, beg, end.position)
1357        }
1358        if indent > 0, !(tabulated && params.contains("append")) {
1359            buffer.point = beg
1360            while buffer.point < end.position {
1361                if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) }
1362                if buffer.forwardLine(1) != 0 { break }
1363            }
1364        }
1365    }
1366
1367    /// `org-escape-code-in-region`.
1368    static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) {
1369        buffer.point = start
1370        let stop = buffer.marker(end)
1371        defer { buffer.release(stop) }
1372        while buffer.point < stop.position {
1373            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
1374            if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) {
1375                buffer.point += line[..<m.1.startIndex].utf16.count
1376                buffer.insert(",")
1377            }
1378            if buffer.forwardLine(1) != 0 { break }
1379        }
1380    }
1381
1382    /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
1383    static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
1384        let text = buffer.substring(beg, end)
1385        var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0)
1386        if text.isEmpty { size = 0 }
1387        guard size > 0 else { return }
1388        if size < 10 {
1389            buffer.point = beg
1390            for _ in 0..<size {
1391                buffer.point = buffer.lineStart(buffer.point)
1392                buffer.insert(": ")
1393                buffer.forwardLine(1)
1394            }
1395            return
1396        }
1397        let endMarker = buffer.marker(end)
1398        defer { buffer.release(endMarker) }
1399        buffer.point = beg
1400        buffer.insert("#+begin_example\n")
1401        escapeCode(buffer, from: buffer.point, to: endMarker.position)
1402        buffer.point = endMarker.position
1403        if !buffer.bolp { buffer.insert("\n") }
1404        buffer.insert("#+end_example")
1405        if !buffer.eolp { buffer.insert("\n") }
1406    }
1407}
1408
1409/// C-c C-c in a src block: `org-babel-execute-src-block`.
1410public struct ExecuteSrcBlock: OrgCommand {
1411    public init() {}
1412    public var id: String { "org.babel.execute" }
1413    public var title: String { "Run Source Block" }
1414    public func applies(in context: EditContext) -> Bool { KeyContext.holds("src", in: context) || Self.atCallOrInline(context) }
1415
1416    /// On a `#+CALL:` line or an inline `src_` block.
1417    static func atCallOrInline(_ context: EditContext) -> Bool {
1418        let ns = context.text as NSString
1419        let line = ns.substring(with: ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0)))
1420        if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil { return true }
1421        var node = context.tree.root
1422        while let child = node.child(containing: context.caret) {
1423            if child.kind == .inlineSourceBlock { return true }
1424            node = child
1425        }
1426        return false
1427    }
1428
1429    public func run(in context: EditContext) -> CommandStep {
1430        switch Babel.plan(context) {
1431        case .success(let job): return .external(.babel(job))
1432        case .failure(.message(let message)): return .failed(message)
1433        }
1434    }
1435}
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