HTML export colors source blocks !227

merged merged by cmc on 2026-10-11 02:22 UTC · krz/orgstar:export-code-colors into main

7 files changed, +116 −8

Layout: unified · split

Sources/OrgCore/Export/CodeStyle.swift added +37
@@ -0,0 +1,37 @@
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}
Sources/OrgCore/Export/HTMLExport.swift +8 −3
@@ -42,7 +42,8 @@ public enum HTMLExport {
4242 /// `{{{input-file}}}`. `bodyOnly` returns what goes inside `<body>` without the title and
4343 /// byline: the table of contents, the document and its footnotes, as Org's body-only export.
4444 public static func page(
45 _ text: String, fallbackTitle: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false
45 _ text: String, fallbackTitle: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
46 codeStyle: HTMLCodeStyle? = nil
4647 ) -> String {
4748 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
4849 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
@@ -50,6 +51,7 @@ public enum HTMLExport {
5051 let meta = metadata(text, settings: settings)
5152 let title = meta.title ?? fallbackTitle
5253 let renderer = HTMLRenderer(settings: settings, options: options)
54 renderer.codeStyle = codeStyle
5355 // The title isn't part of the document Org processes citations in: they drop out.
5456 renderer.inTitle = true
5557 let titleHTML = renderer.inlineString(title)
@@ -88,7 +90,7 @@ public enum HTMLExport {
8890 .todo { color: #c33; } .done { color: #393; } .byline { color: #888; } .center { text-align: center; }
8991 figure { margin: 1em 0; } img { max-width: 100%; }
9092 #table-of-contents ul { list-style: none; padding-left: 1.2em; } #table-of-contents > div > ul { padding-left: 0; }
91 </style>
93 \(codeStyle?.css ?? "")</style>
9294 \(head)</head>
9395 <body>
9496 \(header)\(body)</body>
@@ -144,6 +146,8 @@ final class HTMLRenderer {
144146 var citations: CiteProcessor?
145147 /// Rendering the title, where Org exports citations as nothing.
146148 var inTitle = false
149 /// Colors for source blocks; plain without.
150 var codeStyle: HTMLCodeStyle?
147151
148152 enum FootnoteContent {
149153 case definition(String)
@@ -640,7 +644,8 @@ final class HTMLRenderer {
640644 switch type {
641645 case "src":
642646 let language = parameters.split(separator: " ").first.map(String.init)
643 let code = Self.escape(dedent(unescaped).joined(separator: "\n"))
647 let source = dedent(unescaped).joined(separator: "\n")
648 let code = language.flatMap { codeStyle?.html(language: $0, code: source) } ?? Self.escape(source)
644649 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
645650 return "<pre><code\(cls)>\(code)</code></pre>\n"
646651 case "example":
Sources/OrgPresentation/Presentation.swift +37
@@ -295,3 +295,40 @@ public enum Presentation {
295295 tree.root.descendants().filter { $0.kind == .heading }.map(\.range.lowerBound)
296296 }
297297}
298
299extension SyntaxCategory {
300 /// The class htmlize gives the face Emacs uses for this kind of token.
301 public var htmlClass: String? {
302 switch self {
303 case .keyword: "org-keyword"
304 case .string: "org-string"
305 case .comment: "org-comment"
306 case .function: "org-function-name"
307 case .type: "org-type"
308 case .number, .constant, .escape: "org-constant"
309 case .property, .attribute, .tag: "org-property-name"
310 case .label: "org-label"
311 case .variable: "org-variable-name"
312 case .operator, .punctuation: nil
313 }
314 }
315}
316
317extension HTMLCodeStyle {
318 /// Source blocks colored by `highlighter` in `theme`'s colors, light and dark.
319 public init(highlighter: any CodeHighlighter, theme: ThemeSpec) {
320 var light: [String] = []
321 var dark: [String] = []
322 var seen = Set<String>()
323 for category in SyntaxCategory.allCases {
324 guard let cls = category.htmlClass, let key = category.themeKey, seen.insert(cls).inserted else { continue }
325 if let color = theme.color(key, dark: false) { light.append(".\(cls) { color: \(color.hex); }") }
326 if let color = theme.color(key, dark: true) { dark.append(".\(cls) { color: \(color.hex); }") }
327 }
328 var css = light.joined(separator: " ") + "\n"
329 if !dark.isEmpty { css += "@media (prefers-color-scheme: dark) { " + dark.joined(separator: " ") + " }\n" }
330 self.init(css: css) { language, code in
331 highlighter.highlights(language: language, code: code).compactMap { run in run.category.htmlClass.map { (run.range, $0) } }
332 }
333 }
334}
Sources/Orgstar/ContentView.swift +4 −1
@@ -434,7 +434,10 @@ struct ContentView: View {
434434 let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
435435 let content = format == "markdown"
436436 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
437 : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly)
437 : HTMLExport.page(
438 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
439 codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme)
440 )
438441 do {
439442 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
440443 try content.write(to: target, atomically: true, encoding: .utf8)
Sources/OrgstarMobile/ExportMenu.swift +9 −2
@@ -2,6 +2,7 @@
22import CoreTransferable
33import OrgApp
44import OrgCore
5import OrgPresentation
56import SwiftUI
67import UniformTypeIdentifiers
78
@@ -13,6 +14,8 @@ struct OrgExport: Transferable {
1314 let path: String
1415 let format: Format
1516 let settings: OrgSettings
17 /// Made on the main actor, where the editor's highlighter is.
18 let codeStyle: HTMLCodeStyle
1619
1720 /// `#+EXPORT_FILE_NAME`'s name, or the file's, with the format's extension.
1821 var fileName: String {
@@ -35,7 +38,9 @@ struct OrgExport: Transferable {
3538 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
3639 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
3740 let content = switch format {
38 case .html: HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path)
41 case .html: HTMLExport.page(
42 text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle
43 )
3944 case .markdown: MarkdownExport.document(text, settings: settings, path: path)
4045 }
4146 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
@@ -50,11 +55,13 @@ struct OrgExport: Transferable {
5055struct ExportMenu: View {
5156 let path: String
5257 let text: String
58 @Environment(MobileModel.self) private var model
5359
5460 var body: some View {
5561 Menu("Export", systemImage: "square.and.arrow.up") {
5662 ForEach([(OrgExport.Format.html, "HTML"), (.markdown, "Markdown")], id: \.1) { format, name in
57 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings())
63 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
64 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
5865 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(name) }
5966 }
6067 }
Tests/OrgHighlightTests/HTMLCodeStyleTests.swift added +20
@@ -0,0 +1,20 @@
1import Foundation
2import OrgCore
3import OrgPresentation
4import Testing
5@testable import OrgHighlight
6
7struct HTMLCodeStyleTests {
8 @Test func sourceBlocksGetHtmlizeClassesAndThemeColors() {
9 let style = HTMLCodeStyle(highlighter: TreeSitterHighlighter(), theme: .default)
10 let text = "#+begin_src python\ndef f(x):\n return \"<a>\" # note\n#+end_src\n"
11 let page = HTMLExport.page(text, fallbackTitle: "t", codeStyle: style)
12 #expect(page.contains("<span class=\"org-keyword\">def</span>"))
13 #expect(page.contains("<span class=\"org-string\">&quot;&lt;a&gt;&quot;</span>") || page.contains("<span class=\"org-string\">\"&lt;a&gt;\"</span>"))
14 #expect(page.contains("<span class=\"org-comment\"># note</span>"))
15 #expect(page.contains(".org-keyword { color: #") && page.contains("@media (prefers-color-scheme: dark) { .org-"))
16 // Unknown languages and plain export stay as before.
17 #expect(HTMLExport.page("#+begin_src nosuchlang\na < b\n#+end_src\n", fallbackTitle: "t", codeStyle: style).contains("<code class=\"language-nosuchlang\">a &lt; b</code>"))
18 #expect(!HTMLExport.page(text, fallbackTitle: "t").contains("<span class=\"org-"))
19 }
20}
docs/manual/guide/12-export.org +1 −2
@@ -154,7 +154,7 @@ Links to =.org= files point to the =.html= file of the same name. Links to headi
154154
155155** Source blocks and their results
156156
157A source block is exported as =<pre><code class="language-LANG">=, with the code escaped and its common indentation removed. orgstar does not color the code; the class lets a script or stylesheet in =#+HTML_HEAD= highlight it. Noweb references are shown as written. Line-number switches are ignored.
157A source block is exported as =<pre><code class="language-LANG">=, with the code escaped and its common indentation removed. Code in a language the editor highlights is colored as the editor colors it: each token is a =<span>= with the class Emacs's htmlize gives its face (=org-keyword=, =org-string=, =org-comment=, =org-function-name=, =org-type=, =org-constant=, =org-property-name=, =org-variable-name=), and the page's stylesheet colors them with the theme's =syntax-= colors, light and dark. Other languages are exported plain; the =language-= class lets a script or stylesheet in =#+HTML_HEAD= highlight them. Noweb references are shown as written. Line-number switches are ignored.
158158
159159The block's =:exports= header argument decides what appears. orgstar resolves it as running the block would: from the =#+begin_src= line, =#+HEADER:= lines, =header-args= properties and =#+PROPERTY:= lines (see [[file:11-code-blocks.org][Code blocks]]). Without one, it is =results= for =dot=, =plantuml=, =ditaa=, =gnuplot=, =latex= and =lilypond= blocks, as their Org defaults set it, and =code= for other languages.
160160
@@ -305,5 +305,4 @@ The publisher part comes from the =publisher=, =journal=, =institution= or =scho
305305
306306- Subtree and body-only export are in the export dialog only; the single-format commands export the whole file. There is no asynchronous export.
307307- Source blocks are not run, and noweb references are not expanded.
308- HTML export does not color source code.
309308- Export settings in the dialog are not per file.