Commit 7624d81df5

7624d81df5f4d9060bfc1c6dc3e9d71b075e2190

parent: ebb9b1cc59

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 16:40 UTC

Export to LaTeX natively in every build, and publish to LaTeX

Layout: unified · split

Sources/OrgApp/AppStoreCommands.swift +1 −1
@@ -4,7 +4,7 @@ import Foundation
44/// Emacs, and attaching by link, which the sandbox doesn't allow.
55public enum AppStoreCommands {
66 public static let hidden: Set<String> = [
7 "app.export.pdf", "app.export.odt", "app.export.latex", "app.export.text",
7 "app.export.pdf", "app.export.odt", "app.export.text",
88 "app.attach.link", "app.attach.symlink",
99 ]
1010
Sources/OrgApp/CommandTitles.swift +1 −1
@@ -88,7 +88,7 @@ enum CommandTitles {
8888 String(localized: "Export Table to File…", comment: "Command title"),
8989 String(localized: "Export to HTML", comment: "Command title"),
9090 String(localized: "Export to HTML and Open", comment: "Command title"),
91 String(localized: "Export to LaTeX with Emacs", comment: "Command title"),
91 String(localized: "Export to LaTeX", comment: "Command title"),
9292 String(localized: "Export to Markdown", comment: "Command title"),
9393 String(localized: "Export to ODT with Emacs", comment: "Command title"),
9494 String(localized: "Export to PDF", comment: "Command title"),
Sources/OrgApp/Publish.swift +5 −5
@@ -40,7 +40,7 @@ public struct PublishProject: Sendable, Equatable {
4040
4141 public init(name: String) { self.name = name }
4242
43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-publish-attachment"]
43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-latex-publish-to-latex", "org-publish-attachment"]
4444}
4545
4646public enum Publish {
@@ -252,10 +252,10 @@ public enum Publish {
252252
253253 /// `org-publish-projects`: each project's sitemap, when it has one, then its files, through
254254 /// its publishing functions. A file whose output is newer than it is skipped unless `force`.
255 /// `export` turns an Org file's text into the HTML or Markdown to write.
255 /// `export` turns an Org file's text into the HTML, Markdown or LaTeX to write.
256256 public static func publish(
257257 _ chosen: [PublishProject], all: [PublishProject], force: Bool = false, only: String? = nil,
258 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) -> String
258 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
259259 ) throws -> Report {
260260 var report = Report()
261261 let fm = FileManager.default
@@ -290,7 +290,7 @@ public enum Publish {
290290 if directory((file as NSString).deletingLastPathComponent) == outputDirectory { return nil }
291291 return outputDirectory + (file as NSString).lastPathComponent
292292 }
293 let ext = function == "org-md-publish-to-md" ? "md" : "html"
293 let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex"][function] ?? "html"
294294 guard let text = read(file) else { throw Failure(description: "Can't read \(file)") }
295295 return ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent),
296296 name: ExportScope.fileName(text), extension: ext).path
@@ -299,7 +299,7 @@ public enum Publish {
299299 /// Copies an attachment to `output`, or writes what `function` exports from `file`.
300300 private static func write(
301301 _ file: String, to output: String, function: String, bodyOnly: Bool,
302 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) -> String
302 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
303303 ) throws {
304304 let fm = FileManager.default
305305 if function == "org-publish-attachment" {
Sources/OrgCore/Export/LaTeXExport.swift +8 −6
@@ -5,9 +5,10 @@ import Foundation
55/// can't write as Emacs would throws `Unsupported`, naming the construct, instead of writing
66/// something else. Labels are made from the document, where Emacs picks them at random.
77public enum LaTeXExport {
8 public struct Unsupported: Error, LocalizedError, Equatable {
8 public struct Unsupported: Error, LocalizedError, Equatable, CustomStringConvertible {
99 public let reason: String
1010 public var errorDescription: String? { reason }
11 public var description: String { reason }
1112 }
1213
1314 /// `org-latex-classes`: each class's header and its sectioning, numbered and not.
@@ -36,18 +37,19 @@ public enum LaTeXExport {
3637
3738 /// A `.tex` document, or with `bodyOnly` what goes between `\begin{document}` and
3839 /// `\end{document}` without the title and contents. `author` stands for `user-full-name`,
39 /// `language` for `org-export-default-language`, `now` for the `% Created` line.
40 /// `language` for `org-export-default-language`, `now` for the `% Created` line. `file` adds
41 /// the final newline `org-export-to-file` writes.
4042 public static func document(
4143 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
42 author: String = "", language: String = "en", timeZone: TimeZone = .current
44 author: String = "", language: String = "en", timeZone: TimeZone = .current, file: Bool = false
4345 ) throws -> String {
4446 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
4547 let included = ExportPreprocess.includes(text, directory: directory)
4648 // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays.
4749 let marker = "\u{E000}"
48 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") }
4950 var literal = included
5051 if included.contains("{{{") {
52 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") }
5153 let ns = included as NSString
5254 let kept = OrgParser.parse(included, defaults: settings).root.descendants()
5355 .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range)
@@ -66,8 +68,8 @@ public enum LaTeXExport {
6668 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
6769 let renderer = try LaTeXRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language)
6870 let body = try renderer.body()
69 if bodyOnly { return body }
70 return try renderer.template(body, author: author, now: now, timeZone: timeZone)
71 let output = bodyOnly ? body : try renderer.template(body, author: author, now: now, timeZone: timeZone)
72 return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
7173 }
7274}
7375
Sources/OrgEditorAppKit/EditorCommands.swift +1 −1
@@ -175,7 +175,7 @@ public enum EditorCommands {
175175 EditorCommand(id: "app.copy-rich-text", title: "Copy as Rich Text", action: .app),
176176 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app),
177177 EditorCommand(id: "app.export.odt", title: "Export to ODT with Emacs", action: .app),
178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX with Emacs", action: .app),
178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX", action: .app),
179179 EditorCommand(id: "app.export.text", title: "Export to Plain Text with Emacs", action: .app),
180180 EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app),
181181 EditorCommand(id: "app.export.icalendar-agenda", title: "Export Agenda Files to iCalendar", action: .app),
Sources/Orgstar/ContentView.swift +31
@@ -628,6 +628,8 @@ struct ContentView: View {
628628 } catch {
629629 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
630630 }
631 case "latex" where exportLaTeX(text, whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults):
632 break
631633 case "print-pdf", "docx", "rtf", "plain-text":
632634 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
633635 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
@@ -689,6 +691,32 @@ struct ContentView: View {
689691 }
690692 }
691693
694 /// Writes `text` as LaTeX, as ox-latex does. False when the native export can't match Emacs
695 /// and Emacs is installed to export instead; otherwise the reason is shown.
696 private func exportLaTeX(_ text: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings) -> Bool {
697 let content: String
698 do {
699 content = try LaTeXExport.document(text, settings: settings, path: url.path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
700 } catch {
701 #if !APPSTORE
702 if EmacsRunner.executable() != nil { return false }
703 #endif
704 commands.show("Can't export to LaTeX: \(error.localizedDescription)")
705 return true
706 }
707 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
708 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "tex")) else { return true }
709 do {
710 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
711 try content.write(to: target, atomically: true, encoding: .utf8)
712 commands.show("Exported to \(target.lastPathComponent)")
713 if open { NSWorkspace.shared.open(target) }
714 } catch {
715 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
716 }
717 return true
718 }
719
692720 /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
693721 /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
694722 private func writable(_ url: URL) -> URL? {
@@ -953,6 +981,9 @@ struct ContentView: View {
953981 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
954982 let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
955983 if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) }
984 if function == "org-latex-publish-to-latex" {
985 return try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
986 }
956987 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
957988 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
958989 }
Sources/Orgstar/ExportSheet.swift +2 −1
@@ -25,12 +25,13 @@ struct ExportSheet: View {
2525 static let formats: [(id: String, title: String, ext: String)] = [
2626 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
2727 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("icalendar", "iCalendar", "ics"),
28 ("latex", "LaTeX", "tex"),
2829 ]
2930 #else
3031 static let formats: [(id: String, title: String, ext: String)] = [
3132 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
3233 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
33 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
34 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
3435 ("icalendar", "iCalendar", "ics"),
3536 ]
3637 #endif
Sources/OrgstarMobile/ExportMenu.swift +9 −2
@@ -6,11 +6,12 @@ import OrgPresentation
66import SwiftUI
77import UniformTypeIdentifiers
88
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar, written when the
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, iCalendar or LaTeX, written when the
1010/// share sheet takes it.
1111struct OrgExport: Transferable {
1212 enum Format: CaseIterable {
1313 case html, markdown, pdf, docx, rtf, plainText, icalendar
14 case latex
1415
1516 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked.
1617 @MainActor var locked: Bool { self != .html && self != .markdown && !ProAccess.shared.isUnlocked }
@@ -24,6 +25,7 @@ struct OrgExport: Transferable {
2425 case .rtf: "Rich Text (RTF)"
2526 case .plainText: "Plain Text"
2627 case .icalendar: "iCalendar"
28 case .latex: "LaTeX"
2729 }
2830 }
2931
@@ -36,6 +38,7 @@ struct OrgExport: Transferable {
3638 case .rtf: "rtf"
3739 case .plainText: "txt"
3840 case .icalendar: "ics"
41 case .latex: "tex"
3942 }
4043 }
4144 }
@@ -72,6 +75,8 @@ struct OrgExport: Transferable {
7275 .exportingCondition { $0.format == .plainText }
7376 FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
7477 .exportingCondition { $0.format == .icalendar }
78 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
79 .exportingCondition { $0.format == .latex }
7580 }
7681
7782 private func write() async throws -> SentTransferredFile {
@@ -87,6 +92,8 @@ struct OrgExport: Transferable {
8792 .write(to: url, atomically: true, encoding: .utf8)
8893 case .markdown:
8994 try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
95 case .latex:
96 try LaTeXExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true).write(to: url, atomically: true, encoding: .utf8)
9097 case .icalendar:
9198 try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
9299 subtree: subtree, destination: url)
@@ -107,7 +114,7 @@ struct OrgExport: Transferable {
107114 }
108115}
109116
110/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar: to another app, or saved with
117/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, iCalendar or LaTeX: to another app, or saved with
111118/// Save to Files; or copying it as rich text.
112119struct ExportMenu: View {
113120 let path: String
Tests/OrgAppTests/PublishTests.swift +59
@@ -136,6 +136,65 @@ struct PublishTests {
136136 #expect(Self.listing(ourFolder) == Self.listing(emacsFolder))
137137 }
138138
139 /// `org-latex-publish-to-latex`: the same `.tex` files as Emacs writes, the `% Created`
140 /// line and the labels aside.
141 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
142 func publishesLaTeXLikeOrg() throws {
143 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-tex-\(UUID().uuidString)").resolvingSymlinksInPath()
144 defer { try? FileManager.default.removeItem(at: folder) }
145 let sources = ["a.org": "#+TITLE: A\n* One\nText with a [[https://orgmode.org][link]].\n", "sub/b.org": "#+OPTIONS: toc:nil\n- item\n- [X] done\n"]
146 for (path, text) in sources {
147 let url = folder.appendingPathComponent("src/" + path)
148 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
149 try text.write(to: url, atomically: true, encoding: .utf8)
150 }
151 let form = """
152 (progn
153 (require 'ox-publish) (require 'ox-latex)
154 (setq user-full-name "A. Writer"
155 org-publish-timestamp-directory "\(folder.path)/ts/"
156 org-publish-project-alist '(("tex" :base-directory "\(folder.path)/src" :publishing-directory "\(folder.path)/emacs"
157 :recursive t :publishing-function org-latex-publish-to-latex)))
158 (org-publish "tex" t))
159 """
160 let process = Process()
161 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
162 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
163 process.standardOutput = FileHandle.nullDevice
164 process.standardError = FileHandle.nullDevice
165 try process.run()
166 process.waitUntilExit()
167
168 let toml = """
169 [[publish]]
170 name = "tex"
171 base-directory = "\(folder.path)/src"
172 publishing-directory = "\(folder.path)/ours"
173 recursive = true
174 publishing-function = "org-latex-publish-to-latex"
175 """
176 let loaded = Publish.projects(fromConfig: toml, root: nil)
177 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
178 let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
179 let report = try Publish.publish(loaded.projects, all: loaded.projects, force: true, read: read) { _, text, path, bodyOnly in
180 try LaTeXExport.document(text, path: path, bodyOnly: bodyOnly, author: "A. Writer", file: true)
181 }
182 #expect(report.published.count == 2)
183 func normalized(_ s: String) -> String {
184 var labels: [String: String] = [:]
185 return s.replacing(#/(?m)^% Created .*\n/#, with: "").replacing(#/org[0-9a-f]{7}/#) { m in
186 let key = String(m.output)
187 if labels[key] == nil { labels[key] = "org\(labels.count + 1)" }
188 return labels[key]!
189 }
190 }
191 for path in ["a.tex", "sub/b.tex"] {
192 let theirs = try String(contentsOf: folder.appendingPathComponent("emacs/" + path), encoding: .utf8)
193 let ours = try String(contentsOf: folder.appendingPathComponent("ours/" + path), encoding: .utf8)
194 #expect(normalized(ours) == normalized(theirs), "\(path)\nours:\n\(ours)\nemacs:\n\(theirs)")
195 }
196 }
197
139198 @Test func skipsUpToDateFilesAndFindsProjects() throws {
140199 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)").resolvingSymlinksInPath()
141200 defer { try? FileManager.default.removeItem(at: folder) }
Tests/OrgEditorAppKitTests/AppStoreCommandsTests.swift +6
@@ -9,6 +9,12 @@ struct AppStoreCommandsTests {
99 #expect(AppStoreCommands.hidden.isSubset(of: ids))
1010 }
1111
12 /// LaTeX export is native, so the sandboxed build has it.
13 @Test func latexExportIsShown() {
14 #expect(!AppStoreCommands.hidden.contains("app.export.latex"))
15 #expect(EditorCommands.all.first { $0.id == "app.export.latex" }?.title == "Export to LaTeX")
16 }
17
1218 @Test func pdfKeysExportThroughWebKit() throws {
1319 let replacement = try #require(AppStoreCommands.replacement(for: "app.export.pdf"))
1420 #expect(replacement == "app.export.print-pdf")
l10n/Localizable.xcstrings +6 −6
@@ -11644,37 +11644,37 @@
1164411644 }
1164511645 }
1164611646 },
11647 "Export to LaTeX with Emacs": {
11647 "Export to LaTeX": {
1164811648 "comment": "Command title",
1164911649 "localizations": {
1165011650 "de": {
1165111651 "stringUnit": {
1165211652 "state": "translated",
11653 "value": "Mit Emacs als LaTeX exportieren"
11653 "value": "Als LaTeX exportieren"
1165411654 }
1165511655 },
1165611656 "es": {
1165711657 "stringUnit": {
1165811658 "state": "translated",
11659 "value": "Exportar a LaTeX con Emacs"
11659 "value": "Exportar a LaTeX"
1166011660 }
1166111661 },
1166211662 "fr": {
1166311663 "stringUnit": {
1166411664 "state": "translated",
11665 "value": "Exporter en LaTeX avec Emacs"
11665 "value": "Exporter en LaTeX"
1166611666 }
1166711667 },
1166811668 "ja": {
1166911669 "stringUnit": {
1167011670 "state": "translated",
11671 "value": "EmacsでLaTeXに書き出す"
11671 "value": "LaTeXに書き出す"
1167211672 }
1167311673 },
1167411674 "pt-BR": {
1167511675 "stringUnit": {
1167611676 "state": "translated",
11677 "value": "Exportar para LaTeX com o Emacs"
11677 "value": "Exportar para LaTeX"
1167811678 }
1167911679 }
1168011680 }