Sources/OrgCore/Export/CodeStyle.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Sources/OrgCore/Export/CodeStyle.swift history · blame · raw

37 lines · 1734 bytes

 1import Foundation
 2
 3/// Colored source code for HTML export, as `org-html-htmlize-output-type` `css` writes it:
 4/// spans with `org-…` classes, and the stylesheet that colors them. The apps make one from
 5/// their tree-sitter highlighter and theme; without one, code is exported plain.
 6public struct HTMLCodeStyle: Sendable {
 7    /// Classes for ranges of `code` (UTF-16 offsets) in a language; later ranges win.
 8    public let classes: @Sendable (_ language: String, _ code: String) -> [(range: Range<Int>, cls: String)]
 9    /// CSS rules for the classes, added to the page's stylesheet.
10    public let css: String
11
12    public init(css: String, classes: @escaping @Sendable (_ language: String, _ code: String) -> [(range: Range<Int>, cls: String)]) {
13        self.classes = classes
14        self.css = css
15    }
16
17    /// `code` escaped, with the spans; nil when the language has no colors.
18    func html(language: String, code: String) -> String? {
19        let runs = classes(language, code)
20        guard !runs.isEmpty else { return nil }
21        let units = Array(code.utf16)
22        var at = [String?](repeating: nil, count: units.count)
23        for run in runs {
24            for i in max(0, run.range.lowerBound)..<min(units.count, run.range.upperBound) { at[i] = run.cls }
25        }
26        var out = ""
27        var start = 0
28        while start < units.count {
29            var end = start + 1
30            while end < units.count, at[end] == at[start] { end += 1 }
31            let piece = HTMLRenderer.escape(String(utf16CodeUnits: Array(units[start..<end]), count: end - start))
32            out += at[start].map { "<span class=\"\($0)\">\(piece)</span>" } ?? piece
33            start = end
34        }
35        return out
36    }
37}