Sources/OrgCore/Compute/Babel.swift

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

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