Sources/OrgCore/Compute/Babel.swift

6a36ba0352b0f5419d22dd2e4100ecf4f38b8ea7
orgstar/Sources/OrgCore/Compute/Babel.swift

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