Sources/OrgCore/Compute/LiterateConfig.swift

23 lines · 1347 bytes

1 symbol in this file
 1import Foundation
 2
 3extension Tangle {
 4    /// The Emacs Lisp a literate configuration (`config.org`) tangles to, as
 5    /// `org-babel-load-file` and Doom's literate module do: `emacs-lisp` and `elisp` blocks,
 6    /// with `:tangle` defaulting to the target, so only `:tangle no` leaves a block out, and
 7    /// none under COMMENT or ARCHIVE headings. Other lines are blank, so that a line of the
 8    /// result is the same line of `text`.
 9    public static func literateLisp(_ text: String) -> String {
10        let ns = text as NSString
11        let model = DocumentModel(tree: OrgParser.parse(text))
12        var lines = Array(repeating: "", count: text.components(separatedBy: "\n").count)
13        for block in model.srcBlocks where ["emacs-lisp", "elisp"].contains(block.language ?? "") && !excluded(block, model: model) {
14            guard let params = try? Babel.Params(block: block, model: model, text: ns, defaults: [(":tangle", "yes")]),
15                  params.single[":tangle"] != "no" else { continue }
16            let first = ns.substring(to: block.range.lowerBound).components(separatedBy: "\n").count
17            for (i, line) in block.body.components(separatedBy: "\n").enumerated() where first + i < lines.count {
18                lines[first + i] = line
19            }
20        }
21        return lines.joined(separator: "\n")
22    }
23}