Sources/OrgCore/Compute/Tangle.swift
296 lines · 14564 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`, and `:var` for shells, Python and Emacs Lisp. Comments
6// (`:comments`) and header values Org would evaluate as Lisp aren't supported.
7
8public enum Tangle {
9 /// All blocks (C-c C-v t), the block at an offset (C-u C-c C-v t), or the blocks going to
10 /// the same file as the block at an offset (C-u C-u C-c C-v t).
11 public enum Scope: Sendable, Equatable {
12 case all
13 case block(Int)
14 case target(Int)
15 }
16
17 public struct File: Sendable, Equatable {
18 /// Absolute.
19 public var path: String
20 public var contents: String
21 /// From `:tangle-mode`, or 0o755 for a file with a `:shebang`; nil leaves the mode alone.
22 public var mode: Int?
23 /// `:mkdirp`: the file's directory is made if missing.
24 public var makeDirectories: Bool
25 }
26
27 public struct Output: Sendable, Equatable {
28 public var files: [File]
29 /// Blocks written, for "Tangled N code blocks".
30 public var blocks: Int
31 }
32
33 /// `org-babel-tangle-lang-exts`.
34 static let extensions = ["emacs-lisp": "el", "elisp": "el", "bibtex": "bib"]
35 /// `org-babel-shell-names`, and `shell` itself.
36 static let shells: Set<String> = ["sh", "bash", "zsh", "fish", "csh", "ash", "dash", "ksh", "mksh", "posh", "shell"]
37
38 /// The files tangling `text`, the contents of the Org file at `path`, writes.
39 public static func run(text: String, path: String, scope: Scope = .all, tree: OrgTree? = nil) -> Result<Output, Babel.Failure> {
40 let ns = text as NSString
41 let model = DocumentModel(tree: tree ?? OrgParser.parse(text))
42 do {
43 var order: [String] = []
44 var specs: [String: [(language: String?, body: String, params: Babel.Params)]] = [:]
45 func add(_ block: SrcBlockInfo, _ params: Babel.Params) throws {
46 guard let file = try fileName(path: path, language: block.language, tangle: params.single[":tangle"] ?? "no") else { return }
47 let body = try body(block, params: params, model: model, text: ns)
48 if specs[file] == nil { order.append(file) }
49 specs[file, default: []].append((block.language, body, params))
50 }
51 switch scope {
52 case .block(let offset):
53 guard let block = block(at: offset, in: model) else { throw Babel.Failure.message("Point is not in a source code block") }
54 try add(block, try params(block, model: model, text: ns))
55 case .all, .target:
56 var target: String?
57 if case .target(let offset) = scope {
58 guard let block = block(at: offset, in: model) else { throw Babel.Failure.message("Point is not in a source code block") }
59 target = try params(block, model: model, text: ns).single[":tangle"] ?? "no"
60 }
61 for block in model.srcBlocks where !excluded(block, model: model) {
62 let params = try params(block, model: model, text: ns)
63 let tangle = params.single[":tangle"] ?? "no"
64 if tangle == "no" || (block.language == nil && tangle == "yes") { continue }
65 if let target, target != tangle { continue }
66 try add(block, params)
67 }
68 }
69 var files: [File] = []
70 var blocks = 0
71 for file in order {
72 var contents = ""
73 var mode: Int?
74 var makeDirectories = false
75 var sheBanged = false
76 for spec in specs[file]! {
77 let shebang = spec.params.single[":shebang"].flatMap { $0.isEmpty ? nil : $0 }
78 var tangleMode = try spec.params.single[":tangle-mode"].map(fileMode)
79 if shebang != nil, tangleMode == nil { tangleMode = 0o755 }
80 // `add-to-list` then `mapc`: the first mode given is the one left.
81 if mode == nil { mode = tangleMode }
82 if let mkdirp = spec.params.single[":mkdirp"], mkdirp != "no" { makeDirectories = true }
83 if spec.params.single[":padline"] != "no", !contents.isEmpty { contents += "\n" }
84 if let shebang, !sheBanged {
85 contents += shebang + "\n"
86 sheBanged = true
87 }
88 contents += spec.body + "\n"
89 blocks += 1
90 }
91 files.append(File(path: file, contents: contents, mode: mode, makeDirectories: makeDirectories))
92 }
93 return .success(Output(files: files, blocks: blocks))
94 } catch let error as Babel.Failure {
95 return .failure(error)
96 } catch {
97 return .failure(.message("\(error)"))
98 }
99 }
100
101 /// `org-babel-where-is-src-block-head`.
102 static func block(at offset: Int, in model: DocumentModel) -> SrcBlockInfo? {
103 model.srcBlocks.first { $0.range.contains(offset) || $0.range.upperBound == offset }
104 }
105
106 /// `org-in-commented-heading-p` and `org-in-archived-heading-p`.
107 static func excluded(_ block: SrcBlockInfo, model: DocumentModel) -> Bool {
108 guard let heading = block.heading else { return false }
109 return ([heading] + model.ancestors(of: heading)).contains { index in
110 let h = model.headings[index]
111 return AgendaSource.isCommented(h.title) || h.localTags.contains("ARCHIVE")
112 }
113 }
114
115 static func params(_ block: SrcBlockInfo, model: DocumentModel, text: NSString) throws -> Babel.Params {
116 let params = try Babel.Params(block: block, model: model, text: text)
117 for (key, value) in params.single where value.hasPrefix("(") && key != ":tangle-mode" {
118 throw Babel.Failure.message("\(key) \(value) is Lisp to evaluate, which tangling doesn't support yet; nothing was tangled.")
119 }
120 if let comments = params.single[":comments"], comments != "no" {
121 throw Babel.Failure.message(":comments \(comments) isn't supported yet; nothing was tangled.")
122 }
123 return params
124 }
125
126 /// `org-babel-effective-tangled-filename`.
127 static func fileName(path: String, language: String?, tangle: String) throws -> String? {
128 let directory = (path as NSString).deletingLastPathComponent
129 let base: String
130 switch tangle {
131 case "no", "": return nil
132 case "yes": base = (path as NSString).deletingPathExtension
133 default: base = expand(tangle, in: directory)
134 }
135 guard tangle == "yes", let language else { return base }
136 return base + "." + (extensions[language] ?? language)
137 }
138
139 /// `expand-file-name`.
140 static func expand(_ name: String, in directory: String) -> String {
141 let expanded = (name as NSString).expandingTildeInPath
142 let absolute = expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)
143 return (absolute as NSString).standardizingPath
144 }
145
146 /// `org-babel-tangle-single-block`'s body: noweb references expanded or stripped, the
147 /// language's expansion with `:var`, `:prologue` and `:epilogue`, `-r` coderefs taken
148 /// out, and indentation and surrounding blank space trimmed.
149 static func body(_ block: SrcBlockInfo, params: Babel.Params, model: DocumentModel, text: NSString) throws -> String {
150 var body = Babel.normalizedBody(block)
151 let noweb = params.single[":noweb"]
152 if Babel.nowebTangles(noweb) {
153 if noweb == "strip-tangle" {
154 body = body.replacingOccurrences(of: "<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>", with: "", options: .regularExpression)
155 } else {
156 body = try Babel.expandNoweb(block, params: params, model: model, text: text, tangling: true)
157 }
158 }
159 if params.single[":no-expand"] == nil {
160 body = try expandBody(body, language: block.language ?? "", params: params, model: model, text: text)
161 }
162 // `(string-match "-r" extra)`.
163 if block.switches.joined(separator: " ").contains("-r") {
164 if block.switches.contains("-l") { throw Babel.Failure.message("-l coderef formats aren't supported yet; nothing was tangled.") }
165 body = body.components(separatedBy: "\n")
166 .map { $0.replacingOccurrences(of: "[ \\t]*\\(ref:[-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)[ \\t]*$", with: "", options: .regularExpression) }
167 .joined(separator: "\n")
168 }
169 let preserve = block.switches.contains("-i")
170 if !preserve { body = removeIndentation(body) }
171 body = body.replacingOccurrences(of: "[ \\t\\n\\r]+$", with: "", options: .regularExpression)
172 return preserve
173 ? body.replacingOccurrences(of: "^([ \\t]*\\n)+", with: "", options: .regularExpression)
174 : body.replacingOccurrences(of: "^[ \\t\\n\\r]+", with: "", options: .regularExpression)
175 }
176
177 /// `org-remove-indentation`.
178 static func removeIndentation(_ s: String) -> String {
179 let lines = s.components(separatedBy: "\n")
180 let indents = lines.filter { $0.contains { !$0.isWhitespace } }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
181 let common = indents.min() ?? 0
182 guard common > 0 else { return s }
183 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }.joined(separator: "\n")
184 }
185
186 /// `org-babel-expand-body:LANG`, or the generic expansion with the language's variable
187 /// assignments.
188 static func expandBody(_ body: String, language: String, params: Babel.Params, model: DocumentModel, text: NSString) throws -> String {
189 let vars = try params.vars.map { ($0.name, try Babel.resolve($0.value, model: model, text: text)) }
190 let prologue = params.single[":prologue"]
191 let epilogue = params.single[":epilogue"]
192 if language == "emacs-lisp" || language == "elisp" {
193 guard !vars.isEmpty else { return body + "\n" }
194 let bindings = vars.map { "(\($0.0) '\(Babel.lispLiteral($0.1)))" }.joined(separator: "\n ")
195 return "(let (\(bindings))\n" + (prologue.map { $0 + "\n " } ?? "") + body + (epilogue.map { "\n " + $0 + "\n" } ?? "") + "\n)"
196 }
197 var lines: [String] = []
198 if shells.contains(language) {
199 lines = try vars.map { name, value in
200 switch value {
201 case .scalar(let s), .number(let s): return "\(name)='" + s.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
202 default: throw Babel.Failure.message("Tables and lists in :var aren't supported for tangling \(language) yet; nothing was tangled.")
203 }
204 }
205 } else if language == "python" {
206 lines = vars.map { "\($0.0)=\(Babel.pythonLiteral($0.1))" }
207 } else if !vars.isEmpty {
208 throw Babel.Failure.message(":var isn't supported for tangling \(language) yet; nothing was tangled.")
209 }
210 return ((prologue.map { [$0] } ?? []) + lines + [body] + (epilogue.map { [$0] } ?? [])).joined(separator: "\n")
211 }
212
213 /// `org-babel-interpret-file-mode`, for `:tangle-mode`.
214 static func fileMode(_ value: String) throws -> Int {
215 let v = value.trimmingCharacters(in: .whitespaces)
216 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})/) {
217 return Int(m.1, radix: 8)!
218 }
219 if v.wholeMatch(of: /[r-][w-][xs-][r-][w-][xs-][r-][w-][x-]/) != nil {
220 let chars = Array(v)
221 var mode = 0
222 for (i, bit) in [0o400, 0o200, 0o100, 0o40, 0o20, 0o10, 0o4, 0o2, 0o1].enumerated() where chars[i] != "-" { mode |= bit }
223 return mode
224 }
225 if v.wholeMatch(of: /[ugoa]*[+=-][rwx]*(,[ugoa]*[+=-][rwx]*)*/) != nil {
226 var mode = 0o644
227 for clause in v.split(separator: ",") {
228 let who = clause.prefix { "ugoa".contains($0) }
229 let rest = clause.dropFirst(who.count)
230 let op = rest.first!
231 let perms = rest.dropFirst()
232 var mask = 0
233 for w in (who.isEmpty ? "a" : String(who)) {
234 switch w {
235 case "u": mask |= 0o700
236 case "g": mask |= 0o070
237 case "o": mask |= 0o007
238 default: mask |= 0o777
239 }
240 }
241 var bits = 0
242 for p in perms {
243 switch p {
244 case "r": bits |= 0o444
245 case "w": bits |= 0o222
246 default: bits |= 0o111
247 }
248 }
249 switch op {
250 case "+": mode |= bits & mask
251 case "-": mode &= ~(bits & mask)
252 default: mode = (mode & ~mask) | (bits & mask)
253 }
254 }
255 return mode
256 }
257 throw Babel.Failure.message("File mode \(value) isn't one tangling understands; nothing was tangled.")
258 }
259}
260
261/// C-c C-v t (`org-babel-tangle`): the app writes the files.
262public struct TangleCommand: OrgCommand {
263 public let scope: Scope
264
265 public enum Scope: Sendable { case all, block, target }
266
267 public init(_ scope: Scope = .all) { self.scope = scope }
268
269 public var id: String {
270 switch scope {
271 case .all: "org.babel.tangle"
272 case .block: "org.babel.tangle-block"
273 case .target: "org.babel.tangle-target"
274 }
275 }
276
277 public var title: String {
278 switch scope {
279 case .all: "Tangle File"
280 case .block: "Tangle Block"
281 case .target: "Tangle Block's Target"
282 }
283 }
284
285 public func applies(in context: EditContext) -> Bool {
286 scope == .all ? !DocumentModel(tree: context.tree).srcBlocks.isEmpty : KeyContext.holds("src", in: context)
287 }
288
289 public func run(in context: EditContext) -> CommandStep {
290 switch scope {
291 case .all: .external(.tangle(.all))
292 case .block: .external(.tangle(.block(context.caret)))
293 case .target: .external(.tangle(.target(context.caret)))
294 }
295 }
296}