Sources/OrgCore/Compute/BabelNoweb.swift
146 lines · 8861 bytes
1import Foundation
2
3extension Babel {
4 // MARK: - Noweb
5
6 /// `org-babel-noweb-p` in the `:eval` context.
7 static func nowebEvaluates(_ value: String?) -> Bool {
8 (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "no-export", "strip-export", "eval", "strip-tangle"].contains(String($0)) }
9 }
10
11 /// `org-babel-noweb-p` for `:tangle`.
12 static func nowebTangles(_ value: String?) -> Bool {
13 (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "tangle", "no-export", "strip-export", "strip-tangle"].contains(String($0)) }
14 }
15
16 /// `org-babel-expand-noweb-references` for evaluation: each `<<name>>` becomes the body of
17 /// the block named so, or of every block with that `:noweb-ref`, joined by `:noweb-sep`, or
18 /// the contents of the heading with that ID; the text before it on its line goes before
19 /// each line it brings.
20 /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as
21 /// evaluation does.
22 /// `links` gives a block's begin and end comments, for `:comments noweb` when tangling.
23 /// `<<name()>>` and `<<name(arg=value)>>` become the result of the block named so, which
24 /// `refs` resolves as it does a `:var` (`org-babel-ref-resolve`); without `refs` nothing
25 /// may run, and they are refused.
26 static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0,
27 links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil, refs: References? = nil) throws -> String {
28 guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") }
29 let body = normalizedBody(block)
30 let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true
31 let commenting = tangling && links != nil && params.single[":comments"] == "noweb"
32 func expand(_ other: SrcBlockInfo) throws -> String {
33 let otherParams = try Params(block: other, model: model, text: text)
34 let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"])
35 let b = expands
36 ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links, refs: refs)
37 : normalizedBody(other)
38 guard commenting, let links else { return b }
39 // `c-wrap`: commented in this block's language, trimmed.
40 func wrap(_ s: String) throws -> String {
41 try Tangle.commentRegion(s, language: block.language ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
42 }
43 var (begin, end) = try links(other.name == nil ? block : other, other.name == nil ? params : otherParams)
44 // A `:noweb-ref` block without a name: the link is the including block's, the name empty.
45 if other.name == nil {
46 if let split = begin.range(of: "][") { begin = begin[..<split.lowerBound] + "][]]" }
47 end = " ends here"
48 }
49 return try wrap(begin) + "\n" + b + "\n" + (try wrap(end)) + "\n"
50 }
51 func inCommentedHeading(_ b: SrcBlockInfo) -> Bool {
52 guard let h = b.heading else { return false }
53 return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
54 }
55 let ns = body as NSString
56 var out = ""
57 var at = 0
58 for m in nowebReference.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
59 let prefix = ns.substring(with: m.range(at: 1))
60 let id = ns.substring(with: m.range(at: 3))
61 out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at))
62 at = NSMaxRange(m.range)
63 var expansion = ""
64 if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
65 guard let refs else {
66 throw Failure.message("The noweb reference <<\(id)>> would run a block while tangling, which isn't supported yet; nothing was tangled.")
67 }
68 // The value as it is when a string, else printed with `%S`.
69 switch try resolve(id, model: model, text: text, refs: refs, through: "a noweb reference") {
70 case .scalar(let s): expansion = s
71 case let value: expansion = lispLiteral(value)
72 }
73 } else if let heading = model.headings.firstIndex(where: { h in
74 h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) }
75 }) {
76 expansion = headlineBody(heading, model: model, text: text)
77 } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) {
78 expansion = try expand(named)
79 } else {
80 var parts: [String] = []
81 var separators: [String] = []
82 for other in model.srcBlocks where !inCommentedHeading(other) {
83 let p = try Params(block: other, model: model, text: text)
84 guard p.single[":noweb-ref"] == id else { continue }
85 parts.append(try expand(other))
86 separators.append(p.single[":noweb-sep"] ?? "\n")
87 }
88 for (i, part) in parts.enumerated() {
89 if i > 0 { expansion += separators[i - 1] }
90 expansion += part
91 }
92 }
93 out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion
94 }
95 return out + ns.substring(from: at)
96 }
97
98 /// `org-babel-noweb-wrap` after the text before it on its line.
99 static let nowebReference = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
100
101 /// The references that run a block in the body of `block`, and in the bodies its other
102 /// references bring in when evaluation expands them.
103 static func nowebCalls(_ block: SrcBlockInfo, model: DocumentModel, text: NSString, seen: inout Set<Int>) -> [String] {
104 guard seen.insert(block.range.lowerBound).inserted else { return [] }
105 var calls: [String] = []
106 let body = block.body as NSString
107 for m in nowebReference.matches(in: block.body, range: NSRange(location: 0, length: body.length)) {
108 let id = body.substring(with: m.range(at: 3))
109 if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
110 calls.append(id)
111 continue
112 }
113 for other in model.srcBlocks {
114 guard let params = try? Params(block: other, model: model, text: text), other.name == id || params.single[":noweb-ref"] == id,
115 nowebEvaluates(params.single[":noweb"]) else { continue }
116 calls += nowebCalls(other, model: model, text: text, seen: &seen)
117 }
118 }
119 return calls
120 }
121
122 /// `org-babel-ref-headline-body`: the entry after its planning and drawers.
123 static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String {
124 let heading = model.headings[index]
125 let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound)
126 buffer.endOfMetaData()
127 let start = buffer.point
128 let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length
129 return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : ""
130 }
131
132 /// `org-babel--normalize-body`: without the final newline, and without the indentation
133 /// common to its lines unless `-i` keeps it.
134 static func normalizedBody(_ block: SrcBlockInfo) -> String {
135 var lines = block.body.components(separatedBy: "\n")
136 if lines.last == "" { lines.removeLast() }
137 // Org escapes lines starting with `*` or `#+` inside blocks with a comma.
138 lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
139 if !block.switches.contains("-i") {
140 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
141 let common = indents.min() ?? 0
142 lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }
143 }
144 return lines.joined(separator: "\n")
145 }
146}