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 {
42 /// `{{{input-file}}}`. `bodyOnly` returns what goes inside `<body>` without the title and 42 /// `{{{input-file}}}`. `bodyOnly` returns what goes inside `<body>` without the title and
43 /// byline: the table of contents, the document and its footnotes, as Org's body-only export. 43 /// byline: the table of contents, the document and its footnotes, as Org's body-only export.
44 public static func page( 44 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
46 ) -> String { 47 ) -> String {
47 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() } 48 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
48 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords) 49 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
@@ -50,6 +51,7 @@ public enum HTMLExport {
50 let meta = metadata(text, settings: settings) 51 let meta = metadata(text, settings: settings)
51 let title = meta.title ?? fallbackTitle 52 let title = meta.title ?? fallbackTitle
52 let renderer = HTMLRenderer(settings: settings, options: options) 53 let renderer = HTMLRenderer(settings: settings, options: options)
54 renderer.codeStyle = codeStyle
53 // The title isn't part of the document Org processes citations in: they drop out. 55 // The title isn't part of the document Org processes citations in: they drop out.
54 renderer.inTitle = true 56 renderer.inTitle = true
55 let titleHTML = renderer.inlineString(title) 57 let titleHTML = renderer.inlineString(title)
@@ -88,7 +90,7 @@ public enum HTMLExport {
88 .todo { color: #c33; } .done { color: #393; } .byline { color: #888; } .center { text-align: center; } 90 .todo { color: #c33; } .done { color: #393; } .byline { color: #888; } .center { text-align: center; }
89 figure { margin: 1em 0; } img { max-width: 100%; } 91 figure { margin: 1em 0; } img { max-width: 100%; }
90 #table-of-contents ul { list-style: none; padding-left: 1.2em; } #table-of-contents > div > ul { padding-left: 0; } 92 #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>
92 \(head)</head> 94 \(head)</head>
93 <body> 95 <body>
94 \(header)\(body)</body> 96 \(header)\(body)</body>
@@ -144,6 +146,8 @@ final class HTMLRenderer {
144 var citations: CiteProcessor? 146 var citations: CiteProcessor?
145 /// Rendering the title, where Org exports citations as nothing. 147 /// Rendering the title, where Org exports citations as nothing.
146 var inTitle = false 148 var inTitle = false
149 /// Colors for source blocks; plain without.
150 var codeStyle: HTMLCodeStyle?
147 151
148 enum FootnoteContent { 152 enum FootnoteContent {
149 case definition(String) 153 case definition(String)
@@ -640,7 +644,8 @@ final class HTMLRenderer {
640 switch type { 644 switch type {
641 case "src": 645 case "src":
642 let language = parameters.split(separator: " ").first.map(String.init) 646 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)
644 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? "" 649 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
645 return "<pre><code\(cls)>\(code)</code></pre>\n" 650 return "<pre><code\(cls)>\(code)</code></pre>\n"
646 case "example": 651 case "example":
Sources/OrgPresentation/Presentation.swift +37
@@ -295,3 +295,40 @@ public enum Presentation {
295 tree.root.descendants().filter { $0.kind == .heading }.map(\.range.lowerBound) 295 tree.root.descendants().filter { $0.kind == .heading }.map(\.range.lowerBound)
296 } 296 }
297} 297}
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 {
434 let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html") 434 let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
435 let content = format == "markdown" 435 let content = format == "markdown"
436 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly) 436 ? 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 )
438 do { 441 do {
439 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) 442 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
440 try content.write(to: target, atomically: true, encoding: .utf8) 443 try content.write(to: target, atomically: true, encoding: .utf8)
Sources/OrgstarMobile/ExportMenu.swift +9 −2
@@ -2,6 +2,7 @@
2import CoreTransferable 2import CoreTransferable
3import OrgApp 3import OrgApp
4import OrgCore 4import OrgCore
5import OrgPresentation
5import SwiftUI 6import SwiftUI
6import UniformTypeIdentifiers 7import UniformTypeIdentifiers
7 8
@@ -13,6 +14,8 @@ struct OrgExport: Transferable {
13 let path: String 14 let path: String
14 let format: Format 15 let format: Format
15 let settings: OrgSettings 16 let settings: OrgSettings
17 /// Made on the main actor, where the editor's highlighter is.
18 let codeStyle: HTMLCodeStyle
16 19
17 /// `#+EXPORT_FILE_NAME`'s name, or the file's, with the format's extension. 20 /// `#+EXPORT_FILE_NAME`'s name, or the file's, with the format's extension.
18 var fileName: String { 21 var fileName: String {
@@ -35,7 +38,9 @@ struct OrgExport: Transferable {
35 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension 38 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
36 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile) 39 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
37 let content = switch format { 40 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 )
39 case .markdown: MarkdownExport.document(text, settings: settings, path: path) 44 case .markdown: MarkdownExport.document(text, settings: settings, path: path)
40 } 45 }
41 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) 46 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
@@ -50,11 +55,13 @@ struct OrgExport: Transferable {
50struct ExportMenu: View { 55struct ExportMenu: View {
51 let path: String 56 let path: String
52 let text: String 57 let text: String
58 @Environment(MobileModel.self) private var model
53 59
54 var body: some View { 60 var body: some View {
55 Menu("Export", systemImage: "square.and.arrow.up") { 61 Menu("Export", systemImage: "square.and.arrow.up") {
56 ForEach([(OrgExport.Format.html, "HTML"), (.markdown, "Markdown")], id: \.1) { format, name in 62 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))
58 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(name) } 65 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(name) }
59 } 66 }
60 } 67 }
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
154 154
155** Source blocks and their results 155** Source blocks and their results
156 156
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.
158 158
159The 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. 159The 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.
160 160
@@ -305,5 +305,4 @@ The publisher part comes from the =publisher=, =journal=, =institution= or =scho
305 305
306- Subtree and body-only export are in the export dialog only; the single-format commands export the whole file. There is no asynchronous export. 306- Subtree and body-only export are in the export dialog only; the single-format commands export the whole file. There is no asynchronous export.
307- Source blocks are not run, and noweb references are not expanded. 307- Source blocks are not run, and noweb references are not expanded.
308- HTML export does not color source code.
309- Export settings in the dialog are not per file. 308- Export settings in the dialog are not per file.