Sources/OrgCore/Compute/BabelHeaders.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/OrgCore/Compute/BabelHeaders.swift history · blame · raw

209 lines · 10262 bytes

  1import Foundation
  2
  3extension Babel {
  4    // MARK: - Header arguments
  5
  6    struct Params {
  7        var results: [String] = ["replace"]
  8        var single: [String: String] = [:]
  9        var vars: [(name: String, value: String)] = []
 10        var wrap: String?
 11        /// Keys whose value is Lisp to evaluate (`org-babel-read`): unquoted, starting with `(`, `'`, `` ` `` or `[`.
 12        var lisp: Set<String> = []
 13        /// Keys whose value was a quoted string, which `org-babel-read` doesn't take for a number.
 14        var quoted: Set<String> = []
 15        /// Lisp values evaluated to something other than a string or number, such as a list of
 16        /// column names.
 17        var evaluated: [String: Sexp] = [:]
 18
 19        /// `org-babel-read` on the Lisp values the interpreter can evaluate: a string or number
 20        /// takes the form's place; other values are kept in `evaluated`.
 21        mutating func evaluateLisp(file: String?) {
 22            for key in lisp {
 23                guard let form = try? LispReader.readFirst(single[key] ?? "").sexp,
 24                      let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form) else { continue }
 25                let printed = Elisp.printed(value)
 26                if let s = value.string {
 27                    single[key] = s
 28                    quoted.insert(key)
 29                    lisp.remove(key)
 30                } else if Babel.number(printed) == printed {
 31                    single[key] = printed
 32                    lisp.remove(key)
 33                } else {
 34                    evaluated[key] = value
 35                }
 36            }
 37        }
 38
 39        static let resultGroups: [Set<String>] = [
 40            ["file", "list", "vector", "table", "scalar", "verbatim"],
 41            ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"],
 42            ["replace", "silent", "none", "discard", "append", "prepend"],
 43            ["output", "value"],
 44        ]
 45
 46        /// `defaults` go under the properties, as `org-babel-default-inline-header-args` do.
 47        init(block: SrcBlockInfo, model: DocumentModel, text: NSString, defaults: [(String, String)] = [], extra: [[(String, String)]] = [],
 48             inline: Bool = false) throws {
 49            var layers: [[(String, String)]] = [defaults, Babel.languageDefaults[block.language ?? ""] ?? []]
 50            layers += Params.propertyLayers(language: block.language ?? "", heading: block.heading, model: model)
 51            let firstLine = inline ? "" : text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0)))
 52            if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) {
 53                var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
 54                while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") {
 55                    rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces)
 56                }
 57                layers.append(Params.parse(rest))
 58            }
 59            // `#+HEADER:` lines above the block.
 60            var headers: [String] = []
 61            var location = block.range.lowerBound
 62            while !inline, location > 0 {
 63                let previous = text.lineRange(for: NSRange(location: location - 1, length: 0))
 64                let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines)
 65                guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break }
 66                if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) }
 67                location = previous.location
 68            }
 69            for header in headers { layers.append(Params.parse(header)) }
 70            layers += extra
 71
 72            for layer in layers {
 73                for (key, raw) in layer {
 74                    let quoted = key != ":var" && raw.count >= 2 && raw.hasPrefix("\"") && raw.hasSuffix("\"")
 75                    let value = quoted ? Params.unescape(String(raw.dropFirst().dropLast())) : raw
 76                    if key != ":var" {
 77                        if !quoted, let first = value.first, "('`[".contains(first) { lisp.insert(key) } else { lisp.remove(key) }
 78                        if quoted { self.quoted.insert(key) } else { self.quoted.remove(key) }
 79                    }
 80                    switch key {
 81                    case ":results":
 82                        for word in value.split(whereSeparator: \.isWhitespace).map(String.init) {
 83                            if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } }
 84                            results.removeAll { $0 == word }
 85                            results.insert(word, at: 0)
 86                        }
 87                    case ":var":
 88                        for value in Params.splitVars(value) {
 89                            guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") }
 90                            let name = value[..<eq].trimmingCharacters(in: .whitespaces)
 91                            let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces)
 92                            vars.removeAll { $0.name == name }
 93                            vars.append((name, assigned))
 94                        }
 95                    case ":wrap":
 96                        wrap = value
 97                    default:
 98                        single[key] = value
 99                    }
100                }
101            }
102        }
103
104        /// `org-babel-params-from-properties` under `heading`, or before any: the inherited
105        /// `header-args`, then the inherited `header-args:LANG`, each the nearest value with `+`
106        /// additions after it.
107        static func propertyLayers(language: String, heading: Int?, model: DocumentModel) -> [[(String, String)]] {
108            var levels = [model.fileProperties]
109            if let heading {
110                levels += (model.ancestors(of: heading) + [heading]).map { model.headings[$0].properties }
111            }
112            return ["header-args", "header-args:\(language)"].compactMap { key in
113                var value: String?
114                for entries in levels {
115                    for entry in entries where entry.key.lowercased() == key {
116                        value = entry.additive ? [value, entry.value].compactMap { $0 }.joined(separator: " ") : entry.value
117                    }
118                }
119                return value.map(Params.parse)
120            }
121        }
122
123        /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and
124        /// parentheses.
125        /// A Lisp string's contents as `read` gives them.
126        static func unescape(_ s: String) -> String {
127            var out = ""
128            var escaped = false
129            for c in s {
130                if escaped {
131                    switch c {
132                    case "n": out.append("\n")
133                    case "t": out.append("\t")
134                    default: out.append(c)
135                    }
136                    escaped = false
137                } else if c == "\\" {
138                    escaped = true
139                } else {
140                    out.append(c)
141                }
142            }
143            return out
144        }
145
146        /// `org-babel-parse-multiple-vars`: one `:var` value holding several assignments split
147        /// on spaces outside quotes and brackets, pieces split beside `=` joined again.
148        static func splitVars(_ value: String) -> [String] {
149            var pieces: [String] = []
150            var current = ""
151            var depth = 0
152            var quoted = false
153            var previous: Character = " "
154            for c in value {
155                if c == "\"", previous != "\\" { quoted.toggle() }
156                previous = c
157                if !quoted, "([{".contains(c) { depth += 1 }
158                if !quoted, ")]}".contains(c) { depth = max(0, depth - 1) }
159                if c == " ", !quoted, depth == 0 {
160                    if !current.isEmpty { pieces.append(current) }
161                    current = ""
162                } else {
163                    current.append(c)
164                }
165            }
166            if !current.isEmpty { pieces.append(current) }
167            var joined: [String] = []
168            for piece in pieces {
169                if let last = joined.last, last.hasSuffix("=") || piece.hasPrefix("=") {
170                    joined[joined.count - 1] = last + piece
171                } else {
172                    joined.append(piece)
173                }
174            }
175            return joined.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
176        }
177
178        static func parse(_ text: String) -> [(String, String)] {
179            var parts: [String] = []
180            var current = ""
181            var depth = 0
182            var quoted = false
183            var previous: Character = " "
184            for c in text {
185                if c == "\"", previous != "\\" { quoted.toggle() }
186                if !quoted {
187                    if c == "(" { depth += 1 }
188                    if c == ")" { depth = max(0, depth - 1) }
189                }
190                if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" {
191                    parts.append(current)
192                    current = ""
193                }
194                current.append(c)
195                previous = c
196            }
197            parts.append(current)
198            var pairs: [(String, String)] = []
199            for part in parts {
200                let trimmed = part.trimmingCharacters(in: .whitespaces)
201                guard trimmed.hasPrefix(":") else { continue }
202                let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased()
203                // Quotes stay until the value is used, so a quoted string isn't taken for Lisp.
204                pairs.append((key, trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces)))
205            }
206            return pairs
207        }
208    }
209}