Commit cf8b291899

cf8b29189934091d7dd0144ced479cc21c4ec764

parent: b28cc71ca3

Verified · cmc

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

Export and publish ASCII natively in every build

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.text",
7 "app.export.pdf",
88 "app.attach.link", "app.attach.symlink",
99 ]
1010
Sources/OrgApp/CommandTitles.swift +1 −1
@@ -94,7 +94,7 @@ enum CommandTitles {
9494 String(localized: "Export to PDF", comment: "Command title"),
9595 String(localized: "Export to PDF with Emacs", comment: "Command title"),
9696 String(localized: "Export to Plain Text", comment: "Command title"),
97 String(localized: "Export to Plain Text with Emacs", comment: "Command title"),
97 String(localized: "Export to Plain Text (ASCII)", comment: "Command title"),
9898 String(localized: "Export to RTF", comment: "Command title"),
9999 String(localized: "Export to Word", comment: "Command title"),
100100 String(localized: "Export to iCalendar", comment: "Command title"),
Sources/OrgApp/Publish.swift +3 −3
@@ -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-latex-publish-to-latex", "org-odt-publish-to-odt", "org-publish-attachment"]
43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-latex-publish-to-latex", "org-odt-publish-to-odt", "org-ascii-publish-to-ascii", "org-publish-attachment"]
4444}
4545
4646public enum Publish {
@@ -252,7 +252,7 @@ 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, Markdown or LaTeX to write.
255 /// `export` turns an Org file's text into the HTML, Markdown, LaTeX or plain text to write.
256256 public static func publish(
257257 _ chosen: [PublishProject], all: [PublishProject], force: Bool = false, only: String? = nil,
258258 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
@@ -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 = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex", "org-odt-publish-to-odt": "odt"][function] ?? "html"
293 let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex", "org-odt-publish-to-odt": "odt", "org-ascii-publish-to-ascii": "txt"][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
Sources/OrgCore/Export/ASCIIExport.swift +5 −3
@@ -15,10 +15,11 @@ public enum ASCIIExport {
1515 }
1616
1717 /// A `.txt` document, or with `bodyOnly` the text without the title block and contents.
18 /// `author` stands for `user-full-name`, `language` for `org-export-default-language`.
18 /// `author` stands for `user-full-name`, `language` for `org-export-default-language`. `file`
19 /// adds the final newline `org-export-to-file` writes.
1920 public static func document(
2021 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), charset: Charset = .ascii,
21 bodyOnly: Bool = false, author: String = "", language: String = "en"
22 bodyOnly: Bool = false, author: String = "", language: String = "en", file: Bool = false
2223 ) throws -> String {
2324 let text = try LaTeXExport.expanded(text, settings: settings, path: path, now: now)
2425 let tree = OrgParser.parse(text, defaults: settings)
@@ -27,7 +28,8 @@ public enum ASCIIExport {
2728 let renderer = try ASCIIRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language, charset: charset)
2829 var output = try renderer.body()
2930 if !bodyOnly { output = try renderer.template(output, author: author) }
30 return output.replacingOccurrences(of: ASCIIRenderer.hardNewline, with: "\n")
31 output = output.replacingOccurrences(of: ASCIIRenderer.hardNewline, with: "\n")
32 return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
3133 }
3234}
3335
Sources/OrgEditorAppKit/EditorCommands.swift +1 −1
@@ -176,7 +176,7 @@ public enum EditorCommands {
176176 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app),
177177 EditorCommand(id: "app.export.odt", title: "Export to ODT", action: .app),
178178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX", action: .app),
179 EditorCommand(id: "app.export.text", title: "Export to Plain Text with Emacs", action: .app),
179 EditorCommand(id: "app.export.text", title: "Export to Plain Text (ASCII)", 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),
182182 EditorCommand(id: "app.export.icalendar-combined", title: "Combine Agenda Files into iCalendar", action: .app),
Sources/Orgstar/ContentView.swift +23 −7
@@ -628,7 +628,13 @@ 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):
631 case "latex" where exportNative("LaTeX", extension: "tex", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, settings: defaults, export: {
632 try LaTeXExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
633 }):
634 break
635 case "text" where exportNative("plain text", extension: "txt", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, settings: defaults, export: {
636 try ASCIIExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
637 }):
632638 break
633639 case "odt":
634640 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
@@ -705,21 +711,24 @@ struct ContentView: View {
705711 }
706712 }
707713
708 /// Writes `text` as LaTeX, as ox-latex does. False when the native export can't match Emacs
709 /// and Emacs is installed to export instead; otherwise the reason is shown.
710 private func exportLaTeX(_ text: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings) -> Bool {
714 /// Writes what `export` makes, as ox does for `format`. False when the native export can't
715 /// match Emacs and Emacs is installed to export instead; otherwise the reason is shown.
716 private func exportNative(
717 _ format: String, extension ext: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, settings: OrgSettings,
718 export: () throws -> String
719 ) -> Bool {
711720 let content: String
712721 do {
713 content = try LaTeXExport.document(text, settings: settings, path: url.path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
722 content = try export()
714723 } catch {
715724 #if !APPSTORE
716725 if EmacsRunner.executable() != nil { return false }
717726 #endif
718 commands.show("Can't export to LaTeX: \(error.localizedDescription)")
727 commands.show("Can't export to \(format): \(error.localizedDescription)")
719728 return true
720729 }
721730 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
722 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "tex")) else { return true }
731 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return true }
723732 do {
724733 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
725734 try content.write(to: target, atomically: true, encoding: .utf8)
@@ -1002,6 +1011,13 @@ struct ContentView: View {
10021011 throw LaTeXExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to LaTeX: \(error.reason)")
10031012 }
10041013 }
1014 if function == "org-ascii-publish-to-ascii" {
1015 do {
1016 return try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
1017 } catch let error as ASCIIExport.Unsupported {
1018 throw ASCIIExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to plain text: \(error.reason)")
1019 }
1020 }
10051021 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
10061022 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
10071023 }
Sources/Orgstar/ExportSheet.swift +2 −2
@@ -25,13 +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"), ("odt", "ODT", "odt"),
28 ("icalendar", "iCalendar", "ics"), ("latex", "LaTeX", "tex"),
28 ("icalendar", "iCalendar", "ics"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII", "txt"),
2929 ]
3030 #else
3131 static let formats: [(id: String, title: String, ext: String)] = [
3232 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
3333 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
34 ("odt", "ODT", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
34 ("odt", "ODT", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII", "txt"),
3535 ("icalendar", "iCalendar", "ics"),
3636 ]
3737 #endif
Sources/OrgstarMobile/ExportMenu.swift +20 −6
@@ -6,12 +6,12 @@ import OrgPresentation
66import SwiftUI
77import UniformTypeIdentifiers
88
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar or LaTeX, written
10/// when the share sheet takes it.
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII,
10/// written when the share sheet takes it.
1111struct OrgExport: Transferable {
1212 enum Format: CaseIterable {
1313 case html, markdown, pdf, docx, rtf, plainText, odt, icalendar
14 case latex
14 case latex, ascii
1515
1616 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked.
1717 @MainActor var locked: Bool { self != .html && self != .markdown && !ProAccess.shared.isUnlocked }
@@ -27,6 +27,7 @@ struct OrgExport: Transferable {
2727 case .odt: "ODT"
2828 case .icalendar: "iCalendar"
2929 case .latex: "LaTeX"
30 case .ascii: "Plain Text (ASCII)"
3031 }
3132 }
3233
@@ -41,6 +42,7 @@ struct OrgExport: Transferable {
4142 case .odt: "odt"
4243 case .icalendar: "ics"
4344 case .latex: "tex"
45 case .ascii: "txt"
4446 }
4547 }
4648 }
@@ -62,8 +64,8 @@ struct OrgExport: Transferable {
6264 .lastPathComponent
6365 }
6466
65 /// Posted with the message, for the screen's message line, when the LaTeX export refuses
66 /// the file: the share sheet shows no reason.
67 /// Posted with the message, for the screen's message line, when the LaTeX or ASCII export
68 /// refuses the file: the share sheet shows no reason.
6769 static let refused = Notification.Name("OrgExportRefused")
6870
6971 static var transferRepresentation: some TransferRepresentation {
@@ -85,6 +87,8 @@ struct OrgExport: Transferable {
8587 .exportingCondition { $0.format == .icalendar }
8688 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
8789 .exportingCondition { $0.format == .latex }
90 FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
91 .exportingCondition { $0.format == .ascii }
8892 }
8993
9094 private func write() async throws -> SentTransferredFile {
@@ -110,6 +114,16 @@ struct OrgExport: Transferable {
110114 throw error
111115 }
112116 try content.write(to: url, atomically: true, encoding: .utf8)
117 case .ascii:
118 let content: String
119 do {
120 content = try ASCIIExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true)
121 } catch let error as ASCIIExport.Unsupported {
122 let message = "Can't export to plain text: \(error.reason)"
123 await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
124 throw error
125 }
126 try content.write(to: url, atomically: true, encoding: .utf8)
113127 case .odt:
114128 try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage())
115129 .write(to: url, options: .atomic)
@@ -133,7 +147,7 @@ struct OrgExport: Transferable {
133147 }
134148}
135149
136/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar or LaTeX: to another app, or saved with
150/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII: to another app, or saved with
137151/// Save to Files; or copying it as rich text.
138152struct ExportMenu: View {
139153 let path: String
Tests/OrgAppTests/PublishTests.swift +50
@@ -195,6 +195,56 @@ struct PublishTests {
195195 }
196196 }
197197
198 /// `org-ascii-publish-to-ascii`: the same `.txt` files as Emacs writes.
199 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
200 func publishesASCIILikeOrg() throws {
201 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-txt-\(UUID().uuidString)").resolvingSymlinksInPath()
202 defer { try? FileManager.default.removeItem(at: folder) }
203 let sources = ["a.org": "#+TITLE: A\n* One\nText with a [[https://orgmode.org][link]].\n| x | y |\n", "sub/b.org": "#+OPTIONS: toc:nil\n- item\n- [X] done\n"]
204 for (path, text) in sources {
205 let url = folder.appendingPathComponent("src/" + path)
206 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
207 try text.write(to: url, atomically: true, encoding: .utf8)
208 }
209 let form = """
210 (progn
211 (require 'ox-publish) (require 'ox-ascii)
212 (setq user-full-name "A. Writer"
213 org-publish-timestamp-directory "\(folder.path)/ts/"
214 org-publish-project-alist '(("txt" :base-directory "\(folder.path)/src" :publishing-directory "\(folder.path)/emacs"
215 :recursive t :publishing-function org-ascii-publish-to-ascii)))
216 (org-publish "txt" t))
217 """
218 let process = Process()
219 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
220 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
221 process.standardOutput = FileHandle.nullDevice
222 process.standardError = FileHandle.nullDevice
223 try process.run()
224 process.waitUntilExit()
225
226 let toml = """
227 [[publish]]
228 name = "txt"
229 base-directory = "\(folder.path)/src"
230 publishing-directory = "\(folder.path)/ours"
231 recursive = true
232 publishing-function = "org-ascii-publish-to-ascii"
233 """
234 let loaded = Publish.projects(fromConfig: toml, root: nil)
235 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
236 let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
237 let report = try Publish.publish(loaded.projects, all: loaded.projects, force: true, read: read) { _, text, path, bodyOnly in
238 try ASCIIExport.document(text, path: path, bodyOnly: bodyOnly, author: "A. Writer", file: true)
239 }
240 #expect(report.published.count == 2)
241 for path in ["a.txt", "sub/b.txt"] {
242 let theirs = try String(contentsOf: folder.appendingPathComponent("emacs/" + path), encoding: .utf8)
243 let ours = try String(contentsOf: folder.appendingPathComponent("ours/" + path), encoding: .utf8)
244 #expect(ours == theirs, "\(path)\nours:\n\(ours)\nemacs:\n\(theirs)")
245 }
246 }
247
198248 /// `org-odt-publish-to-odt` writes `.odt` files, which the export closure doesn't see.
199249 @Test func publishesODT() throws {
200250 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)")
Tests/OrgEditorAppKitTests/AppStoreCommandsTests.swift +6
@@ -15,6 +15,12 @@ struct AppStoreCommandsTests {
1515 #expect(EditorCommands.all.first { $0.id == "app.export.latex" }?.title == "Export to LaTeX")
1616 }
1717
18 /// ASCII export is native, so the sandboxed build has it.
19 @Test func asciiExportIsShown() {
20 #expect(!AppStoreCommands.hidden.contains("app.export.text"))
21 #expect(EditorCommands.all.first { $0.id == "app.export.text" }?.title == "Export to Plain Text (ASCII)")
22 }
23
1824 @Test func pdfKeysExportThroughWebKit() throws {
1925 let replacement = try #require(AppStoreCommands.replacement(for: "app.export.pdf"))
2026 #expect(replacement == "app.export.print-pdf")
l10n/Localizable.xcstrings +6 −6
@@ -11854,37 +11854,37 @@
1185411854 }
1185511855 }
1185611856 },
11857 "Export to Plain Text with Emacs": {
11857 "Export to Plain Text (ASCII)": {
1185811858 "comment": "Command title",
1185911859 "localizations": {
1186011860 "de": {
1186111861 "stringUnit": {
1186211862 "state": "translated",
11863 "value": "Mit Emacs als reinen Text exportieren"
11863 "value": "Als reinen Text (ASCII) exportieren"
1186411864 }
1186511865 },
1186611866 "es": {
1186711867 "stringUnit": {
1186811868 "state": "translated",
11869 "value": "Exportar a texto sin formato con Emacs"
11869 "value": "Exportar a texto sin formato (ASCII)"
1187011870 }
1187111871 },
1187211872 "fr": {
1187311873 "stringUnit": {
1187411874 "state": "translated",
11875 "value": "Exporter en texte brut avec Emacs"
11875 "value": "Exporter en texte brut (ASCII)"
1187611876 }
1187711877 },
1187811878 "ja": {
1187911879 "stringUnit": {
1188011880 "state": "translated",
11881 "value": "Emacsでプレーンテキストに書き出す"
11881 "value": "プレーンテキスト(ASCII)に書き出す"
1188211882 }
1188311883 },
1188411884 "pt-BR": {
1188511885 "stringUnit": {
1188611886 "state": "translated",
11887 "value": "Exportar para Texto Simples com o Emacs"
11887 "value": "Exportar para Texto Simples (ASCII)"
1188811888 }
1188911889 }
1189011890 }