Sources/OrgCore/Compute/Tangle.swift
400 lines · 21566 bytes
1import Foundation
2
3// `org-babel-tangle` (Org 9.8.7 ob-tangle.el): source blocks written to the files their
4// `:tangle` names, with `:noweb`, `:padline`, `:shebang`, `:mkdirp`, `:tangle-mode`,
5// `:prologue` and `:epilogue`, `:var` for shells, Python and Emacs Lisp, and `:comments` for
6// languages whose comment syntax is known. Header values Org would evaluate as Lisp aren't
7// supported.
8
9public enum Tangle {
10 /// All blocks (C-c C-v t), the block at an offset (C-u C-c C-v t), or the blocks going to
11 /// the same file as the block at an offset (C-u C-u C-c C-v t).
12 public enum Scope: Sendable, Equatable {
13 case all
14 case block(Int)
15 case target(Int)
16 }
17
18 public struct File: Sendable, Equatable {
19 /// Absolute.
20 public var path: String
21 public var contents: String
22 /// From `:tangle-mode`, or 0o755 for a file with a `:shebang`; nil leaves the mode alone.
23 public var mode: Int?
24 /// `:mkdirp`: the file's directory is made if missing.
25 public var makeDirectories: Bool
26 }
27
28 public struct Output: Sendable, Equatable {
29 public var files: [File]
30 /// Blocks written, for "Tangled N code blocks".
31 public var blocks: Int
32 }
33
34 /// `org-babel-tangle-lang-exts`.
35 static let extensions = ["emacs-lisp": "el", "elisp": "el", "bibtex": "bib"]
36 /// `org-babel-shell-names`, and `shell` itself.
37 static let shells: Set<String> = ["sh", "bash", "zsh", "fish", "csh", "ash", "dash", "ksh", "mksh", "posh", "shell"]
38
39 /// The files tangling `text`, the contents of the Org file at `path`, writes.
40 public static func run(text: String, path: String, scope: Scope = .all, tree: OrgTree? = nil) -> Result<Output, Babel.Failure> {
41 let ns = text as NSString
42 let model = DocumentModel(tree: tree ?? OrgParser.parse(text))
43 do {
44 var order: [String] = []
45 var specs: [String: [(language: String?, body: String, params: Babel.Params)]] = [:]
46 // `org-babel-tangle-collect-blocks`: blocks numbered from 1 under each heading.
47 var counters: [Int: Int] = [:]
48 var lastHeading: Int?? = .none
49 var counter = 0
50 for block in model.srcBlocks {
51 if lastHeading == .some(block.heading) { counter += 1 } else { (counter, lastHeading) = (1, .some(block.heading)) }
52 counters[block.range.lowerBound] = counter
53 }
54 func add(_ block: SrcBlockInfo, _ params: Babel.Params, counter: Int) throws {
55 guard let file = try fileName(path: path, language: block.language, tangle: params.single[":tangle"] ?? "no") else { return }
56 let parsed = tree ?? OrgParser.parse(text)
57 let links = { (other: SrcBlockInfo, otherParams: Babel.Params) in
58 try Self.links(other, params: otherParams, counter: counters[other.range.lowerBound] ?? 1, path: path, model: model, tree: parsed, text: ns)
59 }
60 let body = try spec(block, body: try body(block, params: params, model: model, text: ns, links: links), params: params, counter: counter,
61 path: path, model: model, tree: parsed, text: ns)
62 if specs[file] == nil { order.append(file) }
63 specs[file, default: []].append((block.language, body, params))
64 }
65 switch scope {
66 case .block(let offset):
67 guard let block = block(at: offset, in: model) else { throw Babel.Failure.message("Point is not in a source code block") }
68 try add(block, try params(block, model: model, text: ns), counter: 1)
69 case .all, .target:
70 var target: String?
71 if case .target(let offset) = scope {
72 guard let block = block(at: offset, in: model) else { throw Babel.Failure.message("Point is not in a source code block") }
73 target = try params(block, model: model, text: ns).single[":tangle"] ?? "no"
74 }
75 for block in model.srcBlocks where !excluded(block, model: model) {
76 let params = try params(block, model: model, text: ns)
77 let tangle = params.single[":tangle"] ?? "no"
78 if tangle == "no" || (block.language == nil && tangle == "yes") { continue }
79 if let target, target != tangle { continue }
80 try add(block, params, counter: counters[block.range.lowerBound] ?? 1)
81 }
82 }
83 var files: [File] = []
84 var blocks = 0
85 for file in order {
86 var contents = ""
87 var mode: Int?
88 var makeDirectories = false
89 var sheBanged = false
90 for spec in specs[file]! {
91 let shebang = spec.params.single[":shebang"].flatMap { $0.isEmpty ? nil : $0 }
92 var tangleMode = try spec.params.single[":tangle-mode"].map(fileMode)
93 if shebang != nil, tangleMode == nil { tangleMode = 0o755 }
94 // `add-to-list` then `mapc`: the first mode given is the one left.
95 if mode == nil { mode = tangleMode }
96 if let mkdirp = spec.params.single[":mkdirp"], mkdirp != "no" { makeDirectories = true }
97 if spec.params.single[":padline"] != "no", !contents.isEmpty { contents += "\n" }
98 if let shebang, !sheBanged {
99 contents += shebang + "\n"
100 sheBanged = true
101 }
102 contents += spec.body
103 blocks += 1
104 }
105 files.append(File(path: file, contents: contents, mode: mode, makeDirectories: makeDirectories))
106 }
107 return .success(Output(files: files, blocks: blocks))
108 } catch let error as Babel.Failure {
109 return .failure(error)
110 } catch {
111 return .failure(.message("\(error)"))
112 }
113 }
114
115 /// `org-babel-where-is-src-block-head`.
116 static func block(at offset: Int, in model: DocumentModel) -> SrcBlockInfo? {
117 model.srcBlocks.first { $0.range.contains(offset) || $0.range.upperBound == offset }
118 }
119
120 /// `org-in-commented-heading-p` and `org-in-archived-heading-p`.
121 static func excluded(_ block: SrcBlockInfo, model: DocumentModel) -> Bool {
122 guard let heading = block.heading else { return false }
123 return ([heading] + model.ancestors(of: heading)).contains { index in
124 let h = model.headings[index]
125 return AgendaSource.isCommented(h.title) || h.localTags.contains("ARCHIVE")
126 }
127 }
128
129 static func params(_ block: SrcBlockInfo, model: DocumentModel, text: NSString) throws -> Babel.Params {
130 let params = try Babel.Params(block: block, model: model, text: text)
131 for (key, value) in params.single where value.hasPrefix("(") && key != ":tangle-mode" {
132 throw Babel.Failure.message("\(key) \(value) is Lisp to evaluate, which tangling doesn't support yet; nothing was tangled.")
133 }
134 return params
135 }
136
137 /// `org-babel-effective-tangled-filename`.
138 static func fileName(path: String, language: String?, tangle: String) throws -> String? {
139 let directory = (path as NSString).deletingLastPathComponent
140 let base: String
141 switch tangle {
142 case "no", "": return nil
143 case "yes": base = (path as NSString).deletingPathExtension
144 default: base = expand(tangle, in: directory)
145 }
146 guard tangle == "yes", let language else { return base }
147 return base + "." + (extensions[language] ?? language)
148 }
149
150 /// `expand-file-name`.
151 static func expand(_ name: String, in directory: String) -> String {
152 let expanded = (name as NSString).expandingTildeInPath
153 let absolute = expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)
154 return (absolute as NSString).standardizingPath
155 }
156
157 /// `org-babel-tangle-single-block`'s body: noweb references expanded or stripped, the
158 /// language's expansion with `:var`, `:prologue` and `:epilogue`, `-r` coderefs taken
159 /// out, and indentation and surrounding blank space trimmed.
160 static func body(_ block: SrcBlockInfo, params: Babel.Params, model: DocumentModel, text: NSString,
161 links: ((SrcBlockInfo, Babel.Params) throws -> (begin: String, end: String))? = nil) throws -> String {
162 var body = Babel.normalizedBody(block)
163 let noweb = params.single[":noweb"]
164 if Babel.nowebTangles(noweb) {
165 if noweb == "strip-tangle" {
166 body = body.replacingOccurrences(of: "<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>", with: "", options: .regularExpression)
167 } else {
168 body = try Babel.expandNoweb(block, params: params, model: model, text: text, tangling: true, links: links)
169 }
170 }
171 if params.single[":no-expand"] == nil {
172 body = try expandBody(body, language: block.language ?? "", params: params, model: model, text: text)
173 }
174 // `(string-match "-r" extra)`.
175 if block.switches.joined(separator: " ").contains("-r") {
176 if block.switches.contains("-l") { throw Babel.Failure.message("-l coderef formats aren't supported yet; nothing was tangled.") }
177 body = body.components(separatedBy: "\n")
178 .map { $0.replacingOccurrences(of: "[ \\t]*\\(ref:[-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)[ \\t]*$", with: "", options: .regularExpression) }
179 .joined(separator: "\n")
180 }
181 let preserve = block.switches.contains("-i")
182 if !preserve { body = removeIndentation(body) }
183 body = body.replacingOccurrences(of: "[ \\t\\n\\r]+$", with: "", options: .regularExpression)
184 return preserve
185 ? body.replacingOccurrences(of: "^([ \\t]*\\n)+", with: "", options: .regularExpression)
186 : body.replacingOccurrences(of: "^[ \\t\\n\\r]+", with: "", options: .regularExpression)
187 }
188
189 /// `org-babel-spec-to-string`: the block's text in the file, with its `:comments`.
190 static func spec(_ block: SrcBlockInfo, body: String, params: Babel.Params, counter: Int, path: String, model: DocumentModel, tree: OrgTree, text: NSString) throws -> String {
191 let comments = params.single[":comments"] ?? "no"
192 guard comments != "no" else { return body + "\n" }
193 let language = block.language ?? ""
194 let linked = ["both", "link", "yes", "noweb"].contains(comments)
195 var out = ""
196 if comments == "org" || comments == "both" {
197 let prose = orgComment(block, model: model, text: text)
198 if prose.contains(where: { !$0.isWhitespace }) { out += try commentRegion(prose, language: language) + "\n" }
199 }
200 let link = linked ? try links(block, params: params, counter: counter, path: path, model: model, tree: tree, text: text) : nil
201 if let link { out += try commentRegion(link.begin, language: language) + "\n" }
202 out += body + "\n"
203 if let link { out += try commentRegion(link.end, language: language) + "\n" }
204 return out
205 }
206
207 /// `org-babel-tangle-comment-format-beg` and `-end` for a block: `[[LINK][NAME]]` and
208 /// `NAME ends here`, the link relative to the tangled file's folder.
209 static func links(_ block: SrcBlockInfo, params: Babel.Params, counter: Int, path: String, model: DocumentModel, tree: OrgTree, text: NSString) throws -> (begin: String, end: String) {
210 let directory = (path as NSString).deletingLastPathComponent
211 let tangle = params.single[":tangle"] ?? "no"
212 let target = tangle.contains("/") ? (expand(tangle, in: directory) as NSString).deletingLastPathComponent : directory
213 let start = beginLine(block, text: text)
214 let context = EditContext(revision: 0, text: text as String, tree: tree, selection: [start..<start])
215 let stored = Links.store(in: context, path: relativePath(path, from: target)).link
216 let name = block.name ?? ((block.heading.map { model.headings[$0].title.trimmingCharacters(in: .whitespaces) } ?? "No heading") + ":\(counter)")
217 return ("[[\(stored)][\(name)]]", "\(name) ends here")
218 }
219
220 /// `file-relative-name`.
221 static func relativePath(_ path: String, from directory: String) -> String {
222 let to = (path as NSString).standardizingPath.split(separator: "/")
223 let from = (directory as NSString).standardizingPath.split(separator: "/")
224 let common = zip(to, from).prefix { $0 == $1 }.count
225 return (Array(repeating: "..", count: from.count - common) + to.dropFirst(common).map(String.init)).joined(separator: "/")
226 }
227
228 /// The start of the block's `#+begin_src` line.
229 static func beginLine(_ block: SrcBlockInfo, text: NSString) -> Int {
230 let regex = try! NSRegularExpression(pattern: "^[ \\t]*#\\+begin_src", options: [.anchorsMatchLines, .caseInsensitive])
231 return regex.firstMatch(in: text as String, range: NSRange(block.range))?.range.location ?? block.range.lowerBound
232 }
233
234 /// The prose `:comments org` takes: from the heading's title, or the end of the block
235 /// before, to the block, without its common indentation.
236 static func orgComment(_ block: SrcBlockInfo, model: DocumentModel, text: NSString) -> String {
237 let begin = beginLine(block, text: text)
238 var start = 0
239 if let heading = block.heading {
240 let line = text.substring(with: NSRange(model.headings[heading].headingRange))
241 start = model.headings[heading].headingRange.lowerBound + (line.firstMatch(of: #/^\*+ /#).map { $0.output.utf16.count } ?? 0)
242 }
243 let end = try! NSRegularExpression(pattern: "^[ \\t]*#\\+end_src", options: [.anchorsMatchLines, .caseInsensitive])
244 for other in model.srcBlocks where other.range.lowerBound < begin {
245 if let m = end.firstMatch(in: text as String, range: NSRange(other.range)), NSMaxRange(m.range) <= begin { start = max(start, NSMaxRange(m.range)) }
246 }
247 return removeIndentation(text.substring(with: NSRange(location: start, length: max(0, begin - start))))
248 }
249
250 /// Comment syntax of the language's major mode (`org-src-get-lang-mode`), as
251 /// `comment-region` writes it.
252 static let commentSyntax: [String: (start: String, end: String)] = {
253 var table: [String: (String, String)] = [:]
254 for language in ["emacs-lisp", "elisp", "lisp", "scheme"] { table[language] = (";; ", "") }
255 for language in ["python", "ruby", "perl", "conf", "toml", "makefile", "awk", "tcl"] { table[language] = ("# ", "") }
256 for language in shells.subtracting(["fish"]) { table[language] = ("# ", "") }
257 for language in ["js", "java", "cpp", "C++"] { table[language] = ("// ", "") }
258 for language in ["c", "C", "css"] { table[language] = ("/* ", " */") }
259 for language in ["lua", "sql", "sqlite"] { table[language] = ("-- ", "") }
260 for language in ["latex"] { table[language] = ("%% ", "") }
261 return table
262 }()
263
264 /// `comment-region` over `text`: each line that isn't blank, commented.
265 static func commentRegion(_ text: String, language: String) throws -> String {
266 guard let syntax = commentSyntax[language] else {
267 throw Babel.Failure.message(":comments needs the comment syntax of \(language.isEmpty ? "the block's language" : language), which isn't known yet; nothing was tangled.")
268 }
269 return text.components(separatedBy: "\n").map { line in
270 line.contains(where: { !$0.isWhitespace }) ? syntax.start + line + syntax.end : line
271 }.joined(separator: "\n")
272 }
273
274 /// `org-remove-indentation`.
275 static func removeIndentation(_ s: String) -> String {
276 let lines = s.components(separatedBy: "\n")
277 let indents = lines.filter { $0.contains { !$0.isWhitespace } }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
278 let common = indents.min() ?? 0
279 guard common > 0 else { return s }
280 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }.joined(separator: "\n")
281 }
282
283 /// `org-babel-expand-body:LANG`, or the generic expansion with the language's variable
284 /// assignments.
285 static func expandBody(_ body: String, language: String, params: Babel.Params, model: DocumentModel, text: NSString) throws -> String {
286 let refs = Babel.References(resolved: [:], options: Babel.Options())
287 let vars = try params.vars.map { variable in
288 do {
289 return (variable.name, try Babel.resolve(variable.value, model: model, text: text, refs: refs))
290 } catch is Babel.Needed {
291 throw Babel.Failure.message(":var \(variable.value) would run a block while tangling, which isn't supported yet; nothing was tangled.")
292 }
293 }
294 let prologue = params.single[":prologue"]
295 let epilogue = params.single[":epilogue"]
296 if language == "emacs-lisp" || language == "elisp" {
297 guard !vars.isEmpty else { return body + "\n" }
298 let bindings = vars.map { "(\($0.0) '\(Babel.lispLiteral($0.1)))" }.joined(separator: "\n ")
299 return "(let (\(bindings))\n" + (prologue.map { $0 + "\n " } ?? "") + body + (epilogue.map { "\n " + $0 + "\n" } ?? "") + "\n)"
300 }
301 var lines: [String] = []
302 if shells.contains(language) {
303 lines = try vars.map { name, value in
304 switch value {
305 case .scalar(let s), .number(let s): return "\(name)='" + s.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
306 default: throw Babel.Failure.message("Tables and lists in :var aren't supported for tangling \(language) yet; nothing was tangled.")
307 }
308 }
309 } else if language == "python" {
310 lines = vars.map { "\($0.0)=\(Babel.pythonLiteral($0.1))" }
311 } else if !vars.isEmpty {
312 throw Babel.Failure.message(":var isn't supported for tangling \(language) yet; nothing was tangled.")
313 }
314 return ((prologue.map { [$0] } ?? []) + lines + [body] + (epilogue.map { [$0] } ?? [])).joined(separator: "\n")
315 }
316
317 /// `org-babel-interpret-file-mode`, for `:tangle-mode`.
318 static func fileMode(_ value: String) throws -> Int {
319 let v = value.trimmingCharacters(in: .whitespaces)
320 if let m = v.wholeMatch(of: /\(identity\s+#o([0-7]{3})\)/) ?? v.wholeMatch(of: /#o([0-7]{3})/) ?? v.wholeMatch(of: /o0?([0-7]{3})/) {
321 return Int(m.1, radix: 8)!
322 }
323 if v.wholeMatch(of: /[r-][w-][xs-][r-][w-][xs-][r-][w-][x-]/) != nil {
324 let chars = Array(v)
325 var mode = 0
326 for (i, bit) in [0o400, 0o200, 0o100, 0o40, 0o20, 0o10, 0o4, 0o2, 0o1].enumerated() where chars[i] != "-" { mode |= bit }
327 return mode
328 }
329 if v.wholeMatch(of: /[ugoa]*[+=-][rwx]*(,[ugoa]*[+=-][rwx]*)*/) != nil {
330 var mode = 0o644
331 for clause in v.split(separator: ",") {
332 let who = clause.prefix { "ugoa".contains($0) }
333 let rest = clause.dropFirst(who.count)
334 let op = rest.first!
335 let perms = rest.dropFirst()
336 var mask = 0
337 for w in (who.isEmpty ? "a" : String(who)) {
338 switch w {
339 case "u": mask |= 0o700
340 case "g": mask |= 0o070
341 case "o": mask |= 0o007
342 default: mask |= 0o777
343 }
344 }
345 var bits = 0
346 for p in perms {
347 switch p {
348 case "r": bits |= 0o444
349 case "w": bits |= 0o222
350 default: bits |= 0o111
351 }
352 }
353 switch op {
354 case "+": mode |= bits & mask
355 case "-": mode &= ~(bits & mask)
356 default: mode = (mode & ~mask) | (bits & mask)
357 }
358 }
359 return mode
360 }
361 throw Babel.Failure.message("File mode \(value) isn't one tangling understands; nothing was tangled.")
362 }
363}
364
365/// C-c C-v t (`org-babel-tangle`): the app writes the files.
366public struct TangleCommand: OrgCommand {
367 public let scope: Scope
368
369 public enum Scope: Sendable { case all, block, target }
370
371 public init(_ scope: Scope = .all) { self.scope = scope }
372
373 public var id: String {
374 switch scope {
375 case .all: "org.babel.tangle"
376 case .block: "org.babel.tangle-block"
377 case .target: "org.babel.tangle-target"
378 }
379 }
380
381 public var title: String {
382 switch scope {
383 case .all: "Tangle File"
384 case .block: "Tangle Block"
385 case .target: "Tangle Block's Target"
386 }
387 }
388
389 public func applies(in context: EditContext) -> Bool {
390 scope == .all ? !DocumentModel(tree: context.tree).srcBlocks.isEmpty : KeyContext.holds("src", in: context)
391 }
392
393 public func run(in context: EditContext) -> CommandStep {
394 switch scope {
395 case .all: .external(.tangle(.all))
396 case .block: .external(.tangle(.block(context.caret)))
397 case .target: .external(.tangle(.target(context.caret)))
398 }
399 }
400}