Sources/OrgCore/Compute/Babel.swift

3f183dc5a69542840ae20a73ec755d1148b354dd
orgstar/Sources/OrgCore/Compute/Babel.swift history · blame · raw

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