Sources/OrgCore/Compute/BabelNoweb.swift
113 lines · 6954 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 static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0,
24 links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil) throws -> String {
25 guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") }
26 let body = normalizedBody(block)
27 let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true
28 let commenting = tangling && links != nil && params.single[":comments"] == "noweb"
29 func expand(_ other: SrcBlockInfo) throws -> String {
30 let otherParams = try Params(block: other, model: model, text: text)
31 let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"])
32 let b = expands
33 ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links)
34 : normalizedBody(other)
35 guard commenting, let links else { return b }
36 // `c-wrap`: commented in this block's language, trimmed.
37 func wrap(_ s: String) throws -> String {
38 try Tangle.commentRegion(s, language: block.language ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
39 }
40 var (begin, end) = try links(other.name == nil ? block : other, other.name == nil ? params : otherParams)
41 // A `:noweb-ref` block without a name: the link is the including block's, the name empty.
42 if other.name == nil {
43 if let split = begin.range(of: "][") { begin = begin[..<split.lowerBound] + "][]]" }
44 end = " ends here"
45 }
46 return try wrap(begin) + "\n" + b + "\n" + (try wrap(end)) + "\n"
47 }
48 func inCommentedHeading(_ b: SrcBlockInfo) -> Bool {
49 guard let h = b.heading else { return false }
50 return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
51 }
52 let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
53 let ns = body as NSString
54 var out = ""
55 var at = 0
56 for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
57 let prefix = ns.substring(with: m.range(at: 1))
58 let id = ns.substring(with: m.range(at: 3))
59 out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at))
60 at = NSMaxRange(m.range)
61 var expansion = ""
62 if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
63 throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.")
64 } else if let heading = model.headings.firstIndex(where: { h in
65 h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) }
66 }) {
67 expansion = headlineBody(heading, model: model, text: text)
68 } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) {
69 expansion = try expand(named)
70 } else {
71 var parts: [String] = []
72 var separators: [String] = []
73 for other in model.srcBlocks where !inCommentedHeading(other) {
74 let p = try Params(block: other, model: model, text: text)
75 guard p.single[":noweb-ref"] == id else { continue }
76 parts.append(try expand(other))
77 separators.append(p.single[":noweb-sep"] ?? "\n")
78 }
79 for (i, part) in parts.enumerated() {
80 if i > 0 { expansion += separators[i - 1] }
81 expansion += part
82 }
83 }
84 out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion
85 }
86 return out + ns.substring(from: at)
87 }
88
89 /// `org-babel-ref-headline-body`: the entry after its planning and drawers.
90 static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String {
91 let heading = model.headings[index]
92 let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound)
93 buffer.endOfMetaData()
94 let start = buffer.point
95 let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length
96 return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : ""
97 }
98
99 /// `org-babel--normalize-body`: without the final newline, and without the indentation
100 /// common to its lines unless `-i` keeps it.
101 static func normalizedBody(_ block: SrcBlockInfo) -> String {
102 var lines = block.body.components(separatedBy: "\n")
103 if lines.last == "" { lines.removeLast() }
104 // Org escapes lines starting with `*` or `#+` inside blocks with a comma.
105 lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
106 if !block.switches.contains("-i") {
107 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
108 let common = indents.min() ?? 0
109 lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }
110 }
111 return lines.joined(separator: "\n")
112 }
113}