Native ODT export matching ox-odt !413

merged merged by cmc on 2026-11-20 18:46 UTC · krz/orgstar:parity-odt into main

25 files changed, +2839 −109

Layout: unified · split

README.org +2 −2
@@ -36,8 +36,8 @@ Emacs tomorrow and nothing has been reformatted.
36- *Tables.* Aligned as you type, with =#+TBLFM= formulas. 36- *Tables.* Aligned as you type, with =#+TBLFM= formulas.
37- *Code blocks.* Run source blocks and tangle them into files, as =org-babel-tangle= 37- *Code blocks.* Run source blocks and tangle them into files, as =org-babel-tangle=
38 does. 38 does.
39- *Export.* HTML, Markdown, PDF, Word, RTF, iCalendar and LaTeX built in; PDF through LaTeX, 39- *Export.* HTML, Markdown, PDF, Word, RTF, ODT, iCalendar and LaTeX built in; PDF through
40 ODT and more through Emacs when it is installed (download version only). 40 LaTeX and more through Emacs when it is installed (download version only).
41- *Search.* Across file names, headings and text, plus Spotlight and Quick Look 41- *Search.* Across file names, headings and text, plus Spotlight and Quick Look
42 previews of =.org= files. 42 previews of =.org= files.
43 43
Sources/OrgApp/AppStoreCommands.swift +1 −1
@@ -4,7 +4,7 @@ import Foundation
4/// Emacs, and attaching by link, which the sandbox doesn't allow. 4/// Emacs, and attaching by link, which the sandbox doesn't allow.
5public enum AppStoreCommands { 5public enum AppStoreCommands {
6 public static let hidden: Set<String> = [ 6 public static let hidden: Set<String> = [
7 "app.export.pdf", "app.export.odt", "app.export.text", 7 "app.export.pdf", "app.export.text",
8 "app.attach.link", "app.attach.symlink", 8 "app.attach.link", "app.attach.symlink",
9 ] 9 ]
10 10
Sources/OrgApp/CommandTitles.swift +1 −1
@@ -90,7 +90,7 @@ enum CommandTitles {
90 String(localized: "Export to HTML and Open", comment: "Command title"), 90 String(localized: "Export to HTML and Open", comment: "Command title"),
91 String(localized: "Export to LaTeX", comment: "Command title"), 91 String(localized: "Export to LaTeX", comment: "Command title"),
92 String(localized: "Export to Markdown", comment: "Command title"), 92 String(localized: "Export to Markdown", comment: "Command title"),
93 String(localized: "Export to ODT with Emacs", comment: "Command title"), 93 String(localized: "Export to ODT", comment: "Command title"),
94 String(localized: "Export to PDF", comment: "Command title"), 94 String(localized: "Export to PDF", comment: "Command title"),
95 String(localized: "Export to PDF with Emacs", comment: "Command title"), 95 String(localized: "Export to PDF with Emacs", comment: "Command title"),
96 String(localized: "Export to Plain Text", comment: "Command title"), 96 String(localized: "Export to Plain Text", comment: "Command title"),
Sources/OrgApp/DocxWriter.swift +1 −48
@@ -1,4 +1,5 @@
1import Foundation 1import Foundation
2import OrgCore
2#if os(macOS) 3#if os(macOS)
3import AppKit 4import AppKit
4typealias DocxFont = NSFont 5typealias DocxFont = NSFont
@@ -302,51 +303,3 @@ enum DocxWriter {
302 .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;") 303 .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
303 } 304 }
304} 305}
305
306/// A zip archive with stored (uncompressed) entries, as `.docx` files are read.
307struct ZipWriter {
308 private var entries: [(name: Data, data: Data, crc: UInt32, offset: UInt32)] = []
309 private var archive = Data()
310
311 mutating func add(_ name: String, _ text: String) {
312 add(name, data: Data(text.utf8))
313 }
314
315 mutating func add(_ name: String, data: Data) {
316 let nameData = Data(name.utf8)
317 let crc = Self.crc32(data)
318 let offset = UInt32(archive.count)
319 archive += Self.le32(0x04034b50) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
320 archive += Self.le32(crc) + Self.le32(UInt32(data.count)) + Self.le32(UInt32(data.count))
321 archive += Self.le16(UInt16(nameData.count)) + Self.le16(0) + nameData + data
322 entries.append((nameData, data, crc, offset))
323 }
324
325 func data() -> Data {
326 var central = Data()
327 for entry in entries {
328 central += Self.le32(0x02014b50) + Self.le16(20) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
329 central += Self.le32(entry.crc) + Self.le32(UInt32(entry.data.count)) + Self.le32(UInt32(entry.data.count))
330 central += Self.le16(UInt16(entry.name.count)) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le32(0)
331 central += Self.le32(entry.offset) + entry.name
332 }
333 var end = Self.le32(0x06054b50) + Self.le16(0) + Self.le16(0) + Self.le16(UInt16(entries.count)) + Self.le16(UInt16(entries.count))
334 end += Self.le32(UInt32(central.count)) + Self.le32(UInt32(archive.count)) + Self.le16(0)
335 return archive + central + end
336 }
337
338 private static func le16(_ v: UInt16) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
339 private static func le32(_ v: UInt32) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
340
341 private static let table: [UInt32] = (0..<256).map { n in
342 var c = UInt32(n)
343 for _ in 0..<8 { c = c & 1 != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1 }
344 return c
345 }
346
347 static func crc32(_ data: Data) -> UInt32 {
348 var c: UInt32 = 0xFFFFFFFF
349 for byte in data { c = table[Int((c ^ UInt32(byte)) & 0xFF)] ^ (c >> 8) }
350 return c ^ 0xFFFFFFFF
351 }
352}
Sources/OrgApp/Publish.swift +11 −5
@@ -14,8 +14,8 @@ import OrgCore
14/// 14///
15/// Other keys: `base-extension` (an Emacs regexp, or `any`), `exclude` (a regexp on the path 15/// Other keys: `base-extension` (an Emacs regexp, or `any`), `exclude` (a regexp on the path
16/// under the base directory), `include` (file names separated by spaces), `publishing-function` 16/// under the base directory), `include` (file names separated by spaces), `publishing-function`
17/// (`org-html-publish-to-html`, `org-md-publish-to-md`, `org-publish-attachment`, separated by 17/// (`org-html-publish-to-html`, `org-md-publish-to-md`, `org-odt-publish-to-odt`,
18/// spaces), `sitemap-filename`, `sitemap-title`, `sitemap-style` (`tree` or `list`), 18/// `org-publish-attachment`, separated by spaces), `sitemap-filename`, `sitemap-title`, `sitemap-style` (`tree` or `list`),
19/// `sitemap-sort-files` (`alphabetically`, `chronologically`, `anti-chronologically`, `nil`), 19/// `sitemap-sort-files` (`alphabetically`, `chronologically`, `anti-chronologically`, `nil`),
20/// `sitemap-sort-folders` (`ignore`, `first`, `last`, `nil`), `sitemap-ignore-case`, 20/// `sitemap-sort-folders` (`ignore`, `first`, `last`, `nil`), `sitemap-ignore-case`,
21/// `body-only`, and `components` (project names separated by spaces) for a project of projects. 21/// `body-only`, and `components` (project names separated by spaces) for a project of projects.
@@ -40,7 +40,7 @@ public struct PublishProject: Sendable, Equatable {
40 40
41 public init(name: String) { self.name = name } 41 public init(name: String) { self.name = name }
42 42
43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-latex-publish-to-latex", "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-publish-attachment"]
44} 44}
45 45
46public enum Publish { 46public enum Publish {
@@ -290,13 +290,14 @@ public enum Publish {
290 if directory((file as NSString).deletingLastPathComponent) == outputDirectory { return nil } 290 if directory((file as NSString).deletingLastPathComponent) == outputDirectory { return nil }
291 return outputDirectory + (file as NSString).lastPathComponent 291 return outputDirectory + (file as NSString).lastPathComponent
292 } 292 }
293 let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex"][function] ?? "html" 293 let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex", "org-odt-publish-to-odt": "odt"][function] ?? "html"
294 guard let text = read(file) else { throw Failure(description: "Can't read \(file)") } 294 guard let text = read(file) else { throw Failure(description: "Can't read \(file)") }
295 return ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent), 295 return ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent),
296 name: ExportScope.fileName(text), extension: ext).path 296 name: ExportScope.fileName(text), extension: ext).path
297 } 297 }
298 298
299 /// Copies an attachment to `output`, or writes what `function` exports from `file`. 299 /// Copies an attachment to `output`, or writes what `function` exports from `file`; ODT is
300 /// exported here, with the preferences' settings.
300 private static func write( 301 private static func write(
301 _ file: String, to output: String, function: String, bodyOnly: Bool, 302 _ file: String, to output: String, function: String, bodyOnly: Bool,
302 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String 303 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
@@ -305,6 +306,11 @@ public enum Publish {
305 if function == "org-publish-attachment" { 306 if function == "org-publish-attachment" {
306 if fm.fileExists(atPath: output) { try fm.removeItem(atPath: output) } 307 if fm.fileExists(atPath: output) { try fm.removeItem(atPath: output) }
307 try fm.copyItem(atPath: file, toPath: output) 308 try fm.copyItem(atPath: file, toPath: output)
309 } else if function == "org-odt-publish-to-odt" {
310 let text = read(file) ?? ""
311 let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: file, read: OrgSettings.readFile)
312 try ODTExport.document(text, settings: settings, path: file, author: NSFullUserName(), language: OrgPreferences.exportLanguage())
313 .write(to: URL(fileURLWithPath: output), options: .atomic)
308 } else { 314 } else {
309 try export(function, read(file) ?? "", file, bodyOnly).write(toFile: output, atomically: true, encoding: .utf8) 315 try export(function, read(file) ?? "", file, bodyOnly).write(toFile: output, atomically: true, encoding: .utf8)
310 } 316 }
Sources/OrgCore/Compute/Babel.swift +4 −3
@@ -252,10 +252,11 @@ public enum Babel {
252 /// What export shows of the src block, `#+CALL:` line, inline call or inline src block 252 /// What export shows of the src block, `#+CALL:` line, inline call or inline src block
253 /// starting at `offset` (`org-babel-exp-process-buffer`): `code`, `results`, `both` or 253 /// starting at `offset` (`org-babel-exp-process-buffer`): `code`, `results`, `both` or
254 /// `none`, from the header arguments as evaluation resolves them. Calls never show code. 254 /// `none`, from the header arguments as evaluation resolves them. Calls never show code.
255 /// Nil when nothing there runs. 255 /// Nil when nothing there runs. Without `languages`, as in `emacs -Q`, no language's
256 public static func exports(at offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) -> String? { 256 /// `ob-` library is loaded to give its own default.
257 public static func exports(at offset: Int, tree: OrgTree, model: DocumentModel, text: NSString, languages: Bool = true) -> String? {
257 func value(_ params: Params?, language: String?) -> String { 258 func value(_ params: Params?, language: String?) -> String {
258 (params?.single[":exports"] ?? language.flatMap { languageExports[$0] } ?? "code").lowercased() 259 (params?.single[":exports"] ?? language.flatMap { languages ? languageExports[$0] : nil } ?? "code").lowercased()
259 } 260 }
260 if let block = model.srcBlocks.first(where: { $0.range.lowerBound == offset }) { 261 if let block = model.srcBlocks.first(where: { $0.range.lowerBound == offset }) {
261 return value(try? Params(block: block, model: model, text: text), language: block.language) 262 return value(try? Params(block: block, model: model, text: text), language: block.language)
Sources/OrgCore/Export/ExportOptions.swift +74 −2
@@ -118,7 +118,9 @@ public struct ExportOptions: Sendable, Equatable {
118public enum ExportPreprocess { 118public enum ExportPreprocess {
119 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with 119 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with
120 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`. 120 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`.
121 public static func includes(_ text: String, directory: URL?, depth: Int = 0) -> String { 121 /// `includer` is the exported file's directory, `directory` at the top.
122 public static func includes(_ text: String, directory: URL?, depth: Int = 0, includer: URL? = nil) -> String {
123 let includer = depth == 0 ? directory : includer
122 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text } 124 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text }
123 var lines: [String] = [] 125 var lines: [String] = []
124 for line in text.components(separatedBy: "\n") { 126 for line in text.components(separatedBy: "\n") {
@@ -159,10 +161,11 @@ public enum ExportPreprocess {
159 lines.append("#+END_\(kind)") 161 lines.append("#+END_\(kind)")
160 continue 162 continue
161 } 163 }
164 if let includer { included = rebasingLinks(included, from: url.deletingLastPathComponent(), to: includer) }
162 if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) { 165 if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) {
163 included = shift(included, to: minLevel) 166 included = shift(included, to: minLevel)
164 } 167 }
165 let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1) 168 let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1, includer: includer)
166 lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded) 169 lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded)
167 } 170 }
168 return lines.joined(separator: "\n") 171 return lines.joined(separator: "\n")
@@ -187,6 +190,75 @@ public enum ExportPreprocess {
187 return unreadable 190 return unreadable
188 } 191 }
189 192
193 /// `org-export--update-included-link`: the relative `file` links of a file in `directory`,
194 /// relative to `includer` instead. Links in descriptions too; `plain` for those, which
195 /// can only be plain or angle links.
196 static func rebasingLinks(_ text: String, from directory: URL, to includer: URL, plain: Bool = false) -> String {
197 guard plain || directory.resolvingSymlinksInPath().path != includer.resolvingSymlinksInPath().path else { return text }
198 let ns = text as NSString
199 var edits: [(range: Range<Int>, text: String)] = []
200 for node in OrgParser.parse(text).root.descendants() where node.kind == .link {
201 let whole = node.text
202 if whole.hasPrefix("[[") {
203 guard !plain else { continue }
204 if let description = node.firstChild(.linkDescription) {
205 let rebased = rebasingLinks(description.text, from: directory, to: includer, plain: true)
206 if rebased != description.text { edits.append((description.range, rebased)) }
207 }
208 if let path = node.tokens.first(where: { $0.kind == .linkPath }), let rebased = rebasedPath(path.text, from: directory, to: includer, bracket: true) {
209 edits.append((path.range, rebased))
210 }
211 } else if whole.hasPrefix("<"), whole.hasSuffix(">") {
212 if let rebased = rebasedPath(String(whole.dropFirst().dropLast()), from: directory, to: includer, bracket: false) {
213 edits.append((node.range, "<" + rebased + ">"))
214 }
215 } else if let rebased = rebasedPath(whole, from: directory, to: includer, bracket: false) {
216 edits.append((node.range, rebased))
217 }
218 }
219 guard !edits.isEmpty else { return text }
220 let out = NSMutableString(string: ns)
221 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
222 out.replaceCharacters(in: NSRange(location: edit.range.lowerBound, length: edit.range.count), with: edit.text)
223 }
224 return out as String
225 }
226
227 /// A link's path rewritten as `org-element-link-interpreter` writes it back: the type only
228 /// when it was written. Nil when it isn't a relative file link.
229 static func rebasedPath(_ raw: String, from directory: URL, to includer: URL, bracket: Bool) -> String? {
230 var type = ""
231 var rest = raw
232 if let m = raw.firstMatch(of: /^(file(?:\+[^:]+)?|[^:\/]+\+file):/) {
233 type = String(m.0)
234 rest = String(raw[m.0.endIndex...])
235 } else if !(bracket && ["/", "./", "../", "~"].contains(where: raw.hasPrefix)) {
236 return nil
237 }
238 var path = rest
239 var search = ""
240 if let r = rest.range(of: "::") {
241 path = String(rest[..<r.lowerBound])
242 search = String(rest[r.lowerBound...])
243 }
244 guard !path.hasPrefix("/"), !path.hasPrefix("~") else { return nil }
245 // `file-relative-name` of `expand-file-name`.
246 func components(_ path: String) -> [String] {
247 var out: [String] = []
248 for part in path.split(separator: "/", omittingEmptySubsequences: true) {
249 if part == "." { continue }
250 if part == ".." { if !out.isEmpty { out.removeLast() } } else { out.append(String(part)) }
251 }
252 return out
253 }
254 let target = components(directory.path + "/" + path)
255 let base = components(includer.path)
256 var common = 0
257 while common < min(target.count, base.count), target[common] == base[common] { common += 1 }
258 let relative = (Array(repeating: "..", count: base.count - common) + target[common...]).joined(separator: "/")
259 return type + (relative.isEmpty ? "." : relative) + search
260 }
261
190 /// An include's file, relative to `directory`. 262 /// An include's file, relative to `directory`.
191 static func includeURL(_ file: String, directory: URL?) -> URL { 263 static func includeURL(_ file: String, directory: URL?) -> URL {
192 (file as NSString).isAbsolutePath || directory == nil 264 (file as NSString).isAbsolutePath || directory == nil
Sources/OrgCore/Export/HTMLExport.swift +5 −2
@@ -112,14 +112,17 @@ final class ExportSource {
112 /// Whether the last inline src block or call lets the `{{{results(…)}}}` after it show; 112 /// Whether the last inline src block or call lets the `{{{results(…)}}}` after it show;
113 /// nil when nothing asks. 113 /// nil when nothing asks.
114 var inlineResults: Bool? 114 var inlineResults: Bool?
115 /// Whether the languages' own `:exports` defaults apply.
116 let languages: Bool
115 117
116 init(tree: OrgTree, text: String) { 118 init(tree: OrgTree, text: String, languages: Bool = true) {
117 self.tree = tree 119 self.tree = tree
118 self.text = text as NSString 120 self.text = text as NSString
121 self.languages = languages
119 } 122 }
120 123
121 func exports(at offset: Int) -> String? { 124 func exports(at offset: Int) -> String? {
122 Babel.exports(at: offset, tree: tree, model: model, text: text) 125 Babel.exports(at: offset, tree: tree, model: model, text: text, languages: languages)
123 } 126 }
124 127
125 /// `{{{results(…)}}}`, Org's `$1` macro, as the inline block or call before it allows: 128 /// `{{{results(…)}}}`, Org's `$1` macro, as the inline block or call before it allows:
Sources/OrgCore/Export/ODTExport.swift added +1535
@@ -0,0 +1,1535 @@
1import Foundation
2import ImageIO
3
4/// OpenDocument text export written from the parse tree, in the shape ox-odt (Org 9.8.7) gives
5/// `content.xml` under `emacs -Q`: LaTeX left verbatim, as without a MathML converter, and source
6/// blocks without colors. `styles.xml` is a reduced template holding ox-odt's style names.
7public enum ODTExport {
8 public struct Failure: LocalizedError, Equatable {
9 public let message: String
10 public var errorDescription: String? { message }
11 }
12
13 /// The `.odt` file: `content.xml`, `styles.xml`, `meta.xml`, the images and the manifest,
14 /// with `mimetype` first and stored. `path` is the file's, for `#+INCLUDE`, macros and
15 /// images; `author` is used without `#+AUTHOR` (`user-full-name`); `language` is
16 /// `org-export-default-language`. Throws what makes ox-odt stop: broken links and missing
17 /// images among them.
18 public static func document(
19 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(),
20 author: String? = nil, language: String = "en"
21 ) throws -> Data {
22 var zip = ZipWriter()
23 for part in try parts(text, settings: settings, path: path, now: now, author: author, language: language) {
24 zip.add(part.name, data: part.data)
25 }
26 return zip.data()
27 }
28
29 /// The image files `text` embeds, for the sandbox to reach before exporting.
30 /// Images in `#+INCLUDE`d files and images shown as a link's description count.
31 public static func imageFiles(_ text: String, settings: OrgSettings = .default, path: String) -> [String] {
32 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
33 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, setup: settings.setupKeywords)
34 return OrgParser.parse(text, defaults: settings).root.descendants().compactMap { node in
35 guard node.kind == .link else { return nil }
36 let file: String?
37 if let description = node.firstChild(.linkDescription) {
38 file = ODTRenderer.describedImage(description)
39 } else {
40 file = ODTRenderer.linkPath(node).flatMap(ODTRenderer.filePath).flatMap { ODTRenderer.isImage($0) ? $0 : nil }
41 }
42 return file.map { ODTRenderer.expand($0, directory: directory).path }
43 }
44 }
45
46 static func parts(
47 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(),
48 author: String? = nil, language: String = "en"
49 ) throws -> [(name: String, data: Data)] {
50 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
51 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
52 let options = ExportOptions.parse(settings.setupKeywords + text)
53 let meta = HTMLExport.metadata(text, settings: settings)
54 let keywords = Self.keywords(text, settings: settings)
55 let renderer = ODTRenderer(settings: settings, options: options, directory: directory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath))
56 try Self.read(settings.setupKeywords + text, into: renderer)
57 renderer.language = meta.language ?? language
58
59 // The title isn't part of the document Org processes citations in: they drop out.
60 renderer.inTitle = true
61 let title = meta.title.map(renderer.inlineString) ?? ""
62 let subtitle = keywords["SUBTITLE"].map(renderer.inlineString) ?? ""
63 let authorName = (meta.author ?? author).flatMap { $0.isEmpty ? nil : $0 }.map(renderer.inlineString)
64 renderer.inTitle = false
65 renderer.author = authorName
66 renderer.dated = !(meta.date ?? "").isEmpty
67 renderer.citations = CiteProcessor(text: text, directory: directory)
68 let body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
69 let date = options.date ? meta.date.flatMap { $0.isEmpty ? nil : renderer.inlineString($0) } : nil
70 if let failure = renderer.failure { throw failure }
71
72 var preamble = ""
73 if options.title, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
74 preamble += "\n<text:p text:style-name=\"OrgTitle\">\n<text:title>\(title)</text:title></text:p>\n"
75 preamble += "\n<text:p text:style-name=\"OrgTitle\"/>\n"
76 if !subtitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
77 preamble += "<text:p text:style-name=\"OrgSubtitle\">\n<text:user-defined style:data-style-name=\"N0\" text:name=\"subtitle\">\n\(subtitle)</text:user-defined>\n\n</text:p>\n"
78 preamble += "<text:p text:style-name=\"OrgSubtitle\"/>\n"
79 }
80 }
81 if options.author, let authorName {
82 preamble += "\n<text:p text:style-name=\"OrgSubtitle\"><text:initial-creator>\(authorName)</text:initial-creator></text:p>"
83 preamble += "\n<text:p text:style-name=\"OrgSubtitle\"/>"
84 }
85 if let date { preamble += "\n<text:p text:style-name=\"OrgSubtitle\">\(date)</text:p><text:p text:style-name=\"OrgSubtitle\"/>" }
86 let contents = ODTTemplate.content(automaticStyles: renderer.automaticStyles(), body: preamble + renderer.tableOfContents() + body)
87
88 let stamp = meta.date.flatMap(Timestamp.parse).map { stamp -> String in
89 let p = stamp.start
90 return String(format: "%04d-%02d-%02dT%02d:%02d:00", p.year, p.month, p.day, p.hour ?? 0, p.minute ?? 0)
91 } ?? Self.isoDate(now)
92 let metaXML = ODTTemplate.meta(
93 author: authorName.map(ODTRenderer.stripped) ?? "", date: options.date ? stamp : nil, keywords: keywords["KEYWORDS"] ?? "",
94 description: keywords["DESCRIPTION"] ?? "", title: ODTRenderer.stripped(title), subtitle: ODTRenderer.stripped(subtitle)
95 )
96
97 var parts: [(name: String, data: Data)] = [("mimetype", Data(ODTTemplate.mimetype.utf8))]
98 parts.append(("content.xml", Data(contents.utf8)))
99 parts.append(("styles.xml", Data(ODTTemplate.styles(numbered: min(renderer.numbered ?? 0, 10)).utf8)))
100 parts.append(("meta.xml", Data(metaXML.utf8)))
101 parts += renderer.images.map { ($0.name, $0.data) }
102 parts.append(("META-INF/manifest.xml", Data(ODTTemplate.manifest(images: renderer.images.map(\.name)).utf8)))
103 return parts
104 }
105
106 /// The `#+OPTIONS` items ox-odt reads that `ExportOptions` doesn't, or reads differently:
107 /// `num` to any depth, `\\n`, `f`, `|`, `e` and `d` honored; other items at a value other
108 /// than their default stop the export.
109 static func read(_ text: String, into renderer: ODTRenderer) throws {
110 var items: [String: String] = [:]
111 for line in text.matches(of: #/(?mi)^[ \t]*#\+OPTIONS:[ \t]*(.*?)[ \t]*$/#) {
112 for item in line.1.matches(of: /(\S+?):(\S+)/) { items[String(item.1)] = String(item.2) }
113 }
114 let defaults = [
115 "p": "nil", "broken-links": "nil", "c": "nil", "prop": "nil", ":": "t", "*": "t", "stat": "t",
116 "tasks": "t", "<": "t", "arch": "headline", "email": "nil", "'": "nil",
117 ]
118 for (key, value) in items.sorted(by: { $0.key < $1.key }) {
119 if let standard = defaults[key], value != standard {
120 throw Failure(message: "ODT export doesn't support #+OPTIONS: \(key):\(value)")
121 }
122 }
123 if let tex = items["tex"], tex != "t", tex != "nil" { throw Failure(message: "ODT export doesn't support #+OPTIONS: tex:\(tex)") }
124 switch items["d"] {
125 case nil: renderer.drawers = nil
126 case "nil": renderer.drawers = false
127 case "t": renderer.drawers = true
128 case let value?: throw Failure(message: "ODT export doesn't support #+OPTIONS: d:\(value)")
129 }
130 // `org-export-numbered-headline-p`: `t` numbers every level, `N` levels to N, past `H`.
131 switch items["num"] {
132 case "nil": renderer.numbered = nil
133 case let value?: renderer.numbered = Int(value) ?? Int.max
134 case nil: renderer.numbered = Int.max
135 }
136 renderer.preserveBreaks = items["\\n"].map { $0 != "nil" } ?? false
137 renderer.withFootnotes = items["f"] != "nil"
138 renderer.withTables = items["|"] != "nil"
139 renderer.withEntities = items["e"] != "nil"
140 }
141
142 /// `#+SUBTITLE`, `#+KEYWORDS` and `#+DESCRIPTION`: lines of the same keyword joined.
143 static func keywords(_ text: String, settings: OrgSettings) -> [String: String] {
144 let tree = OrgParser.parse(text, defaults: settings)
145 let own = tree.root.children.filter { $0.kind == .zerothSection }.flatMap { $0.children.filter { $0.kind == .keyword } }.map(\.text)
146 var values: [String: String] = [:]
147 for line in settings.setupKeywords.split(separator: "\n").map(String.init) + own {
148 guard let m = line.firstMatch(of: /^[ \t]*#\+([A-Za-z_]+):[ \t]*(.*?)[ \t]*\n?$/) else { continue }
149 let key = m.1.uppercased()
150 guard ["SUBTITLE", "KEYWORDS", "DESCRIPTION"].contains(key) else { continue }
151 values[key] = values[key].map { $0 + (key == "DESCRIPTION" ? "\n" : " ") + m.2 } ?? String(m.2)
152 }
153 return values
154 }
155
156 static func isoDate(_ date: Date) -> String {
157 let formatter = DateFormatter()
158 formatter.locale = Locale(identifier: "en_US_POSIX")
159 formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
160 return formatter.string(from: date)
161 }
162}
163
164final class ODTRenderer {
165 let settings: OrgSettings
166 let options: ExportOptions
167 let directory: URL
168 var language = "en"
169 var citations: CiteProcessor?
170 /// Rendering the title, where Org exports citations as nothing.
171 var inTitle = false
172 /// The document's author, rendered, and whether it has a date, for annotations.
173 var author: String?
174 var dated = false
175 /// The first error, which stops the export as ox-odt's errors do.
176 private(set) var failure: ODTExport.Failure?
177 private(set) var images: [(name: String, data: Data)] = []
178
179 /// `num`: headings numbered to this relative level, `Int.max` for all; nil for none.
180 var numbered: Int? = Int.max
181 /// `\\n`, `f`, `|` and `e`.
182 var preserveBreaks = false
183 var withFootnotes = true
184 var withTables = true
185 var withEntities = true
186 /// `d`: nil for every drawer but `LOGBOOK`, true for every drawer, false for none.
187 var drawers: Bool?
188
189 init(settings: OrgSettings, options: ExportOptions, directory: URL) {
190 self.settings = settings
191 self.options = options
192 self.directory = directory
193 }
194
195 private func fail(_ message: String) -> String {
196 if failure == nil { failure = ODTExport.Failure(message: message) }
197 return ""
198 }
199
200 // MARK: - Collecting
201
202 /// An exported heading, by its start in the document.
203 struct Heading {
204 var key: Int
205 var level: Int
206 var ancestors: [Int]
207 var info: HeadingInfo?
208 var node: SyntaxNode
209 var relative = 1
210 var number: [Int]?
211 var lowLevel = false
212 var reference = ""
213 }
214
215 /// A captioned or named table, source block or image: its category, sequence and label.
216 struct Label {
217 var category: String
218 var variable: String
219 var sequence: String
220 var reference: String?
221 }
222
223 private var headings: [Int: Heading] = [:]
224 private var headingOrder: [Int] = []
225 private var targets: [(words: [String], key: Int, reference: String)] = []
226 private var names: [(words: [String], key: Int)] = []
227 private var labels: [Int: Label] = [:]
228 private var enumerables: [(key: Int, category: String, ancestors: [Int])] = []
229 private var references = 0
230 private var selected: Set<Int>?
231 private var documentTree: OrgTree?
232 private var blockLocs: [String: [Int?]] = [:]
233 /// Footnote definitions by label: the last in the document, a definition or an inline one.
234 private var definitions: [String: (text: String, base: Int, inline: Bool)] = [:]
235
236 /// Where the tree being read starts in the document, so elements read from a block's or a
237 /// footnote's contents keep their place; how deep in such contents it is.
238 private var base = 0
239 private var depth = 0
240 /// Elements after a footnote definition that belong to it, by their start.
241 private var absorbed: Set<Int> = []
242
243 private func newReference() -> String {
244 references += 1
245 return String(format: "org%07x", references &* 2_654_435_761 & 0xFFF_FFFF)
246 }
247
248 private static func words(_ s: String) -> [String] { s.split(whereSeparator: \.isWhitespace).map(String.init) }
249
250 private func collect(_ tree: OrgTree) {
251 let model = DocumentModel(tree: tree)
252 var infos: [Int: HeadingInfo] = [:]
253 for heading in model.headings { infos[heading.headingRange.lowerBound] = heading }
254 collect(tree.root, ancestors: [], infos: infos)
255 let top = headingOrder.compactMap { headings[$0]?.level }.min() ?? 1
256 var counters: [Int] = []
257 for key in headingOrder {
258 var heading = headings[key]!
259 heading.relative = heading.level - top + 1
260 heading.lowLevel = heading.relative > options.headlineLevels
261 heading.reference = newReference()
262 let unnumbered = unnumberedValue(heading).map { $0 != "nil" } ?? false
263 if let numbered, heading.relative <= numbered, !unnumbered {
264 let index = heading.relative - 1
265 if counters.count <= index { counters += Array(repeating: 0, count: index + 1 - counters.count) }
266 counters[index] += 1
267 for i in (index + 1)..<counters.count { counters[i] = 0 }
268 heading.number = Array(counters.prefix(index + 1))
269 }
270 headings[key] = heading
271 }
272 // `org-odt--enumerate`: numbered within the closest numbered heading at level 2 or
273 // above, else through the document.
274 for (index, item) in enumerables.enumerated() {
275 let scope = item.ancestors.reversed().first { headings[$0].map { $0.relative <= 2 && $0.number != nil } ?? false }
276 let ordinal = enumerables[...index].filter { $0.category == item.category && (scope.map($0.ancestors.contains) ?? true) }.count
277 let sequence = (scope.flatMap { headings[$0]?.number }.map { $0.map(String.init).joined(separator: ".") + "." } ?? "") + String(ordinal)
278 let named = names.contains { $0.key == item.key }
279 let variable = ["Table": "Table", "Figure": "Illustration", "Listing": "Listing"][item.category]!
280 labels[item.key] = Label(category: item.category, variable: variable, sequence: sequence, reference: named ? newReference() : nil)
281 }
282 }
283
284 /// `UNNUMBERED` of the heading or its closest ancestor that has it.
285 private func unnumberedValue(_ heading: Heading) -> String? {
286 for key in [heading.key] + heading.ancestors.reversed() {
287 if let value = headings[key]?.info?.properties.last(where: { $0.key.uppercased() == "UNNUMBERED" })?.value {
288 return value.trimmingCharacters(in: .whitespaces)
289 }
290 }
291 return nil
292 }
293
294 private func collect(_ node: SyntaxNode, ancestors: [Int], infos: [Int: HeadingInfo]) {
295 var affiliated: [String: String] = [:]
296 for child in node.children {
297 if child.kind == .affiliatedKeyword {
298 if let m = child.text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
299 affiliated[m.1.uppercased()] = String(m.2)
300 }
301 continue
302 }
303 defer { affiliated = [:] }
304 if depth == 0, absorbed.contains(child.range.lowerBound) { continue }
305 let key = base + child.range.lowerBound
306 if let name = affiliated["NAME"] { names.append((Self.words(name), key)) }
307 let captioned = affiliated["CAPTION"] != nil || affiliated["NAME"] != nil
308 switch child.kind {
309 case .section:
310 guard let heading = child.firstChild(.heading) else { collect(child, ancestors: ancestors, infos: infos); continue }
311 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
312 if export == .nothing { continue }
313 let headingKey = base + heading.range.lowerBound
314 let level = heading.tokens.first { $0.kind == .stars }?.text.count ?? 1
315 headings[headingKey] = Heading(key: headingKey, level: level, ancestors: ancestors, info: infos[heading.range.lowerBound], node: heading)
316 headingOrder.append(headingKey)
317 collect(heading, ancestors: ancestors, infos: infos)
318 if export == .all { collect(child, ancestors: ancestors + [headingKey], infos: infos) }
319 case .heading, .footnoteDefinition:
320 continue
321 case .target, .radioTarget:
322 let inner = child.kind == .target ? child.text.dropFirst(2).dropLast(2) : child.text.dropFirst(3).dropLast(3)
323 targets.append((Self.words(inner.uppercased()), key, newReference()))
324 case .table:
325 guard withTables else { continue }
326 if captioned { enumerables.append((key, "Table", ancestors)) }
327 collect(child, ancestors: ancestors, infos: infos)
328 case .paragraph:
329 if captioned, soleImage(child) != nil { enumerables.append((key, "Figure", ancestors)) }
330 collect(child, ancestors: ancestors, infos: infos)
331 case .block:
332 let (type, _, _, body) = Self.blockParts(child)
333 if type == "src", captioned { enumerables.append((key, "Listing", ancestors)) }
334 if ["src", "example", "export", "comment", "verse"].contains(type) { continue }
335 within(body.text, base: key + body.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
336 case .drawer, .dynamicBlock:
337 guard let inner = inner(child) else { continue }
338 within(inner.text, base: key + inner.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
339 default:
340 collect(child, ancestors: ancestors, infos: infos)
341 }
342 }
343 }
344
345 /// A drawer's or dynamic block's contents and their offset in it; nil for a drawer `d`
346 /// leaves out.
347 private func inner(_ node: SyntaxNode) -> (text: String, offset: Int)? {
348 var lines = node.text.components(separatedBy: "\n")
349 if lines.last == "" { lines.removeLast() }
350 guard let first = lines.first else { return nil }
351 if node.kind == .drawer, !(drawers ?? (first.trimmingCharacters(in: .whitespaces).uppercased() != ":LOGBOOK:")) { return nil }
352 return (lines.dropFirst().dropLast().joined(separator: "\n"), first.utf16.count + 1)
353 }
354
355 /// `body` with `text`, which starts at `base` in the document, parsed.
356 private func within<T>(_ text: String, base: Int, _ body: (OrgTree) -> T) -> T {
357 let saved = self.base
358 self.base = base
359 depth += 1
360 defer { self.base = saved; depth -= 1 }
361 return body(OrgParser.parse(text, defaults: settings))
362 }
363
364 // MARK: - Document
365
366 private var source: ExportSource?
367
368 /// `body` with `tree` as the source of `:exports`. As in `emacs -Q`, which loads no `ob-`
369 /// library for dot, LaTeX and the like, their blocks export their code.
370 private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
371 let saved = source
372 source = ExportSource(tree: tree, text: text, languages: false)
373 defer { source = saved }
374 return body()
375 }
376
377 func document(_ text: String) -> String {
378 let tree = OrgParser.parse(text, defaults: settings)
379 documentTree = tree
380 let codeBlocks = Coderef.blocks(tree)
381 for (lines, loc) in zip(codeBlocks, Coderef.locs(codeBlocks.compactMap(Coderef.block))) {
382 blockLocs[lines.joined(separator: "\n"), default: []].append(loc)
383 }
384 // A definition runs to the next definition or heading, or two blank lines.
385 let ns = text as NSString
386 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
387 guard let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) else { continue }
388 let start = node.range.lowerBound + node.text.utf16.distance(from: node.text.startIndex, to: m.range.upperBound)
389 var end = node.range.upperBound
390 let siblings = node.parent?.children ?? []
391 if let index = siblings.firstIndex(where: { $0.range == node.range }) {
392 for sibling in siblings[(index + 1)...] {
393 if [.footnoteDefinition, .section, .heading].contains(sibling.kind) { break }
394 let gap = ns.substring(with: NSRange(location: node.range.lowerBound, length: sibling.range.lowerBound - node.range.lowerBound))
395 if gap.range(of: "\n[ \t]*\n[ \t]*\n[ \t]*$", options: .regularExpression) != nil { break }
396 absorbed.insert(sibling.range.lowerBound)
397 end = sibling.range.upperBound
398 }
399 }
400 definitions[String(m.1)] = (ns.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .newlines), start, false)
401 }
402 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
403 collect(tree)
404 if footnotePass == nil, withFootnotes { numberFootnotes(text) }
405 return rendering(tree, text) { tree.root.children.map(element).joined() }
406 }
407
408 /// Org text that starts at `base` in the document, rendered as elements.
409 private func blocks(_ text: String, base: Int) -> String {
410 within(text, base: base) { tree in rendering(tree, text) { tree.root.children.map(element).joined() } }
411 }
412
413 /// One line of org text rendered inline.
414 func inlineString(_ text: String) -> String {
415 let tree = OrgParser.parse(text, defaults: settings)
416 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
417 return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
418 }
419
420 // MARK: - Table of contents
421
422 /// `org-odt-toc` for the whole document: headings to `toc`, or nothing.
423 func tableOfContents() -> String {
424 guard let depth = options.toc else { return "" }
425 return toc(depth: depth, scope: nil, template: true)
426 }
427
428 /// `org-export-collect-headlines`: `depth` relative to `scope`, within `H`, without the
429 /// headings `org-export-excluded-from-toc-p` leaves out.
430 /// In the `template` one, ox-odt reads `org-done-keywords` outside the Org buffer, where
431 /// it's empty: every keyword is a TODO one.
432 /// A `local` one has no title, even outside any heading.
433 private func toc(depth: Int, scope: Int?, local: Bool = false, template: Bool = false) -> String {
434 let limit = min(scope.flatMap { headings[$0].map { $0.relative + depth } } ?? depth, options.headlineLevels)
435 let keys = headingOrder.filter { key in
436 let heading = headings[key]!
437 let excluded = heading.lowLevel || unnumberedValue(heading) == "notoc" || options.toc.map { heading.relative > $0 } ?? false
438 return heading.relative <= limit && !excluded && (scope.map { heading.ancestors.contains($0) } ?? true)
439 }
440 guard !keys.isEmpty else { return "" }
441 let title = local ? nil : ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8)
442 var out = "\n<text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">\n"
443 out += " <text:table-of-content-source text:outline-level=\"\(depth)\">"
444 if let title { out += "\n <text:index-title-template text:style-name=\"Contents_20_Heading\">\(Self.escape(title))</text:index-title-template>\n" }
445 for level in 1...10 {
446 out += """
447
448 <text:table-of-content-entry-template text:outline-level="\(level)" text:style-name="Contents_20_\(level)">
449 <text:index-entry-link-start text:style-name="Internet_20_link"/>
450 <text:index-entry-chapter/>
451 <text:index-entry-text/>
452 <text:index-entry-link-end/>
453 </text:table-of-content-entry-template>
454
455 """
456 }
457 out += "\n </text:table-of-content-source>\n <text:index-body>"
458 if let title {
459 out += "\n <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">\n <text:p text:style-name=\"Contents_20_Heading\">\(Self.escape(title))</text:p>\n </text:index-title>\n"
460 }
461 tocEntry = true
462 out += keys.map { key in
463 let heading = headings[key]!
464 var entry = heading.number.map { $0.map(String.init).joined(separator: ".") + ". " } ?? ""
465 let parts = headlineParts(heading.node)
466 if let todo = parts.todo { entry += "<text:span text:style-name=\"\(settings.isDone(todo) && !template ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
467 if let priority = parts.priority { entry += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
468 entry += parts.title
469 if options.tagsInTOC, !parts.tags.isEmpty { entry += " " + tagsSpan(parts.tags) }
470 return "\n<text:p text:style-name=\"Contents_20_\(heading.relative)\"><text:a xlink:type=\"simple\" xlink:href=\"#\(heading.reference)\">\(entry)</text:a></text:p>"
471 }.joined(separator: "\n")
472 tocEntry = false
473 return out + "\n </text:index-body>\n</text:table-of-content>"
474 }
475
476 /// Rendering a table of contents entry: footnotes and targets drop out, links become text.
477 private var tocEntry = false
478
479 // MARK: - Elements
480
481 private var affiliated: [String: String] = [:]
482 /// `:exports` of the last src block or call: its results are exported only for `results`
483 /// and `both`; nothing runs.
484 private var lastExports = "code"
485
486 func element(_ node: SyntaxNode) -> String {
487 if depth == 0, absorbed.contains(node.range.lowerBound) { return "" }
488 defer { if node.kind != .affiliatedKeyword { affiliated = [:] } }
489 if node.kind != .affiliatedKeyword, affiliated["RESULTS"] != nil {
490 defer { lastExports = "code" }
491 if lastExports != "results", lastExports != "both" { return "" }
492 }
493 if node.kind == .block || node.kind == .keyword, let exports = source?.exports(at: node.range.lowerBound) {
494 lastExports = exports
495 if exports == "results" || exports == "none" { return "" }
496 }
497 switch node.kind {
498 case .section:
499 guard let heading = node.firstChild(.heading) else { fallthrough }
500 switch HTMLRenderer.sectionExport(heading, options: options, selected: selected) {
501 case .nothing: return ""
502 case .heading: return section(node, heading: heading, contents: false)
503 case .all: return section(node, heading: heading, contents: true)
504 }
505 case .zerothSection, .document:
506 return node.children.map(element).joined()
507 case .affiliatedKeyword:
508 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
509 if let m = line.firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
510 affiliated[m.1.uppercased()] = String(m.2)
511 }
512 return ""
513 case .paragraph:
514 return paragraph(node)
515 case .keyword:
516 return keyword(node)
517 case .plainList:
518 return list(node)
519 case .table:
520 return withTables ? table(node) : ""
521 case .block:
522 return block(node)
523 case .horizontalRule:
524 return "\n<text:p text:style-name=\"Horizontal_20_Line\"></text:p>"
525 case .drawer, .dynamicBlock:
526 guard let inner = inner(node) else { return "" }
527 return blocks(inner.text, base: base + node.range.lowerBound + inner.offset)
528 case .inlineTask:
529 // `emacs -Q` doesn't load org-inlinetask, so ox-odt reads them as headings.
530 return fail("ODT export doesn't support inline tasks")
531 case .latexEnvironment:
532 guard options.tex else { return "" }
533 // Its value ends with a newline, which ox-odt writes as an empty last line.
534 return code(Self.dedent(node.text.trimmingCharacters(in: .newlines).components(separatedBy: "\n")), emptyLast: node.text.hasSuffix("\n"))
535 case .fixedWidth:
536 let lines = node.text.trimmingCharacters(in: .newlines).split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
537 let trimmed = line.drop { $0 == " " || $0 == "\t" }
538 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
539 }
540 return code(lines)
541 case .tableEl:
542 // ox-odt strips table.el tables, the list around them closed and opened again.
543 return frames.isEmpty || !withTables ? "" : "\n" + reopening(nil, for: node)
544 default:
545 // Comments, property drawers, planning, clocks, footnote definitions, formulas.
546 return ""
547 }
548 }
549
550 // MARK: - Headings
551
552 private func headlineParts(_ node: SyntaxNode) -> (todo: String?, priority: String?, title: String, tags: [String]) {
553 let tokens = node.tokens
554 let todo = options.todo ? tokens.first { $0.kind == .todoKeyword }?.text : nil
555 let priority = options.priority ? tokens.first { $0.kind == .priority }?.text.firstMatch(of: /\[#(.+)\]/).map { String($0.1) } : nil
556 let title = node.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
557 let tags = options.tags ? tokens.first { $0.kind == .tags }?.text.split(separator: ":").map(String.init) ?? [] : []
558 return (todo, priority, title, tags)
559 }
560
561 private func tagsSpan(_ tags: [String]) -> String {
562 "<text:span text:style-name=\"OrgTags\">[" + tags.map { "<text:span text:style-name=\"OrgTag\">\(Self.escape($0))</text:span>" }.joined(separator: " : ") + "]</text:span>"
563 }
564
565 /// `org-odt-format-headline-default-function`.
566 private func headline(_ node: SyntaxNode) -> String {
567 let parts = headlineParts(node)
568 var out = ""
569 if let todo = parts.todo { out += "<text:span text:style-name=\"\(settings.isDone(todo) ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
570 if let priority = parts.priority { out += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
571 out += parts.title
572 if !parts.tags.isEmpty { out += "<text:tab/>" + tagsSpan(parts.tags) }
573 return out
574 }
575
576 private static func target(_ text: String, _ id: String) -> String {
577 "\n<text:bookmark-start text:name=\"OrgXref.\(id)\"/>\n<text:bookmark text:name=\"\(id)\"/>\(text)\n<text:bookmark-end text:name=\"OrgXref.\(id)\"/>"
578 }
579
580 private func section(_ node: SyntaxNode, heading node0: SyntaxNode, contents: Bool) -> String {
581 guard let heading = headings[base + node0.range.lowerBound] else { return "" }
582 let extra = heading.info?.id.map { Self.target("", "ID-" + $0) } ?? ""
583 let anchored = Self.target(headline(node0), heading.reference)
584 let numbered = heading.number != nil
585 headingStack.append(heading.key)
586 defer { headingStack.removeLast() }
587 guard heading.lowLevel else {
588 let open = "\n<text:h text:style-name=\"Heading_20_\(heading.relative)\(numbered ? "" : "_unnumbered")\" text:outline-level=\"\(heading.relative)\" text:is-list-header=\"\(numbered ? "false" : "true")\">\(extra)\(anchored)</text:h>"
589 return open + (contents ? node.children.filter { $0.kind != .heading }.map(element).joined() : "")
590 }
591 // A heading deeper than `H` is a list item, its siblings in one list.
592 let siblings = (node.parent?.children ?? []).filter { section in
593 section.kind == .section && section.firstChild(.heading).map { headings[base + $0.range.lowerBound] != nil } ?? false
594 }
595 let style = numbered ? "OrgNumberedList" : "OrgBulletedList"
596 var out = ""
597 if siblings.first?.range == node.range {
598 let parentLow = heading.ancestors.last.flatMap { headings[$0]?.lowLevel } ?? false
599 out += "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"\(parentLow)\">"
600 }
601 frames.append(Frame(style: style, heading: true))
602 let body = "\n<text:p text:style-name=\"Text_20_body\">\(extra)\(anchored)</text:p>" + (contents ? node.children.filter { $0.kind != .heading }.map(element).joined() : "")
603 let frame = frames.removeLast()
604 out += "\n<text:list-item>\n\(body)\n\(frame.header ? "</text:list-header>" : "</text:list-item>")"
605 if siblings.last?.range == node.range { out += "</text:list>" }
606 return out
607 }
608
609 // MARK: - Paragraphs
610
611 private enum Container { case quote, center }
612 /// The quote or center block paragraphs are in.
613 private var container: Container?
614 /// Paragraph styles outside, in a center block and in a quote block.
615 private var paragraphStyles = ("Text_20_body", "OrgCenter", "Quotations")
616 /// Rendering a paragraph that is only an image link.
617 private var standalone = false
618
619 private func paragraph(_ node: SyntaxNode, prefix: String = "", style: String? = nil) -> String {
620 let named = style ?? paragraphStyles.0
621 let chosen = container == .quote ? paragraphStyles.2 : container == .center ? paragraphStyles.1 : named
622 standalone = soleImage(node) != nil
623 defer { standalone = false }
624 imageKey = base + node.range.lowerBound
625 imageCaptioned = affiliated["CAPTION"] != nil || affiliated["NAME"] != nil
626 imageCaption = affiliated["CAPTION"]
627 imageAttributes = affiliated["ATTR_ODT"]
628 defer { imageKey = nil; imageCaptioned = false; imageCaption = nil; imageAttributes = nil }
629 var contents = inline(node)
630 // The paragraph's own last newline isn't a line break.
631 if preserveBreaks, node.text.hasSuffix("\n"), node.text.range(of: "\\\\\\\\[ \t]*\n$", options: .regularExpression) == nil,
632 contents.hasSuffix("<text:line-break/>") {
633 contents.removeLast("<text:line-break/>".count)
634 }
635 return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(contents.trimmingCharacters(in: .whitespacesAndNewlines))</text:p>"
636 }
637
638 /// The link of a paragraph that is only an image link.
639 private func soleImage(_ node: SyntaxNode) -> SyntaxNode? {
640 let links = node.children.filter { $0.kind == .link }
641 guard links.count == 1, node.children.count == 1,
642 node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }),
643 links[0].firstChild(.linkDescription) == nil,
644 let file = Self.linkPath(links[0]).flatMap(Self.filePath), Self.isImage(file) else { return nil }
645 return links[0]
646 }
647
648 private func keyword(_ node: SyntaxNode) -> String {
649 guard let m = node.text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) else { return "" }
650 let value = String(m.2)
651 switch m.1.uppercased() {
652 case "ODT":
653 return value
654 case "TOC":
655 guard value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil else { return "" }
656 let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) } ?? options.headlineLevels
657 if value.range(of: ":target", options: .caseInsensitive) != nil { return fail("ODT export doesn't support #+TOC with :target") }
658 let local = value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil
659 return toc(depth: depth, scope: local ? currentHeading() : nil, local: local)
660 case "PRINT_BIBLIOGRAPHY":
661 guard let citations else { return "" }
662 return citations.bibliography.map { "\n<text:p text:style-name=\"Text_20_body\">" + render($0) + "</text:p>" }.joined()
663 default:
664 return ""
665 }
666 }
667
668 /// The heading whose section is being rendered.
669 private var headingStack: [Int] = []
670 private func currentHeading() -> Int? { headingStack.last }
671
672 // MARK: - Lists
673
674 /// An open list item, closed and opened again around a table; `heading` for a heading
675 /// deeper than `H`.
676 private struct Frame {
677 var style: String
678 var heading = false
679 var header = false
680 }
681
682 private var frames: [Frame] = []
683
684 private func list(_ node: SyntaxNode) -> String {
685 let items = node.children.filter { $0.kind == .item }
686 guard let first = items.first else { return "" }
687 let bullet = first.tokens.first { $0.kind == .bullet }?.text ?? "-"
688 let ordered = bullet.first.map { $0.isNumber || $0.isLetter } ?? false
689 let descriptive = !ordered && first.firstChild(.itemTag) != nil
690 let style = ordered ? "OrgNumberedList" : descriptive ? "OrgDescriptionList" : "OrgBulletedList"
691 let nested = node.parent?.kind == .item
692 var out = "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"\(nested)\">\n"
693 for item in items {
694 let box = checkbox(item)
695 if descriptive {
696 // As `org-odt--translate-description-lists`: the term in bold, the definition
697 // an item of a list inside.
698 frames.append(Frame(style: style))
699 let term = item.firstChild(.itemTag).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "(no term)"
700 var body = paragraphText(term, prefix: box, style: "Text_20_body_20_bold")
701 body += "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"true\">\n"
702 body += itemBody(item, prefix: "")
703 body += "</text:list>"
704 out += close(body, start: nil)
705 } else {
706 frames.append(Frame(style: style))
707 let counter = item.tokens.first { $0.kind == .counter }?.text.firstMatch(of: /\[@([0-9A-Za-z]+)\]/).map { String($0.1) }
708 out += closeItem(item, prefix: box, start: counter)
709 }
710 }
711 return out + "</text:list>"
712 }
713
714 private func itemBody(_ item: SyntaxNode, prefix: String) -> String {
715 frames.append(Frame(style: "OrgDescriptionList"))
716 return closeItem(item, prefix: prefix, start: nil)
717 }
718
719 /// The item's contents, the first paragraph after `prefix`, in the open frame.
720 private func closeItem(_ item: SyntaxNode, prefix: String, start: String?) -> String {
721 var body = ""
722 for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
723 body += index == 0 && child.kind == .paragraph ? paragraph(child, prefix: prefix) : element(child)
724 }
725 return close(body, start: start)
726 }
727
728 private func close(_ body: String, start: String?) -> String {
729 let frame = frames.removeLast()
730 return "\n<text:list-item\(start.map { " text:start-value=\"\($0)\"" } ?? "")>\n\(body)\n\(frame.header ? "</text:list-header>" : "</text:list-item>")"
731 }
732
733 private func paragraphText(_ content: String, prefix: String, style: String) -> String {
734 let chosen = container == .quote ? paragraphStyles.2 : container == .center ? paragraphStyles.1 : style
735 return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(content)</text:p>"
736 }
737
738 private func checkbox(_ item: SyntaxNode) -> String {
739 guard let box = item.tokens.first(where: { $0.kind == .checkbox })?.text else { return "" }
740 let mark = ["[X]": "[&#x2713;] ", "[x]": "[&#x2713;] ", "[-]": "[-] "][box] ?? "[ ] "
741 return "<text:span text:style-name=\"OrgCode\">\(mark)</text:span>"
742 }
743
744 /// `org-odt-table`'s list handling for `node`: the open lists closed, `inner` in an indented
745 /// section, the lists opened again, the innermost item as a header.
746 private func reopening(_ inner: String?, for node: SyntaxNode) -> String {
747 // ox-odt doesn't close the lists around a table in a block, and writes XML that doesn't
748 // nest.
749 if let parent = node.parent, parent.kind != .item, parent.kind != .section, frames.contains(where: { !$0.heading }) {
750 return fail("ODT export doesn't support a table in a block inside a list")
751 }
752 var closing: [String] = []
753 for frame in frames.reversed() {
754 closing.append(frame.header ? "</text:list-header>" : "</text:list-item>")
755 closing.append("</text:list>")
756 }
757 var opening: [String] = []
758 for (index, frame) in frames.enumerated() {
759 opening.append("\n<text:list text:style-name=\"\(frame.style)\" text:continue-numbering=\"true\">")
760 opening.append(index == frames.count - 1 || frame.header ? "<text:list-header>" : "<text:list-item>")
761 }
762 if !frames.isEmpty { frames[frames.count - 1].header = true }
763 let section = inner.map { inner -> String in
764 sections += 1
765 return "\n<text:section text:style-name=\"OrgIndentedSection-Level-\(closing.count / 2)\" text:name=\"Section\(sections)\">\n\(inner)\n</text:section>"
766 } ?? ""
767 return closing.joined(separator: "\n") + section + opening.joined(separator: "\n")
768 }
769
770 private var sections = 0
771
772 // MARK: - Tables
773
774 private var tableStyles: [(name: String, width: String)] = []
775 private var tableCount = 0
776
777 private func table(_ node: SyntaxNode) -> String {
778 let attributeLine = affiliated["ATTR_ODT"]
779 let attributes = attributeLine.map(Self.attributes) ?? [:]
780 if attributes["style"] != nil { return fail("ODT export doesn't support table templates (#+ATTR_ODT: :style)") }
781 let caption = label(base + node.range.lowerBound, caption: affiliated["CAPTION"])
782 let rows = node.children.filter { $0.kind == .tableRow }
783 enum Kind { case rule, special, data }
784 var cells: [[SyntaxNode]] = rows.map { $0.children.filter { $0.kind == .tableCell } }
785 var kinds: [Kind] = rows.indices.map { cells[$0].isEmpty && rows[$0].text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") ? .rule : .data }
786 func value(_ cell: SyntaxNode) -> String { cell.text.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "|")).trimmingCharacters(in: .whitespaces) }
787 // `org-export-table-has-special-column-p`.
788 let firsts = rows.indices.filter { kinds[$0] == .data }.map { cells[$0].first.map(value) ?? "" }
789 let specialColumn = firsts.contains { !$0.isEmpty } && firsts.allSatisfy { ["", "/", "#", "!", "$", "*", "_", "^"].contains($0) }
790 for r in rows.indices where kinds[r] == .data {
791 let values = cells[r].map(value)
792 let cookies = values.allSatisfy { $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil } && values.contains { !$0.isEmpty }
793 if values.first == "/" || (specialColumn && ["^", "_", "$", "!"].contains(values.first ?? "")) || cookies { kinds[r] = .special }
794 }
795 let firstValues = rows.indices.map { cells[$0].first.map(value) ?? "" }
796 if specialColumn { cells = cells.map { Array($0.dropFirst()) } }
797 let columns = rows.indices.filter { kinds[$0] != .rule }.map { cells[$0].count }.max() ?? 0
798 // Alignment and width cookies, and column groups.
799 var align = Array(repeating: "", count: columns)
800 var width = Array(repeating: 0, count: columns)
801 var groups = Array(repeating: "", count: columns)
802 for r in rows.indices where kinds[r] == .special {
803 let values = cells[r].map(value)
804 for (c, v) in values.enumerated() {
805 if let m = v.firstMatch(of: /^<([lrc])?([0-9]+)?>$/) {
806 if let a = m.1 { align[c] = String(a) }
807 if let w = m.2 { width[c] = Int(w) ?? 0 }
808 }
809 if firstValues[r] == "/" { groups[c] = v }
810 }
811 }
812 let data = rows.indices.filter { kinds[$0] == .data }
813 for c in 0..<columns where align[c].isEmpty {
814 var numbers = 0
815 var total = 0
816 var previousNumber = false
817 for r in data {
818 let v = c < cells[r].count ? value(cells[r][c]) : ""
819 total += 1
820 if TablePlot.isNumber(v) || (v.isEmpty && previousNumber) {
821 previousNumber = true
822 numbers += 1
823 } else {
824 previousNumber = false
825 }
826 }
827 align[c] = total > 0 && Double(numbers) / Double(total) >= 0.5 ? "r" : "l"
828 }
829 // Row groups: data rows between rules.
830 var group: [Int: Int] = [:]
831 var current = 1
832 var seen = false
833 for r in rows.indices {
834 if kinds[r] == .rule, seen { current += 1; seen = false }
835 if kinds[r] == .data { group[r] = current; seen = true }
836 }
837 // `org-export-table-has-header-p`: a rule between data rows; special rows don't count.
838 let firstData = data.first
839 let hasHeader = firstData.map { start in
840 guard let rule = rows.indices.first(where: { $0 > start && kinds[$0] == .rule }) else { return false }
841 return data.contains { $0 > rule }
842 } ?? false
843 let headerColumns = attributes["header-columns"].map { Int($0) ?? 1 } ?? 0
844 var body = ""
845 for (index, r) in data.enumerated() {
846 let previous = rows.indices.reversed().first { $0 < r && kinds[$0] != .special }
847 let next = rows.indices.first { $0 > r && kinds[$0] != .special }
848 let starts = previous.map { kinds[$0] == .rule } ?? true
849 let ends = next.map { kinds[$0] == .rule } ?? true
850 let header = group[r] == 1 && hasHeader
851 if starts { body += header ? "\n<table:table-header-rows>" : "\n<table:table-rows>" }
852 var row = ""
853 for c in 0..<columns {
854 let cell = c < cells[r].count ? cells[r][c] : nil
855 let startsGroup = c == 0 || ["<", "<>"].contains(groups[c]) || [">", "<>"].contains(groups[c - 1])
856 let style = "OrgTblCell" + (starts || index == 0 ? "T" : "") + (ends ? "B" : "") + (startsGroup && c != 0 ? "L" : "")
857 let paragraph = (header || c < headerColumns ? "OrgTableHeading" : "OrgTableContents") + ["l": "Left", "r": "Right", "c": "Center"][align[c]]!
858 let span = width[c]
859 row += "\n<table:table-cell table:style-name=\"\(style)\"\(span > 0 ? " table:number-columns-spanned=\"\(span + 1)\"" : "")>\n"
860 row += "\n<text:p text:style-name=\"\(paragraph)\">\(cell.map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "")</text:p>"
861 row += "\n</table:table-cell>" + String(repeating: "\n<table:covered-table-cell/>", count: span) + "\n"
862 }
863 body += "\n<table:table-row>\n\(row)\n</table:table-row>"
864 if ends { body += header ? "\n</table:table-header-rows>" : "\n</table:table-rows>" }
865 }
866 // Every table counts toward the automatic style names, given only with `#+ATTR_ODT`.
867 tableCount += 1
868 var style = "OrgTable"
869 if attributeLine != nil {
870 style = "OrgTable\(tableCount)"
871 tableStyles.append((style, attributes["rel-width"] ?? "96"))
872 }
873 let firstRow = data.first.map { cells[$0] } ?? []
874 let columnSpecs = firstRow.indices.map { c in
875 String(repeating: "\n<table:table-column table:style-name=\"OrgTableColumn\"/>", count: (c < width.count ? width[c] : 0) + 1)
876 }.joined(separator: "\n")
877 var out = caption.map { "\n<text:p text:style-name=\"Table\">\($0)</text:p>" } ?? ""
878 out += "\n<table:table table:style-name=\"\(style)\">" + columnSpecs + "\n" + body + "</table:table>"
879 return "\n" + reopening(out, for: node)
880 }
881
882 /// `org-odt-format-label` as a definition: a bookmark, then the category, sequence number
883 /// and caption; nil without a caption or name.
884 private func label(_ key: Int, caption: String?) -> String? {
885 guard let label = labels[key] else { return nil }
886 let reference = label.reference ?? "nil"
887 let category = ExportDictionary.translate(label.category, language: language, encoding: .utf8)
888 let number = "<text:sequence text:ref-name=\"\(reference)\" text:name=\"\(label.variable)\" text:formula=\"ooow:\(label.variable)+1\" style:num-format=\"1\">\(label.sequence)</text:sequence>"
889 let format = ExportDictionary.translate("%e %n: %c", language: language, encoding: .utf8)
890 let text = format.replacingOccurrences(of: "%e", with: category).replacingOccurrences(of: "%n", with: number)
891 .replacingOccurrences(of: "%c", with: caption.map(inlineString) ?? "")
892 return "\n<text:bookmark text:name=\"\(reference)\"/>" + text
893 }
894
895 // MARK: - Blocks
896
897 /// A block's type, parameters, its first line and its contents with their offset in the block.
898 static func blockParts(_ node: SyntaxNode) -> (type: String, parameters: String, lines: [String], body: (text: String, offset: Int)) {
899 var lines = node.text.components(separatedBy: "\n")
900 if lines.last == "" { lines.removeLast() }
901 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return ("", "", lines, ("", 0)) }
902 let body = lines.dropFirst().dropLast().map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
903 return (m.1.lowercased(), String(m.2), lines, (body.joined(separator: "\n"), first.utf16.count + 1))
904 }
905
906 private func block(_ node: SyntaxNode) -> String {
907 let (type, parameters, lines, body) = Self.blockParts(node)
908 guard !lines.isEmpty, !type.isEmpty else { return "" }
909 let key = base + node.range.lowerBound
910 let unescaped = body.text.isEmpty && lines.count <= 2 ? [] : body.text.components(separatedBy: "\n")
911 switch type {
912 case "src":
913 let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? ""
914 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
915 let language = parameters.split(whereSeparator: \.isWhitespace).first.map(String.init).flatMap { $0.hasPrefix("-") || $0.hasPrefix(":") ? nil : $0 }
916 // Babel rewrites the block, which empties lines of only blanks unless `-i` keeps
917 // the indentation.
918 let preserve = Coderef.block(lines)?.switches.preserveIndent ?? false
919 let kept = preserve ? unescaped : unescaped.map { $0.allSatisfy { $0 == " " || $0 == "\t" } ? "" : $0 }
920 let formatted = numbered(lines, Self.dedent(kept), fontified: language.map(ODTSourceModes.fontified) ?? true)
921 if let textbox = attributes["textbox"], textbox != "nil" {
922 return caption + "\n<text:p text:style-name=\"Text_20_body\">\(self.textbox(formatted, width: nil, height: nil, style: nil, extra: nil, anchor: nil))</text:p>"
923 }
924 return caption + formatted
925 case "example":
926 return numbered(lines, Self.dedent(unescaped))
927 case "quote", "center":
928 let saved = container
929 container = type == "quote" ? .quote : .center
930 defer { container = saved }
931 return blocks(body.text, base: key + body.offset)
932 case "verse":
933 let rendered = unescaped.map { line -> String in
934 inlineString(line, verse: true).replacingOccurrences(of: "[ \\t]+$", with: "", options: .regularExpression)
935 }
936 var out = rendered.map { $0 + "<text:line-break/>" }.joined()
937 if let indent = out.firstMatch(of: /^[ \t]+/) {
938 out = Self.encodeSpaces(String(indent.output)) + out[indent.range.upperBound...]
939 }
940 return "\n<text:p text:style-name=\"OrgVerse\">\(out)</text:p>"
941 case "export":
942 return parameters.split(separator: " ").first?.lowercased() == "odt" ? Self.dedent(unescaped).joined(separator: "\n") : ""
943 case "comment":
944 return ""
945 default:
946 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
947 let contents = blocks(body.text, base: key + body.offset)
948 switch type {
949 case "textbox":
950 let size = { (key: String) in attributes[key].flatMap(Double.init) }
951 return "\n<text:p text:style-name=\"Text_20_body\">\(textbox(contents, width: size("width"), height: size("height"), style: attributes["style"], extra: attributes["extra"], anchor: attributes["anchor"]))</text:p>"
952 case "annotation":
953 if attributes["date"] != nil || dated { return fail("ODT export doesn't support dated annotations") }
954 let author = attributes["author"].map { Self.escape($0) } ?? author
955 return "\n<text:p><office:annotation>\n\(author.map { "<dc:creator>\($0)</dc:creator>" } ?? "")\(contents)\n</office:annotation></text:p>"
956 default:
957 return contents
958 }
959 }
960 }
961
962 /// The code of a src or example block, labels and numbers as its switches ask.
963 private func numbered(_ block: [String], _ body: [String], fontified: Bool = true) -> String {
964 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
965 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
966 let key = block.joined(separator: "\n")
967 let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
968 return code(lines, refs: refs, retain: switches.retainLabels, loc: switches.numberLines == nil ? nil : loc, fontified: fontified)
969 }
970
971 /// `org-odt-do-format-code`: one paragraph per line. From the line `org-split-string`
972 /// counts as the last, which leaves out a leading and a trailing empty line, the style is
973 /// the last line's. Without a mode for the language, no fontifying: another style and
974 /// spaces encoded as in text.
975 private func code(_ lines: [String], refs: [Int: String] = [:], retain: Bool = false, loc: Int? = nil, emptyLast: Bool = false, fontified: Bool = true) -> String {
976 let lines = emptyLast ? lines + [""] : lines
977 let joined = lines.joined(separator: "\n")
978 let last = lines.count - (joined.hasPrefix("\n") ? 1 : 0) - (joined.hasSuffix("\n") ? 1 : 0)
979 let style = fontified ? "OrgSrcBlock" : "OrgFixedWidthBlock"
980 let out = lines.enumerated().map { index, line -> String in
981 var text = line
982 if let ref = refs[index + 1], retain { text += " (\(ref))" }
983 var encoded = fontified
984 ? Self.escape(text, quotes: true).replacingOccurrences(of: " ", with: "<text:s/>").replacingOccurrences(of: "\t", with: "<text:tab/>")
985 : Self.encodeSpaces(Self.escape(text))
986 if let ref = refs[index + 1] { encoded = Self.target(encoded, "coderef-" + ref) }
987 let paragraph = "\n<text:p text:style-name=\"\(style)\(last > 0 && index >= last - 1 ? "LastLine" : "")\">\(encoded)</text:p>"
988 return loc == nil ? paragraph : "\n<text:list-item>\(paragraph)\n</text:list-item>"
989 }.joined()
990 guard let loc else { return out }
991 return "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\" text:continue-numbering=\"\(loc != 0)\">\(out)</text:list>"
992 }
993
994 static func dedent(_ lines: [String]) -> [String] {
995 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
996 let common = indents.min() ?? 0
997 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
998 }
999
1000 // MARK: - Frames
1001
1002 private var frameCount = 0
1003
1004 /// `org-odt--frame`.
1005 private func frame(_ text: String, width: Double?, height: Double?, style: String?, extra: String?, anchor: String?) -> String {
1006 frameCount += 1
1007 var attributes = width.map { String(format: " svg:width=\"%0.2fcm\"", $0) } ?? ""
1008 attributes += height.map { String(format: " svg:height=\"%0.2fcm\"", $0) } ?? ""
1009 attributes += (extra ?? "") + " text:anchor-type=\"\(anchor ?? "paragraph")\" draw:name=\"Frame\(frameCount)\""
1010 return "\n<draw:frame draw:style-name=\"\(style ?? "nil")\"\(attributes)>\n\(text)\n</draw:frame>"
1011 }
1012
1013 /// `org-odt--textbox`.
1014 private func textbox(_ text: String, width: Double?, height: Double?, style: String?, extra: String?, anchor: String?) -> String {
1015 let box = String(format: " fo:min-height=\"%0.2fcm\"", height ?? 0.2) + (width == nil ? String(format: " fo:min-width=\"%0.2fcm\"", 0.2) : "")
1016 return frame("\n<draw:text-box \(box)>\(text)\n</draw:text-box>", width: width, height: nil, style: style, extra: extra, anchor: anchor)
1017 }
1018
1019 // MARK: - Images
1020
1021 /// The paragraph holding the image being rendered, and its caption and attributes.
1022 private var imageKey: Int?
1023 private var imageCaptioned = false
1024 private var imageCaption: String?
1025 private var imageAttributes: String?
1026
1027 /// A bracket link's path, or a plain or angle `file:` link's.
1028 static func linkPath(_ node: SyntaxNode) -> String? {
1029 if let token = node.tokens.first(where: { $0.kind == .linkPath }) { return token.text }
1030 var text = node.text
1031 if text.hasPrefix("<"), text.hasSuffix(">") { text = String(text.dropFirst().dropLast()) }
1032 return text.hasPrefix("file:") ? text : nil
1033 }
1034
1035 /// A link's file, for `file:` links and paths Org reads as files.
1036 static func filePath(_ path: String) -> String? {
1037 var file: String
1038 if path.hasPrefix("file:") {
1039 file = String(path.dropFirst(5))
1040 } else if ["/", "./", "../", "~/"].contains(where: path.hasPrefix) {
1041 file = path
1042 } else {
1043 return nil
1044 }
1045 if let range = file.range(of: "::") { file = String(file[..<range.lowerBound]) }
1046 return file
1047 }
1048
1049 /// `org-export-insert-image-links`: the image a link's description shows, if it is one.
1050 static func describedImage(_ description: SyntaxNode) -> String? {
1051 filePath(description.text.trimmingCharacters(in: .whitespaces).replacing(/^\[\[(.*)\]\]$/) { String($0.1) }).flatMap { isImage($0) ? $0 : nil }
1052 }
1053
1054 static func isImage(_ file: String) -> Bool {
1055 file.range(of: "\\.(jpeg|jpg|png|gif|svg)", options: [.regularExpression, .caseInsensitive]) != nil
1056 }
1057
1058 static func expand(_ file: String, directory: URL) -> URL {
1059 let path = OrgPaths.expandingTilde(file)
1060 return path.hasPrefix("/") ? URL(fileURLWithPath: path) : directory.appendingPathComponent(path).standardizedFileURL
1061 }
1062
1063 /// `org-odt-link--inline-image`: the file embedded under `Images/`, sized from its pixels
1064 /// at 96 dpi or `#+ATTR_ODT`, within 17 by 20 cm.
1065 private func image(_ file: String) -> String {
1066 let url = Self.expand(file, directory: directory)
1067 guard let data = try? Data(contentsOf: url) else { return fail("Opening input file: No such file or directory, \(url.path)") }
1068 let ext = (file as NSString).pathExtension
1069 let name = String(format: "Images/%04d.%@", images.count + 1, ext)
1070 images.append((name, data))
1071 let attributes = imageAttributes.map(Self.attributes) ?? [:]
1072 let user = { (key: String) in attributes[key].flatMap(Double.init) }
1073 let scale = user("scale")
1074 let userWidth = scale == nil ? user("width") : nil
1075 let userHeight = scale == nil ? user("length") : nil
1076 var size = (width: 5.0, height: 5.0)
1077 if userWidth == nil || userHeight == nil {
1078 if let source = CGImageSourceCreateWithData(data as CFData, nil),
1079 let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
1080 let w = properties[kCGImagePropertyPixelWidth] as? Double, let h = properties[kCGImagePropertyPixelHeight] as? Double {
1081 size = (w / 96 * 2.54, h / 96 * 2.54)
1082 }
1083 }
1084 if let scale {
1085 size = (size.width * scale, size.height * scale)
1086 } else if let userWidth, let userHeight {
1087 size = (userWidth, userHeight)
1088 } else if let userHeight {
1089 size = (userHeight * size.width / size.height, userHeight)
1090 } else if let userWidth {
1091 size = (userWidth, userWidth * size.height / size.width)
1092 }
1093 if size.width > 17 || size.height > 20 {
1094 let factor = min(17 / size.width, 20 / size.height)
1095 size = (size.width * factor, size.height * factor)
1096 }
1097 let href = "\n<draw:image xlink:href=\"\(name)\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
1098 if !standalone, imageCaptioned { return fail("Don't know how to format label for an image inside text") }
1099 let caption = standalone ? imageKey.flatMap { label($0, caption: imageCaption) } : nil
1100 guard let caption else {
1101 return frame(href, width: size.width, height: size.height, style: standalone ? "OrgDisplayImage" : "OrgInlineImage", extra: nil, anchor: standalone ? "paragraph" : "as-char")
1102 }
1103 let inner = frame(href, width: size.width, height: size.height, style: "OrgCaptionedImage", extra: " style:rel-width=\"100%\" style:rel-height=\"scale\"", anchor: "paragraph")
1104 return textbox("\n<text:p text:style-name=\"Illustration\">\(inner)\(caption)</text:p>", width: size.width, height: size.height, style: "OrgImageCaptionFrame", extra: nil, anchor: "paragraph")
1105 }
1106
1107 // MARK: - Inline
1108
1109 func inline(_ node: SyntaxNode) -> String {
1110 afterFootnote = false
1111 var out = ""
1112 var text = ""
1113 // A line break object takes the newline after it, as Org's does.
1114 var afterBreak = false
1115 for element in node.elements {
1116 switch element {
1117 case .token(let token):
1118 switch token.kind {
1119 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1120 continue
1121 default:
1122 text += afterBreak && text.isEmpty && token.text.hasPrefix("\n") ? String(token.text.dropFirst()) : token.text
1123 afterBreak = false
1124 }
1125 case .node(let child):
1126 if !text.isEmpty { afterFootnote = false }
1127 out += plainText(text)
1128 text = ""
1129 out += object(child)
1130 afterBreak = child.kind == .lineBreak
1131 }
1132 }
1133 if !text.isEmpty { afterFootnote = false }
1134 return out + plainText(text)
1135 }
1136
1137 private var verse = false
1138
1139 private func inlineString(_ text: String, verse: Bool) -> String {
1140 let saved = self.verse
1141 self.verse = verse
1142 defer { self.verse = saved }
1143 let tree = OrgParser.parse(text, defaults: settings)
1144 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
1145 return rendering(tree, text) { inline(paragraph) }
1146 }
1147
1148 static let textObjects = HTMLRenderer.textObjects
1149
1150 /// `org-odt-plain-text`, with the LaTeX fragments, entities and scripts the parser leaves in
1151 /// text.
1152 private func plainText(_ text: String) -> String {
1153 guard !text.isEmpty else { return "" }
1154 let ns = text as NSString
1155 var out = ""
1156 var at = 0
1157 for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
1158 out += plain(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
1159 at = NSMaxRange(m.range)
1160 let whole = ns.substring(with: m.range)
1161 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
1162 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
1163 if options.tex { out += "<text:span text:style-name=\"OrgCode\">\(Self.escape(whole))</text:span>" }
1164 } else if let name = group(5) {
1165 out += withEntities ? OrgEntities.display[name].map { Self.escape($0) } ?? plain(whole) : plain(whole)
1166 } else if let marker = group(7), let body = group(8) {
1167 let braced = body.hasPrefix("{")
1168 if options.scripts == .off || (options.scripts == .braces && !braced) {
1169 out += plain(whole)
1170 continue
1171 }
1172 let inner = braced ? String(body.dropFirst().dropLast()) : body
1173 out += "<text:span text:style-name=\"\(marker == "_" ? "OrgSubscript" : "OrgSuperscript")\">\(plain(inner))</text:span>"
1174 } else {
1175 out += plain(whole)
1176 }
1177 }
1178 return out + plain(ns.substring(from: at))
1179 }
1180
1181 /// Escaped text with special strings, its line breaks as spaces outside verse, or as line
1182 /// breaks with `\\n`.
1183 private func plain(_ text: String) -> String {
1184 var out = Self.escape(text)
1185 if options.specialStrings {
1186 out = out.replacingOccurrences(of: "\\\\-", with: "&#x00ad;", options: .regularExpression)
1187 .replacingOccurrences(of: "---([^-])", with: "&#x2014;$1", options: .regularExpression)
1188 .replacingOccurrences(of: "--([^-])", with: "&#x2013;$1", options: .regularExpression)
1189 .replacingOccurrences(of: "...", with: "&#x2026;")
1190 }
1191 if verse { return out }
1192 if preserveBreaks { return out.replacingOccurrences(of: "[ \t]*\n", with: "<text:line-break/>", options: .regularExpression) }
1193 return out.replacingOccurrences(of: "\n", with: " ")
1194 }
1195
1196 private func span(_ style: String, _ content: String) -> String {
1197 "<text:span text:style-name=\"\(style)\">\(content)</text:span>"
1198 }
1199
1200 /// The previous object was a footnote reference, for the comma between two.
1201 private var afterFootnote = false
1202
1203 private func object(_ node: SyntaxNode) -> String {
1204 defer { afterFootnote = node.kind == .footnoteReference && !tocEntry }
1205 switch node.kind {
1206 case .bold: return span("Bold", inline(node))
1207 case .italic: return span("Emphasis", inline(node))
1208 case .underline: return span("Underline", inline(node))
1209 case .strikeThrough: return span("Strikethrough", inline(node))
1210 case .verbatim, .code:
1211 let value = node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1212 return span("OrgCode", Self.encodeSpaces(Self.escape(value)))
1213 case .link: return link(node)
1214 case .linkDescription: return inline(node)
1215 case .timestamp:
1216 let text = node.text.trimmingCharacters(in: .whitespaces)
1217 if text.hasPrefix("<%%") { return plain(text) }
1218 return span(text.hasPrefix("<") ? "OrgActiveTimestamp" : "OrgInactiveTimestamp", plain(text))
1219 case .footnoteReference:
1220 if tocEntry || !withFootnotes { return "" }
1221 let comma = afterFootnote ? span("OrgSuperscript", ",") : ""
1222 return comma + footnote(node)
1223 case .entity:
1224 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
1225 return withEntities ? OrgEntities.display[name].map { Self.escape($0) } ?? plain(node.text) : plain(node.text)
1226 case .radioTarget:
1227 let inner = plain(String(node.text.dropFirst(3).dropLast(3)))
1228 if tocEntry { return inner }
1229 return Self.target(inner, targets.first { $0.key == base + node.range.lowerBound }?.reference ?? "nil")
1230 case .target:
1231 if tocEntry { return "" }
1232 return Self.target("", targets.first { $0.key == base + node.range.lowerBound }?.reference ?? "nil")
1233 case .superscript, .subscript:
1234 let text = node.text
1235 let body = text.dropFirst()
1236 let braced = body.hasPrefix("{") && body.hasSuffix("}")
1237 if options.scripts == .off || (options.scripts == .braces && !braced) { return plain(text) }
1238 let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
1239 return span(text.hasPrefix("_") ? "OrgSubscript" : "OrgSuperscript", plain(inner))
1240 case .lineBreak: return "<text:line-break/>"
1241 case .macro:
1242 guard case .some(let value) = source?.resultsMacro(node) else { return "" }
1243 return value.map(inlineString) ?? ""
1244 case .inlineSourceBlock:
1245 let exports = source?.exports(at: node.range.lowerBound) ?? "results"
1246 source?.inlineResults = exports == "results" || exports == "both"
1247 guard exports == "code" || exports == "both" else { return "" }
1248 // ox-odt has no transcoder for them.
1249 return fail("ODT export doesn't support inline source blocks")
1250 case .latexFragment:
1251 guard options.tex else { return "" }
1252 return span("OrgCode", Self.escape(node.text))
1253 case .statisticsCookie: return span("OrgCode", Self.escape(node.text))
1254 case .exportSnippet:
1255 guard node.tokens.first?.text.lowercased() == "@@odt:" else { return "" }
1256 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1257 case .citation:
1258 if inTitle { return "" }
1259 guard let pieces = citations?.next(node.text) else { return plain(node.text) }
1260 return render(pieces)
1261 case .inlineBabelCall:
1262 source?.inlineResults = (source?.exports(at: node.range.lowerBound) ?? "results") == "results"
1263 return ""
1264 default: return inline(node)
1265 }
1266 }
1267
1268 /// A citation's or a bibliography entry's pieces.
1269 private func render(_ pieces: [CiteProcessor.Piece]) -> String {
1270 pieces.map { piece in
1271 switch piece {
1272 case .text(let s): plain(s)
1273 case .italic(let s): span("Emphasis", plain(s))
1274 case .org(let s) where s.allSatisfy(\.isWhitespace): s
1275 case .org(let s):
1276 String(s.prefix { $0.isWhitespace }) + inlineString(s) + String(s.reversed().prefix { $0.isWhitespace })
1277 }
1278 }.joined()
1279 }
1280
1281 // MARK: - Footnotes
1282
1283 /// Numbers by footnote, a label or `@` and an anonymous reference's place, and the place
1284 /// of each one's first reference.
1285 private var footnoteNumbers: [String: Int] = [:]
1286 private var firstReferences: [String: Int] = [:]
1287
1288 /// The passes that number footnotes as ox-odt does, `org-export-get-footnote-number` with
1289 /// BODY-FIRST: the references in the body in order, then those in the definitions of
1290 /// these, each definition entered at its first reference.
1291 private enum FootnotePass { case body, definitions }
1292 private var footnotePass: FootnotePass?
1293 private var referencesMet: [(id: String, key: Int)] = []
1294 private var labelsSeen: Set<String> = []
1295 private var definitionsWaiting: [(label: String?, inline: (text: String, base: Int)?)] = []
1296
1297 private func numberFootnotes(_ text: String) {
1298 let pass = ODTRenderer(settings: settings, options: options, directory: directory)
1299 pass.language = language
1300 pass.author = author
1301 pass.dated = dated
1302 pass.numbered = numbered
1303 pass.preserveBreaks = preserveBreaks
1304 pass.withTables = withTables
1305 pass.withEntities = withEntities
1306 pass.drawers = drawers
1307 pass.footnotePass = .body
1308 _ = pass.document(text)
1309 pass.footnotePass = .definitions
1310 for waiting in pass.definitionsWaiting { _ = pass.definition(label: waiting.label, inline: waiting.inline) }
1311 for reference in pass.referencesMet where footnoteNumbers[reference.id] == nil {
1312 footnoteNumbers[reference.id] = footnoteNumbers.count + 1
1313 firstReferences[reference.id] = reference.key
1314 }
1315 definitions = pass.definitions
1316 }
1317
1318 /// A footnote's definition rendered: an anonymous one's own, else the label's.
1319 private func definition(label: String?, inline: (text: String, base: Int)?) -> String? {
1320 if label == nil, let inline { return inlineDefinition(inline.text, base: inline.base) }
1321 guard let label, let found = definitions[label] else { return nil }
1322 if found.inline { return inlineDefinition(found.text, base: found.base) }
1323 return blocks(found.text, base: found.base).trimmingCharacters(in: .whitespacesAndNewlines)
1324 }
1325
1326 private func inlineDefinition(_ text: String, base: Int) -> String {
1327 let rendered = within(text, base: base) { tree -> String in
1328 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
1329 return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
1330 }
1331 return "\n<text:p text:style-name=\"Footnote\">\(rendered)</text:p>"
1332 }
1333
1334 private func footnote(_ node: SyntaxNode) -> String {
1335 let text = node.text
1336 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return plain(text) }
1337 let key = base + node.range.lowerBound
1338 let label = m.1.isEmpty ? nil : String(m.1)
1339 let id = label ?? "@\(key)"
1340 let inline = m.2.map { (text: String($0), base: key + text.utf16.distance(from: text.startIndex, to: $0.startIndex)) }
1341 if let label, let inline, definitions[label].map({ $0.base < inline.base }) ?? true {
1342 definitions[label] = (inline.text, inline.base, true)
1343 }
1344 if let pass = footnotePass {
1345 referencesMet.append((id, key))
1346 if let label, !labelsSeen.insert(label).inserted { return "" }
1347 if pass == .body {
1348 definitionsWaiting.append((label, inline))
1349 } else {
1350 _ = definition(label: label, inline: inline)
1351 }
1352 return ""
1353 }
1354 if footnoteNumbers[id] == nil {
1355 footnoteNumbers[id] = (footnoteNumbers.values.max() ?? 0) + 1
1356 firstReferences[id] = key
1357 }
1358 let n = footnoteNumbers[id]!
1359 if label != nil, firstReferences[id] != key {
1360 return span("OrgSuperscript", "<text:note-ref text:note-class=\"footnote\" text:reference-format=\"text\" text:ref-name=\"fn\(n)\">\(n)</text:note-ref>")
1361 }
1362 let saved = (paragraphStyles, container, frames, afterFootnote)
1363 paragraphStyles = ("Footnote", "OrgFootnoteCenter", "OrgFootnoteQuotations")
1364 container = nil
1365 frames = []
1366 defer { (paragraphStyles, container, frames, afterFootnote) = saved }
1367 guard let definition = definition(label: label, inline: inline) else { return fail("Definition not found for footnote \(m.1)") }
1368 return "<text:note text:id=\"fn\(n)\" text:note-class=\"footnote\"><text:note-citation>\(n)</text:note-citation><text:note-body>\(definition)</text:note-body></text:note>"
1369 }
1370
1371 // MARK: - Links
1372
1373 private enum Destination {
1374 case heading(Heading)
1375 case target(String)
1376 case element(Int)
1377 }
1378
1379 private func titleWords(_ heading: Heading) -> [String] {
1380 let title = heading.info?.title ?? heading.node.firstChild(.title)?.text ?? ""
1381 return Self.words(title.replacingOccurrences(of: "\\[[0-9]*(%|/[0-9]*)\\]", with: " ", options: .regularExpression).uppercased())
1382 }
1383
1384 /// `org-export-resolve-fuzzy-link`: a target or name first, else the last heading with the
1385 /// title.
1386 private func resolve(_ path: String) -> Destination? {
1387 let all = headingOrder.compactMap { headings[$0] }
1388 if path.hasPrefix("*") {
1389 let words = Self.words(String(path.dropFirst()).uppercased())
1390 return all.last { titleWords($0) == words }.map(Destination.heading)
1391 }
1392 if path.hasPrefix("#") {
1393 let id = String(path.dropFirst())
1394 return all.last { $0.info?.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value == id }.map(Destination.heading)
1395 }
1396 let words = Self.words(path)
1397 let upper = words.map { $0.uppercased() }
1398 if let name = names.last(where: { $0.words == words }) { return .element(name.key) }
1399 if let target = targets.last(where: { $0.words == upper }) { return .target(target.reference) }
1400 if let name = names.last(where: { $0.words == upper }) { return .element(name.key) }
1401 return all.last { titleWords($0) == upper }.map(Destination.heading)
1402 }
1403
1404 private func link(_ node: SyntaxNode) -> String {
1405 let path = Self.linkPath(node)
1406 let descriptionNode = node.firstChild(.linkDescription)
1407 var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 }
1408 // `org-export-insert-image-links`: a description that is an image's path shows it.
1409 let describedImage = descriptionNode.flatMap(Self.describedImage)
1410 if let describedImage, !tocEntry { description = image(describedImage) }
1411 guard let path else {
1412 // A radio link refers to its target.
1413 if !node.text.hasPrefix("<"), !node.text.contains(":") {
1414 let words = Self.words(node.text.uppercased())
1415 let text = plain(node.text)
1416 if tocEntry { return text }
1417 guard let target = targets.first(where: { $0.words == words }) else { return text }
1418 return "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.\(target.reference)\">\(text)</text:bookmark-ref>"
1419 }
1420 var target = node.text
1421 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
1422 if tocEntry { return plain(target) }
1423 return external(target, description: nil)
1424 }
1425 if tocEntry { return description ?? plain(path) }
1426 if let file = Self.filePath(path) {
1427 if description == nil, Self.isImage(file) { return image(file) }
1428 let uri = file.hasPrefix("/") || file.hasPrefix("~") ? "file://" + OrgPaths.expandingTilde(file) : "../" + file
1429 return external(uri, description: description, image: describedImage != nil)
1430 }
1431 // A code reference: its line's number.
1432 if path.hasPrefix("("), path.hasSuffix(")"), path.count >= 2 {
1433 let name = String(path.dropFirst().dropLast())
1434 guard let resolved = documentTree.flatMap({ Coderef.resolve(name, in: $0) }) else { return fail("Unable to resolve code reference: \(name)") }
1435 guard Int(resolved) != nil else { return fail("ODT export only resolves code references to numbered lines: \(name)") }
1436 let reference = "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.coderef-\(Self.escape(name, quotes: true))\">\(resolved)</text:bookmark-ref>"
1437 return Coderef.linkText(reference, description: description)
1438 }
1439 if let colon = path.firstIndex(of: ":"), Links.types.contains(String(path[..<colon])) {
1440 if path.hasPrefix("id:") {
1441 let id = String(path.dropFirst(3))
1442 guard let heading = headingOrder.compactMap({ headings[$0] }).first(where: { $0.info?.id == id }) else { return fail("Unable to resolve link: \"\(id)\"") }
1443 return toHeading(heading, description: description, customID: nil)
1444 }
1445 return external(path, description: description, image: describedImage != nil)
1446 }
1447 let search = path
1448 guard let destination = resolve(search) else { return fail("Unable to resolve link: \"\(search)\"") }
1449 switch destination {
1450 case .heading(let heading):
1451 return toHeading(heading, description: description, customID: search.hasPrefix("#") ? String(search.dropFirst()) : nil)
1452 case .target(let reference):
1453 guard let description else { return fail("ODT export doesn't number links to targets without a description: \(search)") }
1454 return "<text:a xlink:type=\"simple\" xlink:href=\"#\(reference)\">\(description)</text:a>"
1455 case .element(let key):
1456 guard let label = labels[key], let reference = label.reference else { return fail("FIXME: Unable to resolve \(search)") }
1457 guard let description else {
1458 return "<text:sequence-ref text:reference-format=\"value\" text:ref-name=\"\(reference)\">\(label.sequence)</text:sequence-ref>"
1459 }
1460 return "<text:a xlink:type=\"simple\" xlink:href=\"#\(reference)\">\(description)</text:a>"
1461 }
1462 }
1463
1464 /// A hyperlink, a clickable image when the description is only an image link.
1465 private func external(_ target: String, description: String?, image: Bool = false) -> String {
1466 let href = Self.escape(target, quotes: true)
1467 if image, let description { return "\n<draw:a xlink:type=\"simple\" xlink:href=\"\(href)\">\n\(description)\n</draw:a>" }
1468 return "<text:a xlink:type=\"simple\" xlink:href=\"\(href)\">\(description ?? Self.escape(target))</text:a>"
1469 }
1470
1471 /// A link to a heading: with a description, a hyperlink; without, its number or title.
1472 private func toHeading(_ heading: Heading, description: String?, customID: String?) -> String {
1473 if let description {
1474 return "<text:a xlink:type=\"simple\" xlink:href=\"#\(Self.escape(customID ?? heading.reference, quotes: true))\">\(description)</text:a>"
1475 }
1476 let chain = (heading.ancestors + [heading.key]).compactMap { headings[$0] }
1477 if chain.dropLast().contains(where: \.lowLevel) { return fail("ODT export doesn't number links to items under a heading deeper than H") }
1478 let regular = chain.reversed().first { !$0.lowLevel }
1479 if heading.number != nil, let numbered = chain.reversed().first(where: { !$0.lowLevel && $0.number != nil }) {
1480 return "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.\(heading.reference)\">\(numbered.number!.map(String.init).joined(separator: "."))</text:bookmark-ref>"
1481 }
1482 guard let regular else { return fail("FIXME?") }
1483 let title = regular.node.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
1484 return "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.\(heading.reference)\">\(title)</text:bookmark-ref>"
1485 }
1486
1487 // MARK: - Styles
1488
1489 /// The automatic styles of tables with `#+ATTR_ODT`.
1490 func automaticStyles() -> String {
1491 tableStyles.map {
1492 "\n<style:style style:name=\"\($0.name)\" style:family=\"table\">\n <style:table-properties style:rel-width=\"\($0.width)%\" fo:margin-top=\"0cm\" fo:margin-bottom=\"0.20cm\" table:align=\"center\"/>\n</style:style>\n"
1493 }.joined()
1494 }
1495
1496 // MARK: - Text
1497
1498 /// `:key value :other "quoted value"`.
1499 static func attributes(_ text: String) -> [String: String] {
1500 var pairs: [String: String] = [:]
1501 for m in text.matches(of: /:([A-Za-z_-]+)(?:[ \t]+("[^"]*"|[^:\s]\S*))?/) {
1502 var value = m.2.map(String.init) ?? "t"
1503 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
1504 pairs[m.1.lowercased()] = value
1505 }
1506 return pairs
1507 }
1508
1509 /// `&`, `<`, `>` (and `"` with `quotes`) escaped, characters XML forbids removed.
1510 static func escape(_ s: String, quotes: Bool = false) -> String {
1511 var out = ""
1512 for c in s.unicodeScalars {
1513 switch c {
1514 case "&": out += "&amp;"
1515 case "<": out += "&lt;"
1516 case ">": out += "&gt;"
1517 case "\"" where quotes: out += "&quot;"
1518 case "\t", "\n", "\r": out.unicodeScalars.append(c)
1519 case _ where c.value < 0x20 || c.value == 0xFFFE || c.value == 0xFFFF: continue
1520 default: out.unicodeScalars.append(c)
1521 }
1522 }
1523 return out
1524 }
1525
1526 /// `org-odt--encode-tabs-and-spaces`.
1527 static func encodeSpaces(_ s: String) -> String {
1528 s.replacing(/\t| {2,}/) { m in m.output == "\t" ? "<text:tab/>" : " <text:s text:c=\"\(m.output.count - 1)\"/>" }
1529 }
1530
1531 /// Rendered markup without its elements, for `meta.xml`.
1532 static func stripped(_ xml: String) -> String {
1533 xml.replacingOccurrences(of: "<[^>]*>", with: "", options: .regularExpression)
1534 }
1535}
Sources/OrgCore/Export/ODTSourceModes.swift added +90
@@ -0,0 +1,90 @@
1/// The names `NAME-mode` is a function for in `emacs -Q` (Emacs 31.1, Org 9.8.7, ox-odt
2/// loaded): the source block languages ox-odt fontifies, after `org-src-lang-modes`.
3enum ODTSourceModes {
4 static func fontified(_ language: String) -> Bool {
5 modes.contains(langModes[language] ?? language)
6 }
7
8 /// `org-src-lang-modes`.
9 static let langModes: [String: String] = [
10 "C": "c", "C++": "c++", "asymptote": "asy", "beamer": "latex", "calc": "fundamental", "cpp": "c++",
11 "ditaa": "artist", "desktop": "conf-desktop", "dot": "graphviz-dot", "elisp": "emacs-lisp",
12 "ocaml": "tuareg", "screen": "shell-script", "sqlite": "sql", "toml": "conf-toml", "shell": "sh",
13 "ash": "sh", "sh": "sh", "bash": "sh", "jsh": "sh", "bash2": "sh", "dash": "sh", "dtksh": "sh",
14 "ksh": "sh", "es": "sh", "rc": "sh", "itcsh": "sh", "tcsh": "sh", "jcsh": "sh", "csh": "sh",
15 "ksh88": "sh", "oash": "sh", "pdksh": "sh", "mksh": "sh", "posix": "sh", "wksh": "sh", "wsh": "sh",
16 "zsh": "sh", "rpm": "sh",
17 ]
18
19 static let modes: Set<String> = Set("""
20 *table--cell-describe Buffer-menu Buffer-menu-group-by Info LaTeX TeX abbrev add-minor allout
21 allout-widgets antlr antlr-v4 archive array artist asm authinfo auto-composition auto-compression
22 auto-encryption auto-fill auto-image-file auto-insert auto-lower auto-raise auto-revert
23 auto-revert-tail auto-save auto-save-visited autoconf awk bash-ts bat bibtex bibtex-style
24 binary-overwrite blink-cursor bovine-grammar buffer-face bug-reference bug-reference-prog button c
25 c++ c++-ts c-initialize-cc c-or-c++ c-or-c++-ts c-ts calendar capitalized-words center-line
26 cfengine-auto cfengine2 cfengine3 change-log checkdoc-minor cl-font-lock-built-in
27 cl-old-struct-compat clean cmake-ts column-number comint comint-fontify-input common-lisp compilation
28 compilation-minor compilation-shell-minor completion-in-region completion-list completion-preview
29 conf conf-colon conf-desktop conf-javaprop conf-npmrc conf-ppd conf-space conf-toml conf-unix
30 conf-windows conf-xdefaults context-menu cperl csharp csharp-ts css css-ts cua cua-rectangle-mark
31 cua-selection current-input cursor-face-highlight cursor-intangible cursor-sensor custom-group-of
32 custom-set-minor customize cvs-status cwarn dcl decipher delete-selection delete-selection-local
33 delete-trailing-whitespace delphi describe describe-minor desktop-save diary dictionary
34 dictionary-tooltip diff diff-minor dired dirtrack display-battery display-fill-column-indicator
35 display-line-numbers display-time dns doc-view doc-view-minor dockerfile-ts doctex double dsssl
36 dynamic-completion ebrowse-member ebrowse-tree edit-abbrevs editorconfig editorconfig-conf eldoc
37 electric-indent electric-indent-local electric-layout electric-layout-local electric-pair
38 electric-pair-local electric-quote electric-quote-local elide-head elisp-byte-code elixir-ts
39 emacs-authors emacs-lisp emacs-lock emacs-news emacs-news-view enriched epa-global-mail epa-mail erts
40 eshell etags-regen etc-authors eww f90 fido fido-vertical file-name-shadow find-function flymake
41 flyspell flyspell-prog follow font-lock font-lock-change font-lock-value-in-major footnote forms
42 fortran frame--current-background frame--current-backround frame-set-background
43 frame-terminal-default-bg fundamental gdb-script generic glasses global-auto-composition
44 global-auto-revert global-completion-preview global-cwarn global-dictionary-tooltip
45 global-display-fill-column-indicator global-display-line-numbers global-ede global-eldoc
46 global-font-lock global-goto-address global-hi-lock global-highlight-changes global-hl-line
47 global-prettify-symbols global-reveal global-so-long global-subword global-superword global-tab-line
48 global-visual-line global-visual-wrap-prefix global-whitespace global-whitespace-newline
49 global-window-tool-bar global-word-wrap-whitespace global-xref-mouse glyphless-display
50 gnus-mailing-list gnus-score go-mod-ts go-ts go-work-ts goto-address goto-address-prog gpm-mouse grep
51 gud-tooltip header-line-indent heex-ts help hexl hi-lock hide-ifdef highlight-changes
52 highlight-changes-visible hl-line hs-indentation hs-minor html html-ts icalendar icomplete
53 icomplete-vertical icon idl ido iimage image image-dired-minor image-minor indent-according-to
54 indent-tabs indented-text isearch isearch--describe-regexp isearch--describe-word isearch-describe
55 isearch-fold-quotes ispell-minor iswitchb java java-ts javascript jit-lock jit-lock-debug js js-base
56 js-json js-jsx js-ts json-ts kill-ring-deindent latex ld-script less-css line-number lisp lisp-data
57 lisp-interaction lock-file log-view lost-selection lua lua-ts m2 m4 mail mail-abbrevs makefile
58 makefile-automake makefile-bsdmake makefile-gmake makefile-imake makefile-makepp master menu-bar
59 menu-bar-display-line-numbers mercury message messages-buffer metafont metapost mh-folder mhtml
60 mhtml-ts midnight minibuffer minibuffer-depth-indicate minibuffer-electric-default
61 minibuffer-inactive minibuffer-nonselected minibuffer-regexp mixal mode-line-invisible modula-2
62 mouse-avoidance mouse-shift-adjust mouse-wheel msb next-error-follow-minor normal
63 normal-erase-is-backspace nroff nxml objc occur occur-edit octave octave-maybe opascal org org-agenda
64 org-agenda-archives org-agenda-clockreport org-agenda-entry-text org-agenda-follow org-agenda-log
65 org-babel-interpret-file org-beamer org-cdlatex org-check-for-org org-element--next org-export-stack
66 org-fontify-like-in-org org-indent org-list-checkbox-radio org-num org-run-like-in-org org-src
67 org-src-get-lang org-table-follow-field org-table-header-line orgtbl outline outline-minor overwrite
68 package-autosuggest paragraph-indent-minor paragraph-indent-text pascal pending-delete perl php-ts
69 picture pike pixel-scroll pixel-scroll-precision plain-TeX plain-tex plstore pr-toggle pr-txt
70 prettify-special-glyphs prettify-symbols process-menu prog prolog ps python python-base python-ts
71 rcirc-track-minor read-extended-command read-only recentf rectangle-mark refill reftex
72 reftex-index-phrases reftex-isearch-minor repeat reveal rmail rng-validate rst rst-minor ruby
73 ruby-base ruby-ts ruler rust-ts save-place save-place-local savehist scheme scroll-all scroll-lock
74 scss semantic server ses set-auto set-binary set-buffer-major set-input set-input-interrupt
75 set-input-meta sgml sh sh--redirect-bash-ts sh-base sh-electric-here-document shell-script show-paren
76 show-paren-local sieve simula size-indication slitex smerge snmp snmpv2 so-long so-long-minor special
77 speedbar-frame speedbar-window sql srecode-template srt strokes subword superword system-taskbar
78 tab-bar tab-bar-history tab-line tab-switcher table-fixed-width tabulated-list tags-table tar tcl
79 temp-buffer-resize tex texinfo text tildify todo todo-archive todo-filtered-items toggle-rot13
80 toggle-viper toml-ts tooltip tooltip-show-help-non transient-mark treesit--explorer-tree
81 treesit--read-major treesit-explore treesit-inspect tsx-ts tty-tip turn-off-follow
82 turn-on-auto-revert turn-on-auto-revert-tail turn-on-eldoc turn-on-follow turn-on-gnus-dired
83 turn-on-gnus-mailing-list turn-on-prettify-symbols turn-on-visual-line type-break typescript-ts
84 typescript-ts-base undelete-frame universal-argument- url-handler variable-pitch vc vc-auto-revert
85 vera verilog vhdl view viper visible visual-line visual-wrap-prefix wdired-change-to-wdired
86 which-function which-key which-key-show-full-major which-key-show-major whitespace whitespace-newline
87 whitespace-page-delimiters widget-minor windmove window-divider window-tool-bar winner wisent-grammar
88 word-wrap-whitespace xml xref-mouse xterm-mouse yaml-ts zone
89 """.split(whereSeparator: \.isWhitespace).map(String.init))
90}
Sources/OrgCore/Export/ODTTemplate.swift added +231
@@ -0,0 +1,231 @@
1import Foundation
2
3/// The parts of an `.odt` file around the exported text: the content wrapper with its
4/// automatic styles, `styles.xml` with the style names ox-odt (Org 9.8.7) uses, `meta.xml` and
5/// the manifest. Written here rather than taken from ox-odt's templates.
6enum ODTTemplate {
7 static let mimetype = "application/vnd.oasis.opendocument.text"
8
9 static let namespaces = """
10 xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
11 xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
12 xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
13 xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
14 xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
15 xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
16 xmlns:xlink="http://www.w3.org/1999/xlink"
17 xmlns:dc="http://purl.org/dc/elements/1.1/"
18 xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"
19 xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"
20 xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
21 xmlns:ooow="http://openoffice.org/2004/writer"
22 office:version="1.2"
23 """
24
25 /// `content.xml`: table cell borders by row and column group, indented sections for tables
26 /// in lists, then `body`.
27 static func content(automaticStyles: String, body: String) -> String {
28 let border = "0.002cm solid #000000"
29 var styles = """
30 <style:style style:name="OrgTable" style:family="table">
31 <style:table-properties style:rel-width="96%" fo:margin-top="0cm" fo:margin-bottom="0.20cm" table:align="center"/>
32 </style:style>
33 <style:style style:name="OrgTableColumn" style:family="table-column">
34 <style:table-column-properties style:rel-column-width="1*"/>
35 </style:style>
36 <style:style style:name="OrgIndexSection" style:family="section">
37 <style:section-properties fo:background-color="#c0c0c0" style:editable="false"/>
38 </style:style>
39
40 """
41 for sides in ["", "T", "B", "L", "TB", "TL", "BL", "TBL"] {
42 func edge(_ side: Character) -> String { sides.contains(side) ? border : "none" }
43 styles += """
44 <style:style style:name="OrgTblCell\(sides)" style:family="table-cell">
45 <style:table-cell-properties style:vertical-align="top" fo:padding="0.159cm" fo:border-top="\(edge("T"))" fo:border-bottom="\(edge("B"))" fo:border-left="\(edge("L"))" fo:border-right="none"/>
46 </style:style>
47
48 """
49 }
50 for level in 0...10 {
51 styles += """
52 <style:style style:name="OrgIndentedSection-Level-\(level)" style:family="section">
53 <style:section-properties fo:margin-left="\(String(format: "%.3fcm", level == 0 ? 0 : 0.635 * Double(level + 1)))" fo:margin-right="0cm" style:editable="false"/>
54 </style:style>
55
56 """
57 }
58 styles += """
59 <style:style style:name="Sect1" style:family="section">
60 <style:section-properties style:editable="false"/>
61 </style:style>
62
63 """
64 let sequences = ["Table", "Illustration", "Text", "Equation", "Listing"].map {
65 "<text:sequence-decl text:display-outline-level=\"2\" text:name=\"\($0)\"/>"
66 }.joined(separator: "\n")
67 return """
68 <?xml version="1.0" encoding="UTF-8"?>
69 <office:document-content
70 \(namespaces)>
71 <office:automatic-styles>
72 \(styles)\(automaticStyles) </office:automatic-styles>
73 <office:body>
74 <office:text>
75
76 <text:sequence-decls>
77 \(sequences)
78 </text:sequence-decls>\(body)
79 </office:text>
80 </office:body>
81 </office:document-content>
82
83 """
84 }
85
86 /// `author`, `title` and `subtitle` are XML text already.
87 static func meta(author: String, date: String?, keywords: String, description: String, title: String, subtitle: String) -> String {
88 let e = { ODTRenderer.escape($0) }
89 var out = """
90 <?xml version="1.0" encoding="UTF-8"?>
91 <office:document-meta
92 \(namespaces)>
93 <office:meta>
94 <dc:creator>\(author)</dc:creator>
95 <meta:initial-creator>\(author)</meta:initial-creator>
96
97 """
98 if let date { out += "<dc:date>\(date)</dc:date>\n<meta:creation-date>\(date)</meta:creation-date>\n" }
99 out += "<meta:generator>orgstar</meta:generator>\n<meta:keyword>\(e(keywords))</meta:keyword>\n<dc:subject>\(e(description))</dc:subject>\n<dc:title>\(title)</dc:title>\n"
100 if !subtitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
101 out += "<meta:user-defined meta:name=\"subtitle\">\(subtitle)</meta:user-defined>\n"
102 }
103 return out + "\n </office:meta>\n</office:document-meta>\n"
104 }
105
106 /// The manifest, which lists every part but `mimetype` (the package itself, `/`).
107 static func manifest(images: [String]) -> String {
108 var entries = [(mimetype, "/", " manifest:version=\"1.2\""), ("text/xml", "content.xml", ""), ("text/xml", "styles.xml", ""), ("text/xml", "meta.xml", "")]
109 if !images.isEmpty { entries.append(("", "Images/", "")) }
110 // ox-odt names the type after the extension.
111 entries += images.map { ("image/" + ($0 as NSString).pathExtension, $0, "") }
112 return """
113 <?xml version="1.0" encoding="UTF-8"?>
114 <manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
115 \(entries.map { "<manifest:file-entry manifest:media-type=\"\($0.0)\" manifest:full-path=\"\($0.1)\"\($0.2)/>" }.joined(separator: "\n"))
116 </manifest:manifest>
117
118 """
119 }
120
121 /// `styles.xml`: headings numbered to `numbered` levels, A4 pages with 2 cm margins.
122 static func styles(numbered: Int) -> String {
123 func paragraph(_ name: String, display: String? = nil, parent: String? = "Standard", _ properties: String = "", text: String = "") -> String {
124 var out = " <style:style style:name=\"\(name)\" style:display-name=\"\(display ?? name)\" style:family=\"paragraph\""
125 if let parent { out += " style:parent-style-name=\"\(parent)\"" }
126 out += ">"
127 if !properties.isEmpty { out += "<style:paragraph-properties \(properties)/>" }
128 if !text.isEmpty { out += "<style:text-properties \(text)/>" }
129 return out + "</style:style>\n"
130 }
131 func span(_ name: String, display: String? = nil, _ text: String) -> String {
132 " <style:style style:name=\"\(name)\" style:display-name=\"\(display ?? name)\" style:family=\"text\"><style:text-properties \(text)/></style:style>\n"
133 }
134 func graphic(_ name: String, _ properties: String) -> String {
135 " <style:style style:name=\"\(name)\" style:family=\"graphic\"><style:graphic-properties \(properties)/></style:style>\n"
136 }
137 let mono = "fo:font-family=\"Courier, monospace\" fo:font-size=\"10pt\""
138 let body = "fo:margin-top=\"0cm\" fo:margin-bottom=\"0.212cm\""
139 var styles = """
140 <style:default-style style:family="paragraph"><style:paragraph-properties style:tab-stop-distance="1.251cm"/><style:text-properties fo:font-size="12pt" fo:language="en" fo:country="US"/></style:default-style>
141 <style:style style:name="Standard" style:family="paragraph" style:class="text"/>
142
143 """
144 styles += paragraph("Text_20_body", display: "Text body", body)
145 styles += paragraph("Text_20_body_20_bold", display: "Text body bold", parent: "Text_20_body", text: "fo:font-weight=\"bold\"")
146 styles += paragraph("Heading", parent: "Standard", "fo:margin-top=\"0.423cm\" fo:margin-bottom=\"0.212cm\" fo:keep-with-next=\"always\"", text: "fo:font-size=\"14pt\"")
147 let sizes = ["", "130%", "115%", "101%", "95%", "85%", "85%", "75%", "75%", "65%", "65%"]
148 for level in 1...10 {
149 let bold = "fo:font-size=\"\(sizes[level])\" fo:font-weight=\"bold\""
150 styles += " <style:style style:name=\"Heading_20_\(level)\" style:display-name=\"Heading \(level)\" style:family=\"paragraph\" style:parent-style-name=\"Heading\" style:next-style-name=\"Text_20_body\" style:default-outline-level=\"\(level)\" style:class=\"text\"><style:text-properties \(bold)/></style:style>\n"
151 styles += " <style:style style:name=\"Heading_20_\(level)_unnumbered\" style:display-name=\"Heading \(level) unnumbered\" style:family=\"paragraph\" style:parent-style-name=\"Heading_20_\(level)\" style:class=\"text\"/>\n"
152 }
153 styles += paragraph("OrgTitle", "fo:text-align=\"center\" fo:margin-bottom=\"0.212cm\"", text: "fo:font-size=\"24pt\" fo:font-weight=\"bold\"")
154 styles += paragraph("OrgSubtitle", "fo:text-align=\"center\" fo:margin-bottom=\"0.212cm\"", text: "fo:font-size=\"14pt\"")
155 styles += paragraph("Quotations", parent: "Text_20_body", "fo:margin-left=\"1cm\" fo:margin-right=\"1cm\"")
156 styles += paragraph("OrgCenter", parent: "Text_20_body", "fo:text-align=\"center\"")
157 styles += paragraph("OrgVerse", parent: "Text_20_body", "fo:margin-left=\"1cm\"")
158 styles += paragraph("OrgSrcBlock", parent: "Standard", "fo:margin-top=\"0cm\" fo:margin-bottom=\"0cm\" fo:background-color=\"#f0f0f0\"", text: mono)
159 styles += paragraph("OrgSrcBlockLastLine", parent: "OrgSrcBlock", "fo:margin-bottom=\"0.212cm\"")
160 styles += paragraph("OrgFixedWidthBlock", parent: "Standard", "fo:margin-top=\"0cm\" fo:margin-bottom=\"0cm\" fo:background-color=\"#f0f0f0\"", text: mono)
161 styles += paragraph("OrgFixedWidthBlockLastLine", parent: "OrgFixedWidthBlock", "fo:margin-bottom=\"0.212cm\"")
162 styles += paragraph("Footnote", parent: "Standard", "fo:margin-left=\"0.5cm\" fo:text-indent=\"-0.5cm\"", text: "fo:font-size=\"10pt\"")
163 styles += paragraph("OrgFootnoteCenter", parent: "Footnote", "fo:text-align=\"center\"")
164 styles += paragraph("OrgFootnoteQuotations", parent: "Footnote", "fo:margin-left=\"1cm\" fo:margin-right=\"1cm\"")
165 styles += paragraph("Table_20_Contents", display: "Table Contents", parent: "Standard")
166 for (name, align) in [("Left", "start"), ("Right", "end"), ("Center", "center")] {
167 styles += paragraph("OrgTableContents\(name)", parent: "Table_20_Contents", "fo:text-align=\"\(align)\"")
168 styles += paragraph("OrgTableHeading\(name)", parent: "Table_20_Contents", "fo:text-align=\"\(align)\"", text: "fo:font-weight=\"bold\"")
169 }
170 styles += paragraph("Contents_20_Heading", display: "Contents Heading", parent: "Heading", text: "fo:font-size=\"16pt\" fo:font-weight=\"bold\"")
171 for level in 1...10 {
172 styles += paragraph("Contents_20_\(level)", display: "Contents \(level)", parent: "Standard", "fo:margin-left=\"\(String(format: "%.3f", 0.499 * Double(level - 1)))cm\"")
173 }
174 styles += paragraph("Horizontal_20_Line", display: "Horizontal Line", parent: "Standard", "fo:margin-bottom=\"0.5cm\" fo:border-bottom=\"0.002cm solid #808080\"")
175 styles += paragraph("Caption", parent: "Standard", "fo:margin-top=\"0.212cm\" fo:margin-bottom=\"0.212cm\"", text: "fo:font-style=\"italic\" fo:font-size=\"10pt\"")
176 for name in ["Illustration", "Table", "Listing"] { styles += paragraph(name, parent: "Caption") }
177 styles += span("Emphasis", "fo:font-style=\"italic\"")
178 styles += span("Bold", "fo:font-weight=\"bold\"")
179 styles += span("Underline", "style:text-underline-style=\"solid\" style:text-underline-width=\"auto\" style:text-underline-color=\"font-color\"")
180 styles += span("Strikethrough", "style:text-line-through-style=\"solid\"")
181 styles += span("OrgCode", mono)
182 styles += span("OrgSubscript", "style:text-position=\"sub 58%\"")
183 styles += span("OrgSuperscript", "style:text-position=\"super 58%\"")
184 styles += span("OrgTodo", "fo:color=\"#b00000\" fo:font-weight=\"bold\"")
185 styles += span("OrgDone", "fo:color=\"#008000\" fo:font-weight=\"bold\"")
186 styles += span("OrgTags", "fo:font-size=\"85%\"")
187 styles += span("OrgTag", "fo:font-weight=\"bold\"")
188 styles += span("OrgPriority", "fo:font-weight=\"bold\"")
189 for priority in ["A", "B", "C"] { styles += span("OrgPriority-\(priority)", "fo:font-weight=\"bold\"") }
190 styles += span("OrgActiveTimestamp", "fo:color=\"#555555\"")
191 styles += span("OrgInactiveTimestamp", "fo:color=\"#888888\"")
192 styles += span("Internet_20_link", display: "Internet link", "fo:color=\"#000080\" style:text-underline-style=\"solid\" style:text-underline-width=\"auto\" style:text-underline-color=\"font-color\"")
193 styles += graphic("OrgDisplayImage", "style:wrap=\"none\" style:vertical-pos=\"top\" style:vertical-rel=\"paragraph\" style:horizontal-pos=\"center\" style:horizontal-rel=\"paragraph\"")
194 styles += graphic("OrgInlineImage", "style:vertical-pos=\"middle\" style:vertical-rel=\"text\"")
195 styles += graphic("OrgCaptionedImage", "style:wrap=\"none\" style:vertical-pos=\"top\" style:vertical-rel=\"paragraph\" style:horizontal-pos=\"center\" style:horizontal-rel=\"paragraph\"")
196 styles += graphic("OrgImageCaptionFrame", "style:wrap=\"none\" style:vertical-pos=\"top\" style:vertical-rel=\"paragraph\" style:horizontal-pos=\"center\" style:horizontal-rel=\"paragraph\" fo:padding=\"0cm\" fo:border=\"none\"")
197 func list(_ name: String, _ level: (Int) -> String) -> String {
198 " <text:list-style style:name=\"\(name)\">\n" + (1...10).map(level).joined() + " </text:list-style>\n"
199 }
200 func position(_ level: Int) -> String {
201 let indent = String(format: "%.3fcm", 0.635 * Double(level))
202 return "<style:list-level-properties text:list-level-position-and-space-mode=\"label-alignment\"><style:list-level-label-alignment text:label-followed-by=\"listtab\" text:list-tab-stop-position=\"\(indent)\" fo:text-indent=\"-0.635cm\" fo:margin-left=\"\(indent)\"/></style:list-level-properties>"
203 }
204 styles += list("OrgBulletedList") { " <text:list-level-style-bullet text:level=\"\($0)\" text:bullet-char=\"•\">\(position($0))</text:list-level-style-bullet>\n" }
205 styles += list("OrgNumberedList") { " <text:list-level-style-number text:level=\"\($0)\" style:num-suffix=\".\" style:num-format=\"1\">\(position($0))</text:list-level-style-number>\n" }
206 styles += list("OrgDescriptionList") { " <text:list-level-style-number text:level=\"\($0)\" style:num-format=\"\">\(position($0))</text:list-level-style-number>\n" }
207 styles += list("OrgSrcBlockNumberedLine") { " <text:list-level-style-number text:level=\"\($0)\" style:num-suffix=\" \" style:num-format=\"1\">\(position($0))</text:list-level-style-number>\n" }
208 styles += " <text:outline-style style:name=\"Outline\">\n"
209 for level in 1...10 {
210 let format = level <= numbered ? "style:num-format=\"1\" style:num-suffix=\".\" text:display-levels=\"\(level)\"" : "style:num-format=\"\""
211 styles += " <text:outline-level-style text:level=\"\(level)\" \(format)><style:list-level-properties text:list-level-position-and-space-mode=\"label-alignment\"><style:list-level-label-alignment text:label-followed-by=\"space\"/></style:list-level-properties></text:outline-level-style>\n"
212 }
213 styles += " </text:outline-style>\n"
214 styles += " <text:notes-configuration text:note-class=\"footnote\" style:num-format=\"1\" text:start-value=\"0\" text:footnotes-position=\"page\" text:start-numbering-at=\"document\"/>\n"
215 return """
216 <?xml version="1.0" encoding="UTF-8"?>
217 <office:document-styles
218 \(namespaces)>
219 <office:styles>
220 \(styles) </office:styles>
221 <office:automatic-styles>
222 <style:page-layout style:name="OrgPage"><style:page-layout-properties fo:page-width="21cm" fo:page-height="29.7cm" style:print-orientation="portrait" fo:margin-top="2cm" fo:margin-bottom="2cm" fo:margin-left="2cm" fo:margin-right="2cm"/></style:page-layout>
223 </office:automatic-styles>
224 <office:master-styles>
225 <style:master-page style:name="Standard" style:page-layout-name="OrgPage"/>
226 </office:master-styles>
227 </office:document-styles>
228
229 """
230 }
231}
Sources/OrgCore/Export/ZipWriter.swift added +52
@@ -0,0 +1,52 @@
1import Foundation
2
3/// A zip archive with stored (uncompressed) entries in the order added, as `.docx` and `.odt`
4/// files are read.
5package struct ZipWriter {
6 private var entries: [(name: Data, data: Data, crc: UInt32, offset: UInt32)] = []
7 private var archive = Data()
8
9 package init() {}
10
11 package mutating func add(_ name: String, _ text: String) {
12 add(name, data: Data(text.utf8))
13 }
14
15 package mutating func add(_ name: String, data: Data) {
16 let nameData = Data(name.utf8)
17 let crc = Self.crc32(data)
18 let offset = UInt32(archive.count)
19 archive += Self.le32(0x04034b50) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
20 archive += Self.le32(crc) + Self.le32(UInt32(data.count)) + Self.le32(UInt32(data.count))
21 archive += Self.le16(UInt16(nameData.count)) + Self.le16(0) + nameData + data
22 entries.append((nameData, data, crc, offset))
23 }
24
25 package func data() -> Data {
26 var central = Data()
27 for entry in entries {
28 central += Self.le32(0x02014b50) + Self.le16(20) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
29 central += Self.le32(entry.crc) + Self.le32(UInt32(entry.data.count)) + Self.le32(UInt32(entry.data.count))
30 central += Self.le16(UInt16(entry.name.count)) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le32(0)
31 central += Self.le32(entry.offset) + entry.name
32 }
33 var end = Self.le32(0x06054b50) + Self.le16(0) + Self.le16(0) + Self.le16(UInt16(entries.count)) + Self.le16(UInt16(entries.count))
34 end += Self.le32(UInt32(central.count)) + Self.le32(UInt32(archive.count)) + Self.le16(0)
35 return archive + central + end
36 }
37
38 private static func le16(_ v: UInt16) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
39 private static func le32(_ v: UInt32) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
40
41 private static let table: [UInt32] = (0..<256).map { n in
42 var c = UInt32(n)
43 for _ in 0..<8 { c = c & 1 != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1 }
44 return c
45 }
46
47 private static func crc32(_ data: Data) -> UInt32 {
48 var c: UInt32 = 0xFFFFFFFF
49 for byte in data { c = table[Int((c ^ UInt32(byte)) & 0xFF)] ^ (c >> 8) }
50 return c ^ 0xFFFFFFFF
51 }
52}
Sources/OrgCore/Links/Coderef.swift +4
@@ -14,10 +14,13 @@ public enum Coderef {
14 public var retainLabels = true 14 public var retainLabels = true
15 public var useLabels = true 15 public var useLabels = true
16 public var labelFormat = Coderef.defaultFormat 16 public var labelFormat = Coderef.defaultFormat
17 /// `-i`.
18 public var preserveIndent = false
17 19
18 public static func == (a: Switches, b: Switches) -> Bool { 20 public static func == (a: Switches, b: Switches) -> Bool {
19 a.numberLines?.continued == b.numberLines?.continued && a.numberLines?.before == b.numberLines?.before 21 a.numberLines?.continued == b.numberLines?.continued && a.numberLines?.before == b.numberLines?.before
20 && a.retainLabels == b.retainLabels && a.useLabels == b.useLabels && a.labelFormat == b.labelFormat 22 && a.retainLabels == b.retainLabels && a.useLabels == b.useLabels && a.labelFormat == b.labelFormat
23 && a.preserveIndent == b.preserveIndent
21 } 24 }
22 25
23 public init(_ switches: String?) { 26 public init(_ switches: String?) {
@@ -30,6 +33,7 @@ public enum Coderef {
30 retainLabels = !r || (numberLines != nil && k) 33 retainLabels = !r || (numberLines != nil && k)
31 useLabels = retainLabels && !k 34 useLabels = retainLabels && !k
32 if let m = switches.firstMatch(of: /-l +"([^"\n]+)"/) { labelFormat = String(m.1) } 35 if let m = switches.firstMatch(of: /-l +"([^"\n]+)"/) { labelFormat = String(m.1) }
36 preserveIndent = switches.contains(/-i\b/)
33 } 37 }
34 } 38 }
35 39
Sources/OrgEditorAppKit/EditorCommands.swift +1 −1
@@ -174,7 +174,7 @@ public enum EditorCommands {
174 EditorCommand(id: "app.export.plain-text", title: "Export to Plain Text", action: .app), 174 EditorCommand(id: "app.export.plain-text", title: "Export to Plain Text", action: .app),
175 EditorCommand(id: "app.copy-rich-text", title: "Copy as Rich Text", action: .app), 175 EditorCommand(id: "app.copy-rich-text", title: "Copy as Rich Text", action: .app),
176 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app), 176 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app),
177 EditorCommand(id: "app.export.odt", title: "Export to ODT with Emacs", action: .app), 177 EditorCommand(id: "app.export.odt", title: "Export to ODT", action: .app),
178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX", action: .app), 178 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 with Emacs", action: .app),
180 EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app), 180 EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app),
Sources/Orgstar/ContentView.swift +15 −1
@@ -630,6 +630,20 @@ struct ContentView: View {
630 } 630 }
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 exportLaTeX(text, whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults):
632 break 632 break
633 case "odt":
634 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
635 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "odt")) else { return }
636 // A missing image stops the export, so offer access to them first.
637 _ = reach(ODTExport.imageFiles(text, settings: defaults, path: path).filter(WorkspaceModel.isThere))
638 do {
639 let data = try ODTExport.document(text, settings: defaults, path: path, author: NSFullUserName(), language: OrgPreferences.exportLanguage())
640 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
641 try data.write(to: target, options: .atomic)
642 commands.show("Exported to \(target.lastPathComponent)")
643 if open { NSWorkspace.shared.open(target) }
644 } catch {
645 commands.show("Can't export \(target.lastPathComponent): \(error.localizedDescription)")
646 }
633 case "print-pdf", "docx", "rtf", "plain-text": 647 case "print-pdf", "docx", "rtf", "plain-text":
634 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format 648 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
635 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults) 649 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
@@ -661,7 +675,7 @@ struct ContentView: View {
661 } 675 }
662 default: 676 default:
663 #if !APPSTORE 677 #if !APPSTORE
664 let functions = ["pdf": "org-latex-export-to-pdf", "odt": "org-odt-export-to-odt", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"] 678 let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
665 guard let function = functions[format] else { return } 679 guard let function = functions[format] else { return }
666 commands.show("Exporting with Emacs…") 680 commands.show("Exporting with Emacs…")
667 commands.runInEmacs { 681 commands.runInEmacs {
Sources/Orgstar/ExportSheet.swift +3 −3
@@ -24,14 +24,14 @@ struct ExportSheet: View {
24 #if APPSTORE 24 #if APPSTORE
25 static let formats: [(id: String, title: String, ext: String)] = [ 25 static let formats: [(id: String, title: String, ext: String)] = [
26 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"), 26 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
27 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("icalendar", "iCalendar", "ics"), 27 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("odt", "ODT", "odt"),
28 ("latex", "LaTeX", "tex"), 28 ("icalendar", "iCalendar", "ics"), ("latex", "LaTeX", "tex"),
29 ] 29 ]
30 #else 30 #else
31 static let formats: [(id: String, title: String, ext: String)] = [ 31 static let formats: [(id: String, title: String, ext: String)] = [
32 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"), 32 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
33 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"), 33 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
34 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"), 34 ("odt", "ODT", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
35 ("icalendar", "iCalendar", "ics"), 35 ("icalendar", "iCalendar", "ics"),
36 ] 36 ]
37 #endif 37 #endif
Sources/OrgstarMobile/ExportMenu.swift +11 −4
@@ -6,11 +6,11 @@ import OrgPresentation
6import SwiftUI 6import SwiftUI
7import UniformTypeIdentifiers 7import UniformTypeIdentifiers
8 8
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, iCalendar or LaTeX, written when the 9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar or LaTeX, written
10/// share sheet takes it. 10/// when the share sheet takes it.
11struct OrgExport: Transferable { 11struct OrgExport: Transferable {
12 enum Format: CaseIterable { 12 enum Format: CaseIterable {
13 case html, markdown, pdf, docx, rtf, plainText, icalendar 13 case html, markdown, pdf, docx, rtf, plainText, odt, icalendar
14 case latex 14 case latex
15 15
16 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked. 16 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked.
@@ -24,6 +24,7 @@ struct OrgExport: Transferable {
24 case .docx: "Word" 24 case .docx: "Word"
25 case .rtf: "Rich Text (RTF)" 25 case .rtf: "Rich Text (RTF)"
26 case .plainText: "Plain Text" 26 case .plainText: "Plain Text"
27 case .odt: "ODT"
27 case .icalendar: "iCalendar" 28 case .icalendar: "iCalendar"
28 case .latex: "LaTeX" 29 case .latex: "LaTeX"
29 } 30 }
@@ -37,6 +38,7 @@ struct OrgExport: Transferable {
37 case .docx: "docx" 38 case .docx: "docx"
38 case .rtf: "rtf" 39 case .rtf: "rtf"
39 case .plainText: "txt" 40 case .plainText: "txt"
41 case .odt: "odt"
40 case .icalendar: "ics" 42 case .icalendar: "ics"
41 case .latex: "tex" 43 case .latex: "tex"
42 } 44 }
@@ -77,6 +79,8 @@ struct OrgExport: Transferable {
77 .exportingCondition { $0.format == .rtf } 79 .exportingCondition { $0.format == .rtf }
78 FileRepresentation(exportedContentType: .plainText) { try await $0.write() } 80 FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
79 .exportingCondition { $0.format == .plainText } 81 .exportingCondition { $0.format == .plainText }
82 FileRepresentation(exportedContentType: UTType(filenameExtension: "odt") ?? .data) { try await $0.write() }
83 .exportingCondition { $0.format == .odt }
80 FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() } 84 FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
81 .exportingCondition { $0.format == .icalendar } 85 .exportingCondition { $0.format == .icalendar }
82 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() } 86 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
@@ -106,6 +110,9 @@ struct OrgExport: Transferable {
106 throw error 110 throw error
107 } 111 }
108 try content.write(to: url, atomically: true, encoding: .utf8) 112 try content.write(to: url, atomically: true, encoding: .utf8)
113 case .odt:
114 try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage())
115 .write(to: url, options: .atomic)
109 case .icalendar: 116 case .icalendar:
110 try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(), 117 try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
111 subtree: subtree, destination: url) 118 subtree: subtree, destination: url)
@@ -126,7 +133,7 @@ struct OrgExport: Transferable {
126 } 133 }
127} 134}
128 135
129/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, iCalendar or LaTeX: to another app, or saved with 136/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar or LaTeX: to another app, or saved with
130/// Save to Files; or copying it as rich text. 137/// Save to Files; or copying it as rich text.
131struct ExportMenu: View { 138struct ExportMenu: View {
132 let path: String 139 let path: String
Tests/OrgAppTests/PublishTests.swift +16
@@ -195,6 +195,22 @@ struct PublishTests {
195 } 195 }
196 } 196 }
197 197
198 /// `org-odt-publish-to-odt` writes `.odt` files, which the export closure doesn't see.
199 @Test func publishesODT() throws {
200 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)")
201 defer { try? FileManager.default.removeItem(at: folder) }
202 try Self.tree(folder)
203 let config = "[[publish]]\nname = \"odt\"\nbase-directory = \"\(folder.path)/src\"\npublishing-directory = \"\(folder.path)/odt\"\npublishing-function = \"org-odt-publish-to-odt\"\n"
204 let loaded = Publish.projects(fromConfig: config, root: nil)
205 #expect(loaded.problems.isEmpty)
206 let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
207 let report = try Publish.publish(loaded.projects, all: loaded.projects, read: read) { _, _, _, _ in Issue.record("exported as text"); return "" }
208 #expect(report.published.count == 3)
209 let data = try Data(contentsOf: folder.appendingPathComponent("odt/a.odt"))
210 #expect(data.prefix(4) == Data([0x50, 0x4b, 0x03, 0x04]))
211 #expect(String(decoding: data[30..<38], as: UTF8.self) == "mimetype")
212 }
213
198 @Test func skipsUpToDateFilesAndFindsProjects() throws { 214 @Test func skipsUpToDateFilesAndFindsProjects() throws {
199 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)").resolvingSymlinksInPath() 215 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)").resolvingSymlinksInPath()
200 defer { try? FileManager.default.removeItem(at: folder) } 216 defer { try? FileManager.default.removeItem(at: folder) }
Tests/OrgCoreTests/ODTExportTests.swift added +730
@@ -0,0 +1,730 @@
1import Foundation
2import AppKit
3import ImageIO
4import Testing
5@testable import OrgCore
6
7/// `content.xml` reduced to what ox-odt and the native export must agree on: headings with
8/// their outline level, paragraphs, lists, sections, spans, tables and their rows and cells,
9/// links and images with their targets, notes and frames, the style names of these, and the
10/// text runs. `text:s` counts as spaces; tabs and line breaks are tokens of their own;
11/// references are numbered in order of appearance, since ox-odt's are random. The spans
12/// ox-odt colors source code with are left out: the export doesn't fontify.
13enum ODTSkeleton {
14 static let kept: Set<String> = [
15 "text:h", "text:p", "text:span", "text:list", "text:list-item", "text:list-header", "text:section", "text:note",
16 "table:table", "table:table-header-rows", "table:table-rows", "table:table-row", "table:table-cell", "table:covered-table-cell",
17 "text:a", "draw:a", "draw:frame", "draw:image", "draw:text-box", "text:table-of-content", "text:index-body",
18 ]
19
20 static func reduce(_ xml: String) -> String {
21 guard let start = xml.range(of: "<office:text>"), let end = xml.range(of: "</office:text>") else { return xml }
22 let body = xml[start.upperBound..<end.lowerBound]
23 var lines: [String] = []
24 var text = ""
25 var references: [String: Int] = [:]
26 var spans: [Bool] = []
27 func flush() {
28 let collapsed = Skeleton.decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ")
29 if !collapsed.isEmpty { lines.append("\"" + collapsed + "\"") }
30 text = ""
31 }
32 var i = body.startIndex
33 while i < body.endIndex {
34 guard body[i] == "<", let close = body[i...].firstIndex(of: ">") else {
35 text.append(body[i])
36 i = body.index(after: i)
37 continue
38 }
39 let tag = String(body[body.index(after: i)..<close])
40 i = body.index(after: close)
41 if tag.hasPrefix("!") || tag.hasPrefix("?") { continue }
42 let closing = tag.hasPrefix("/")
43 let name = String(tag.dropFirst(closing ? 1 : 0).prefix { !$0.isWhitespace && $0 != "/" })
44 switch name {
45 case "text:s":
46 let count = tag.firstMatch(of: /text:c="([0-9]+)"/).flatMap { Int($0.1) } ?? 1
47 text += String(repeating: " ", count: count)
48 continue
49 case "text:tab", "text:line-break":
50 flush()
51 lines.append("<\(name)/>")
52 continue
53 default:
54 break
55 }
56 guard kept.contains(name) else { continue }
57 if name == "text:span", !tag.hasSuffix("/") {
58 if closing {
59 if spans.popLast() == false { continue }
60 } else {
61 let colored = tag.contains("text:style-name=\"OrgSrcFontLock")
62 spans.append(!colored)
63 if colored { continue }
64 }
65 }
66 flush()
67 if closing {
68 lines.append("</\(name)>")
69 continue
70 }
71 var attributes = ""
72 if let style = tag.firstMatch(of: /(?:text|table):style-name="([^"]*)"/) { attributes += " style=\(style.1)" }
73 if let level = tag.firstMatch(of: /text:outline-level="([0-9]+)"/) { attributes += " level=\(level.1)" }
74 if let href = tag.firstMatch(of: /xlink:href="([^"]*)"/) {
75 var value = String(href.1)
76 if value.hasPrefix("#") {
77 let n = references[value] ?? references.count + 1
78 references[value] = n
79 value = "#ref\(n)"
80 }
81 attributes += " href=\"\(value)\""
82 }
83 if let span = tag.firstMatch(of: /table:number-columns-spanned="([0-9]+)"/) { attributes += " span=\(span.1)" }
84 lines.append("<\(name)\(attributes)>")
85 if tag.hasSuffix("/") { lines.append("</\(name)>") }
86 }
87 flush()
88 return lines.joined(separator: "\n") + "\n"
89 }
90}
91
92/// Reads a zip's entries, stored or deflated, through `unzip` for the latter.
93enum ZipReader {
94 struct Entry {
95 var name: String
96 var method: UInt16
97 var extraLength: UInt16
98 var data: Data
99 }
100
101 /// The local entries in order.
102 static func entries(_ data: Data) -> [Entry] {
103 var out: [Entry] = []
104 var at = 0
105 let bytes = [UInt8](data)
106 func u16(_ i: Int) -> UInt16 { UInt16(bytes[i]) | UInt16(bytes[i + 1]) << 8 }
107 func u32(_ i: Int) -> UInt32 { UInt32(u16(i)) | UInt32(u16(i + 2)) << 16 }
108 while at + 30 <= bytes.count, u32(at) == 0x04034b50 {
109 let method = u16(at + 8)
110 let size = Int(u32(at + 18))
111 let nameLength = Int(u16(at + 26))
112 let extra = u16(at + 28)
113 let name = String(decoding: bytes[(at + 30)..<(at + 30 + nameLength)], as: UTF8.self)
114 let start = at + 30 + nameLength + Int(extra)
115 out.append(Entry(name: name, method: method, extraLength: extra, data: Data(bytes[start..<(start + size)])))
116 at = start + size
117 }
118 return out
119 }
120
121 /// The names the central directory lists.
122 static func directory(_ data: Data) -> [String] {
123 let bytes = [UInt8](data)
124 var names: [String] = []
125 var i = 0
126 while i + 46 <= bytes.count {
127 if bytes[i] == 0x50, bytes[i + 1] == 0x4b, bytes[i + 2] == 0x01, bytes[i + 3] == 0x02 {
128 let length = Int(bytes[i + 28]) | Int(bytes[i + 29]) << 8
129 names.append(String(decoding: bytes[(i + 46)..<(i + 46 + length)], as: UTF8.self))
130 i += 46 + length
131 } else {
132 i += 1
133 }
134 }
135 return names
136 }
137}
138
139struct ODTExportTests {
140 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable
141
142 /// A PNG of `width` by `height` pixels.
143 static func png(width: Int, height: Int) -> Data {
144 let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
145 space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
146 context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
147 context.fill(CGRect(x: 0, y: 0, width: width, height: height))
148 let data = NSMutableData()
149 let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)!
150 CGImageDestinationAddImage(destination, context.makeImage()!, nil)
151 CGImageDestinationFinalize(destination)
152 return data as Data
153 }
154
155 static let corpus = ["minimal", "core", "headings", "listblocks", "lists", "table", "blocks", "timestamps", "footnote", "tblfm"]
156
157 /// Documents for what the corpus doesn't cover. `PIC` is replaced by an image's path.
158 static let snippets: [String: String] = [
159 "images": """
160 #+TITLE: Images
161
162 [[file:PIC]]
163
164 #+CAPTION: A captioned picture
165 #+NAME: fig:one
166 [[file:PIC]]
167
168 Inline [[file:PIC]] in text and a [[file:PIC][described]] link.
169
170 #+ATTR_ODT: :width 3
171 [[file:PIC]]
172
173 See [[fig:one]] and [[fig:one][the figure]].
174
175 [[https://example.com][file:PIC]]
176 """,
177 "tables": """
178 #+TITLE: Tables
179 #+OPTIONS: toc:nil
180
181 * One
182 #+CAPTION: Scores
183 #+NAME: tbl:scores
184 | Name | <r> |
185 | Name | Score |
186 |-------+-------|
187 | alpha | 10 |
188 |-------+-------|
189 | beta | x |
190 | gamma | |
191
192 Refer to [[tbl:scores]].
193
194 | / | <> | |
195 | # | a | b |
196 | ! | x | y |
197 | # | 1 | 2 |
198
199 | <5> | b |
200 | 1 | 2 |
201
202 #+ATTR_ODT: :rel-width 50
203 | c | d |
204 """,
205 "list-tables": """
206 #+OPTIONS: toc:nil
207
208 1. first
209 - nested
210 | a | b |
211 | 1 | 2 |
212 after the table
213 - next nested
214 2. second
215 | x |
216 | y |
217 then text
218 | z |
219
220 - term :: definition
221 | t |
222 """,
223 "footnotes": """
224 #+OPTIONS: toc:nil
225
226 One[fn:a][fn:b] and again[fn:a], anonymous[fn:: inline /note/].
227
228 [fn:a] First note.
229
230 With a second paragraph.
231 [fn:b] Second note.
232 """,
233 "low-levels": """
234 #+OPTIONS: H:2
235
236 * Top
237 ** Second
238 *** Third
239 Text under third.
240 **** Fourth
241 | cell |
242 *** Third again
243 * Other
244 """,
245 "links": """
246 #+TITLE: Links
247
248 * Alpha
249 :PROPERTIES:
250 :CUSTOM_ID: alpha-id
251 :ID: 1234-abcd
252 :END:
253 Go to [[*Beta]], [[Beta][the beta]], [[#alpha-id][custom]], [[#alpha-id]], [[id:1234-abcd]] and <<here>>.
254 * Beta
255 A <<<radio word>>> and later the radio word again. [[here][back]].
256 Mail [[mailto:a@b.c][me]], a file [[file:notes.txt]], ./rel.txt and [[./dir/x.org][rel]].
257 #+begin_src emacs-lisp -n -r
258 (setq x 1) (ref:one)
259 (setq y 2)
260 #+end_src
261 Line [[(one)]] and [[(one)][line %s]].
262 * Gamma :noexport:
263 Excluded.
264 * COMMENT Delta
265 Commented.
266 """,
267 "inline": """
268 #+TITLE: Inline /markup/
269 #+SUBTITLE: The subtitle
270 #+AUTHOR: Someone
271 #+DATE: <2024-03-01 Fri>
272 #+OPTIONS: num:nil pri:t
273
274 * TODO [#B] Heading with =code= :tag:
275 Text with *bold*, /italic/, _under_, +strike+, ~code spaced~, =verb=.
276 Math \\(a+b\\) and $x$ and \\alpha and H_2O and x^{2} and e^x.
277 Dashes -- and --- and ... and a\\-b.
278 Line one\\\\
279 line two.
280 @@odt:<text:span>raw</text:span>@@ and @@html:<b>no</b>@@ and [2/3] cookie.
281 #+ODT: <text:p>raw paragraph</text:p>
282
283 -----
284
285 \\begin{equation}
286 E = mc^2
287 \\end{equation}
288
289 :NOTES:
290 Drawer contents.
291 :END:
292
293 #+begin_verse
294 Indented first
295 second line
296 #+end_verse
297
298 #+begin_example -n
299 one
300 two
301 #+end_example
302
303 #+CAPTION: A listing
304 #+begin_src python
305 print("x")
306 #+end_src
307
308 : fixed width
309 : lines
310
311 #+begin_center
312 Centered *text*.
313 #+end_center
314
315 #+TOC: headlines 1
316 """,
317 "more": """
318 #+OPTIONS: toc:nil
319
320 * Heading
321 #+begin_src python
322
323 x = 1
324
325 y = 2
326
327 #+end_src
328
329 #+begin_example
330 ex
331
332
333 #+end_example
334
335 3. [@3] third
336 4. fourth
337 - [X] term :: def
338 - [ ] other :: more
339
340 #+begin_quote
341 - a quoted item
342 #+end_quote
343
344 [2024-01-01 Mon]--[2024-01-02 Tue] and <2024-01-01 Mon 10:00>
345
346 #+TOC: headlines local
347
348 ** Sub
349 Text \\alpha{} \\beta and \\nbsp{}.
350
351 #+begin_textbox
352 Boxed.
353 #+end_textbox
354
355 #+begin_annotation
356 Noted.
357 #+end_annotation
358 """,
359 "options": """
360 #+OPTIONS: toc:1 num:1 todo:nil tags:nil author:nil date:nil title:nil -:nil ^:{} tex:nil
361
362 * DONE First :x:
363 ** Sub
364 Text -- here a_b and a_{b} and \\(x\\).
365 * Second
366 """,
367 "deep-headings": """
368 #+OPTIONS: toc:nil
369 * One
370 ** Two
371 *** Three
372 **** Four
373 See [[Four]].
374 **** Five
375 """,
376 "num-past-h": """
377 #+OPTIONS: toc:nil num:3 H:1
378 * A
379 ** B
380 *** C
381 **** D
382 """,
383 "nested-footnotes": """
384 #+OPTIONS: toc:nil
385 A[fn:1] B[fn:2] C[fn:4].
386
387 [fn:1] One[fn:3][fn:4].
388
389 [fn:2] Two.
390
391 [fn:3] Three.
392
393 [fn:4] Four.
394 """,
395 "inline-footnotes": """
396 #+OPTIONS: toc:nil
397 First[fn:x] then[fn:x: inline /def/] and an anonymous[fn:: one[fn:y]] note.
398
399 [fn:y] Nested in an anonymous one.
400 """,
401 "tocs": """
402 #+OPTIONS: toc:nil
403 * Top
404 #+TOC: headlines 1 local
405 ** Child A
406 ** DONE Child B
407 *** Grand
408 * Appendix
409 :PROPERTIES:
410 :UNNUMBERED: notoc
411 :END:
412 ** Inside appendix
413 *** Deeper
414 :PROPERTIES:
415 :UNNUMBERED: nil
416 :END:
417 * Last
418 #+TOC: headlines 5
419 """,
420 "cookie-header": """
421 #+OPTIONS: toc:nil
422 | <r> | <l> |
423 |-----+-----|
424 | a | b |
425 """,
426 "preserve-breaks": """
427 #+OPTIONS: toc:nil \\n:t
428 Line one
429 line two.
430
431 Ends with a break\\\\
432 next line\\\\
433 """,
434 "no-footnotes-tables-entities": """
435 #+OPTIONS: toc:nil f:nil |:nil e:nil
436 Text[fn:1] with \\alpha and \\beta{} here.
437
438 #+CAPTION: Dropped
439 | a | b |
440
441 - item
442 | c |
443
444 [fn:1] Note.
445 """,
446 "no-drawers": """
447 #+OPTIONS: toc:nil d:nil
448 * H
449 :NOTES:
450 Hidden.
451 :END:
452 Shown.
453 """,
454 "include-subdirectory": """
455 #+OPTIONS: toc:nil
456 #+INCLUDE: "sub/part.inc"
457 """,
458 "src-blank-lines": """
459 #+OPTIONS: toc:nil
460 #+begin_src python
461 a
462 \u{20}\u{20}
463 #+end_src
464
465 #+begin_src python
466 a
467 \u{20}\u{20}
468
469 #+end_src
470
471 #+begin_src python -i
472 a
473 \u{20}\u{20}
474 #+end_src
475
476 #+begin_example
477 a
478 \u{20}\u{20}
479 #+end_example
480
481 #+begin_src foo
482 \u{20}\u{20}a
483 \u{20}\u{20}
484 #+end_src
485 """,
486 "toc-local-before-headings": """
487 #+OPTIONS: toc:nil
488 #+TOC: headlines 1 local
489 * A
490 ** B
491 """,
492 "babel-languages": """
493 #+OPTIONS: toc:nil
494 before
495 #+begin_src dot
496 a
497 #+end_src
498 after
499 #+begin_src latex
500 b
501 #+end_src
502 #+begin_src plantuml
503 c
504 #+end_src
505 #+begin_src ditaa
506 d
507 #+end_src
508 #+begin_src gnuplot
509 e
510 #+end_src
511 #+begin_src lilypond
512 f
513 #+end_src
514 """,
515 "all-drawers": """
516 #+OPTIONS: toc:nil d:t
517 * H
518 :LOGBOOK:
519 - Note taken on [2024-01-01 Mon 10:00]
520 :END:
521 Shown.
522 """,
523 ]
524
525 /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the
526 /// message.
527 static func emacs(_ files: [URL]) throws -> [String] {
528 let folder = files[0].deletingLastPathComponent()
529 let output = folder.appendingPathComponent("out.json")
530 let script = folder.appendingPathComponent("odt.el")
531 try """
532 ;;; -*- lexical-binding: t -*-
533 (require 'ox-odt)
534 (require 'json)
535 (setq user-full-name "Tester")
536 (let (results)
537 (dolist (file (split-string (getenv "ODT_FILES") "\\n" t))
538 (push (condition-case err
539 (with-current-buffer (find-file-noselect file)
540 (let ((odt (org-odt-export-to-odt)))
541 (with-temp-buffer
542 (let ((coding-system-for-read 'utf-8))
543 (call-process "unzip" nil t nil "-p" odt "content.xml"))
544 (buffer-string))))
545 (error (concat "ERROR: " (error-message-string err))))
546 results))
547 (let ((coding-system-for-write 'utf-8))
548 (with-temp-file (getenv "ODT_OUTPUT")
549 (insert (json-encode (vconcat (nreverse results)))))))
550 """.write(to: script, atomically: true, encoding: .utf8)
551 try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: [
552 "ODT_FILES": files.map(\.path).joined(separator: "\n"), "ODT_OUTPUT": output.path, "TZ": "UTC",
553 ])
554 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
555 }
556
557 static func content(_ text: String, path: String) throws -> String {
558 let parts = try ODTExport.parts(text, path: path, author: "Tester")
559 return String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
560 }
561
562 @Test(.enabled(if: oracle))
563 func matchesOxODT() throws {
564 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
565 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
566 defer { try? FileManager.default.removeItem(at: folder) }
567 let picture = folder.appendingPathComponent("pic.png")
568 try Self.png(width: 64, height: 48).write(to: picture)
569 // Links in a file included from another folder are relative to that folder.
570 let sub = folder.appendingPathComponent("sub")
571 try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
572 try Self.png(width: 20, height: 10).write(to: sub.appendingPathComponent("pic.png"))
573 try """
574 [[file:pic.png]]
575
576 file:pic.png and <file:pic.png> and [[https://x.org][file:pic.png]] and [[file:../sub/pic.png][pic]]
577
578 See file:notes.txt and <file:notes.txt>.
579
580 #+begin_example
581 [[file:nothere.png]]
582 #+end_example
583 """.write(to: sub.appendingPathComponent("part.inc"), atomically: true, encoding: .utf8)
584 var documents: [(name: String, text: String)] = []
585 for name in Self.corpus {
586 documents.append((name, try String(contentsOf: ExportTests.folder.appendingPathComponent("\(name).org"), encoding: .utf8)))
587 }
588 for (name, text) in Self.snippets.sorted(by: { $0.key < $1.key }) {
589 documents.append((name, text.replacingOccurrences(of: "PIC", with: picture.path) + "\n"))
590 }
591 let files = documents.map { folder.appendingPathComponent($0.name + ".org") }
592 for (document, file) in zip(documents, files) { try document.text.write(to: file, atomically: true, encoding: .utf8) }
593 let expected = try Self.emacs(files)
594 for (index, document) in documents.enumerated() {
595 let theirs = ODTSkeleton.reduce(expected[index])
596 let ours = ODTSkeleton.reduce(try Self.content(document.text, path: files[index].path))
597 #expect(ours == theirs, "\(document.name)\n--- ours\n\(ours)\n--- ox-odt\n\(theirs)")
598 }
599 }
600
601 /// Where ox-odt stops, the export stops with its message.
602 @Test(.enabled(if: oracle))
603 func failsLikeOxODT() throws {
604 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
605 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
606 defer { try? FileManager.default.removeItem(at: folder) }
607 // `[[./pic.png]]` included from `sub` is written back as `[[sub/pic.png]]`, a fuzzy link.
608 let sub = folder.appendingPathComponent("sub")
609 try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
610 try Self.png(width: 10, height: 10).write(to: sub.appendingPathComponent("pic.png"))
611 try "[[./pic.png]]\n".write(to: sub.appendingPathComponent("dot.inc"), atomically: true, encoding: .utf8)
612 let documents = [
613 "broken": "See [[nowhere]].\n",
614 "included-dot-link": "#+INCLUDE: \"sub/dot.inc\"\n",
615 "missing": "[[file:missing.png]]\n",
616 "elements": try String(contentsOf: ExportTests.folder.appendingPathComponent("elements.org"), encoding: .utf8),
617 ].sorted { $0.key < $1.key }
618 let files = documents.map { folder.appendingPathComponent($0.key + ".org") }
619 for (document, file) in zip(documents, files) { try document.value.write(to: file, atomically: true, encoding: .utf8) }
620 let expected = try Self.emacs(files)
621 for (index, document) in documents.enumerated() {
622 #expect(expected[index].hasPrefix("ERROR: "), "\(document.key)")
623 #expect(throws: ODTExport.Failure.self) { try Self.content(document.value, path: files[index].path) }
624 do {
625 _ = try Self.content(document.value, path: files[index].path)
626 } catch let failure as ODTExport.Failure {
627 #expect(expected[index].contains(failure.message), "\(document.key): \(failure.message) / \(expected[index])")
628 }
629 }
630 }
631
632 /// `mimetype` first and stored, with no extra field; the manifest lists every part; each
633 /// XML part parses.
634 @Test func package() throws {
635 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
636 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
637 defer { try? FileManager.default.removeItem(at: folder) }
638 try Self.png(width: 10, height: 10).write(to: folder.appendingPathComponent("a.png"))
639 let path = folder.appendingPathComponent("doc.org").path
640 let data = try ODTExport.document("#+TITLE: T & U\n\n* Heading\n[[./a.png]]\n\n| x | y |\n", path: path)
641 let entries = ZipReader.entries(data)
642 #expect(entries.first?.name == "mimetype")
643 #expect(entries.first?.method == 0)
644 #expect(entries.first?.extraLength == 0)
645 #expect(entries.first.map { String(decoding: $0.data, as: UTF8.self) } == "application/vnd.oasis.opendocument.text")
646 #expect(ZipReader.directory(data) == entries.map(\.name))
647 #expect(entries.map(\.name) == ["mimetype", "content.xml", "styles.xml", "meta.xml", "Images/0001.png", "META-INF/manifest.xml"])
648 let manifest = try XMLDocument(data: entries.last!.data)
649 let listed = try manifest.nodes(forXPath: "//*[local-name()='file-entry']/@*[local-name()='full-path']").compactMap(\.stringValue)
650 for entry in entries where !["mimetype", "META-INF/manifest.xml"].contains(entry.name) {
651 #expect(listed.contains(entry.name), "\(entry.name)")
652 }
653 #expect(listed.contains("/"))
654 for entry in entries where entry.name.hasSuffix(".xml") {
655 #expect(throws: Never.self) { try XMLDocument(data: entry.data) }
656 }
657 let content = try XMLDocument(data: entries[1].data)
658 #expect(try content.nodes(forXPath: "//*[local-name()='h']").count == 1)
659 #expect(try content.nodes(forXPath: "//*[local-name()='image']/@*[local-name()='href']").compactMap(\.stringValue) == ["Images/0001.png"])
660 #expect(try content.nodes(forXPath: "//*[local-name()='table-cell']").count == 2)
661 let meta = try XMLDocument(data: entries[3].data)
662 #expect(try meta.nodes(forXPath: "//*[local-name()='title']").first?.stringValue == "T & U")
663 }
664
665 /// The text system reads the file: headings, list items, table cells and notes.
666 @Test func opensInTextKit() throws {
667 let text = "#+TITLE: Opened\n\n* Heading\n- item one\n- item two\n\n| a | b |\n|---+---|\n| 1 | 2 |\n\nA note.[fn:1]\n\n[fn:1] Noted.\n"
668 let data = try ODTExport.document(text, path: "/tmp/doc.org")
669 let string = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.openDocument], documentAttributes: nil).string
670 for word in ["Opened", "Heading", "item one", "item two", "a", "2", "A note."] {
671 #expect(string.contains(word), "\(word) in \(string)")
672 }
673 }
674
675 /// What the native export can't write the way ox-odt does stops the export instead.
676 @Test(arguments: [
677 "*************** Task\nBody.\n*************** END\n",
678 "Here <<there>> and [[there]].\n",
679 "#+begin_src emacs-lisp\n(x) (ref:a)\n#+end_src\n[[(a)]]\n",
680 "#+ATTR_ODT: :style TableWithHeaderRowAndColumn\n| a |\n",
681 "Code src_python[:exports code]{1 + 1} here.\n",
682 "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n",
683 "- a quote\n #+begin_quote\n | q |\n #+end_quote\n",
684 "#+OPTIONS: p:t\n* H\nSCHEDULED: <2024-01-01 Mon>\n",
685 "#+OPTIONS: broken-links:t\nSee [[nowhere]].\n",
686 "#+OPTIONS: c:t\n* H\nCLOCK: [2024-01-01 Mon 10:00]--[2024-01-01 Mon 11:00] => 1:00\n",
687 "#+OPTIONS: prop:t\n* H\n:PROPERTIES:\n:A: 1\n:END:\n",
688 "#+OPTIONS: ::nil\n: fixed\n",
689 "#+OPTIONS: *:nil\n*bold*\n",
690 "#+OPTIONS: stat:nil\n* H [1/2]\n",
691 "#+OPTIONS: tasks:nil\n* TODO H\n",
692 "#+OPTIONS: <:nil\n<2024-01-01 Mon>\n",
693 "#+OPTIONS: arch:nil\n* H :ARCHIVE:\nBody.\n",
694 "#+OPTIONS: email:t\n#+EMAIL: a@b.c\nText.\n",
695 "#+OPTIONS: ':t\n\"quoted\"\n",
696 "#+OPTIONS: tex:verbatim\n\\(x\\)\n",
697 "#+OPTIONS: d:(\"NOTES\")\n:NOTES:\nx\n:END:\n",
698 ])
699 func refuses(_ text: String) {
700 #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") }
701 }
702
703 @Test func imageFiles() throws {
704 let files = ODTExport.imageFiles("[[file:a.png]] [[./b.jpg][desc]] [[https://x/c.png]] [[/abs/d.svg]] [[https://x][file:e.png]]\n", path: "/doc/notes.org")
705 #expect(files == ["/doc/a.png", "/abs/d.svg", "/doc/e.png"])
706 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
707 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
708 defer { try? FileManager.default.removeItem(at: folder) }
709 try "[[file:/elsewhere/f.png]]\n".write(to: folder.appendingPathComponent("part.org"), atomically: true, encoding: .utf8)
710 #expect(ODTExport.imageFiles("#+INCLUDE: \"part.org\"\n", path: folder.appendingPathComponent("doc.org").path) == ["/elsewhere/f.png"])
711 let sub = folder.appendingPathComponent("sub")
712 try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
713 try "[[file:g.png]] [[https://x][file:../h.png]]\n".write(to: sub.appendingPathComponent("part.inc"), atomically: true, encoding: .utf8)
714 #expect(ODTExport.imageFiles("#+INCLUDE: \"sub/part.inc\"\n", path: folder.appendingPathComponent("doc.org").path)
715 == [sub.appendingPathComponent("g.png").path, folder.appendingPathComponent("h.png").path])
716 }
717
718 /// Every style `content.xml` names is in `styles.xml` or its automatic styles.
719 @Test func stylesDefined() throws {
720 let text = "#+OPTIONS: pri:t\n* TODO [#A] One\n* [#B] Two\n* DONE [#C] Three\n"
721 let parts = try ODTExport.parts(text, path: "/tmp/doc.org")
722 let content = String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
723 let styles = String(decoding: parts.first { $0.name == "styles.xml" }!.data, as: UTF8.self)
724 let used = Set(content.matches(of: /text:style-name="([^"]+)"/).map { String($0.1) })
725 #expect(used.isSuperset(of: ["OrgPriority-A", "OrgPriority-B", "OrgPriority-C"]))
726 for name in used {
727 #expect(styles.contains("style:name=\"\(name)\"") || content.contains("style:name=\"\(name)\""), "\(name)")
728 }
729 }
730}
docs/manual/guide/03-keys.org +1 −1
@@ -995,7 +995,7 @@ When a key appears in several rows, it runs the command whose condition holds at
995| Copy as Rich Text (=app.copy-rich-text=) | — | — | — | Copies the selection, or the file, as HTML, RTF and plain text. | 995| Copy as Rich Text (=app.copy-rich-text=) | — | — | — | Copies the selection, or the file, as HTML, RTF and plain text. |
996| Export to PDF with Emacs (=app.export.pdf=) | =C-c C-e l p= | — | =SPC m e l p= (N) | Exports to PDF through Emacs (=org-latex-export-to-pdf=). | 996| Export to PDF with Emacs (=app.export.pdf=) | =C-c C-e l p= | — | =SPC m e l p= (N) | Exports to PDF through Emacs (=org-latex-export-to-pdf=). |
997| Export to LaTeX (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX without Emacs, as =org-latex-export-to-latex= does. | 997| Export to LaTeX (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX without Emacs, as =org-latex-export-to-latex= does. |
998| Export to ODT with Emacs (=app.export.odt=) | =C-c C-e o o= | — | — | Exports to ODT through Emacs (=org-odt-export-to-odt=). | 998| Export to ODT (=app.export.odt=) | =C-c C-e o o= | — | — | Exports to OpenDocument text without Emacs, as =org-odt-export-to-odt= does. |
999| Export to Plain Text with Emacs (=app.export.text=) | =C-c C-e t u= | — | — | Exports to plain text through Emacs (=org-ascii-export-to-ascii=). | 999| Export to Plain Text with Emacs (=app.export.text=) | =C-c C-e t u= | — | — | Exports to plain text through Emacs (=org-ascii-export-to-ascii=). |
1000| Export to iCalendar (=app.export.icalendar=) | =C-c C-e c f= | — | — | Exports to an =.ics= calendar (=org-icalendar-export-to-ics=). | 1000| Export to iCalendar (=app.export.icalendar=) | =C-c C-e c f= | — | — | Exports to an =.ics= calendar (=org-icalendar-export-to-ics=). |
1001| Export Agenda Files to iCalendar (=app.export.icalendar-agenda=) | =C-c C-e c a= | — | — | Writes an =.ics= beside each agenda file (=org-icalendar-export-agenda-files=). | 1001| Export Agenda Files to iCalendar (=app.export.icalendar-agenda=) | =C-c C-e c a= | — | — | Writes an =.ics= beside each agenda file (=org-icalendar-export-agenda-files=). |
docs/manual/guide/12-export.org +26 −10
@@ -1,6 +1,6 @@
1#+TITLE: Export 1#+TITLE: Export
2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF, plain text, iCalendar and LaTeX, and to ODT and ASCII through Emacs; copying as rich text. 2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar and LaTeX, and to ASCII through Emacs; copying as rich text.
3#+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF, plain text, iCalendar and LaTeX itself, and the Mac download version hands ODT, ASCII and LaTeX-made PDF to Emacs. 3#+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar and LaTeX itself, and the Mac download version hands ASCII and LaTeX-made PDF to Emacs.
4 4
5* Exporting a file 5* Exporting a file
6 6
@@ -19,7 +19,7 @@ Export works on the file in the current editor, using its text as it is now, sav
19| Plain text | Export to Plain Text | — | — | no | 19| Plain text | Export to Plain Text | — | — | no |
20| PDF through LaTeX | Export to PDF with Emacs | =C-c C-e l p= | =SPC m e l p=, =C-c C-e l p= | yes | 20| PDF through LaTeX | Export to PDF with Emacs | =C-c C-e l p= | =SPC m e l p=, =C-c C-e l p= | yes |
21| LaTeX | Export to LaTeX | =C-c C-e l l= | =C-c C-e l l= | no | 21| LaTeX | Export to LaTeX | =C-c C-e l l= | =C-c C-e l l= | no |
22| ODT | Export to ODT with Emacs | =C-c C-e o o= | =C-c C-e o o= | yes | 22| ODT | Export to ODT | =C-c C-e o o= | =C-c C-e o o= | no |
23| ASCII text | Export to Plain Text with Emacs | =C-c C-e t u= | =C-c C-e t u= | yes | 23| ASCII text | Export to Plain Text with Emacs | =C-c C-e t u= | =C-c C-e t u= | yes |
24| iCalendar | Export to iCalendar | =C-c C-e c f= | =C-c C-e c f= | no | 24| iCalendar | Export to iCalendar | =C-c C-e c f= | =C-c C-e c f= | no |
25| iCalendar, every agenda file | Export Agenda Files to iCalendar | =C-c C-e c a= | =C-c C-e c a= | no | 25| iCalendar, every agenda file | Export Agenda Files to iCalendar | =C-c C-e c a= | =C-c C-e c a= | no |
@@ -35,7 +35,7 @@ The [[file:../install.org][Mac App Store version]] has the eleven commands that
35 35
36*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has: 36*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has:
37 37
38- *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT (Emacs), LaTeX, Plain text, ASCII (Emacs) or iCalendar. The App Store version lists LaTeX last. 38- *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT, LaTeX, Plain text, ASCII (Emacs) or iCalendar. The App Store version lists LaTeX last.
39- *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. iCalendar is the exception: there the subtree's heading is an entry like any other. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading. 39- *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. iCalendar is the exception: there the subtree's heading is an entry like any other. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading.
40- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF, Word, RTF, plain text, ODT and iCalendar. 40- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF, Word, RTF, plain text, ODT and iCalendar.
41- *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension. 41- *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension.
@@ -46,7 +46,7 @@ The dialog remembers the format and the *Open after export* setting. The PDF set
46 46
47** On iOS 47** On iOS
48 48
49The Export menu offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, iCalendar and LaTeX, and Copy as Rich Text. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac, except that LaTeX has no =\author= unless the file has =#+AUTHOR:=. ODT, ASCII and PDF through LaTeX are not available on iOS, nor are the agenda-file iCalendar exports. 49The Export menu offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, ODT, iCalendar and LaTeX, and Copy as Rich Text. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac, except that LaTeX and ODT have no author unless the file has =#+AUTHOR:=. ASCII and PDF through LaTeX are not available on iOS, nor are the agenda-file iCalendar exports.
50 50
51* HTML export 51* HTML export
52 52
@@ -126,7 +126,7 @@ LaTeX fragments (=\(…\)=, =\[…\]=, =$…$=, =$$…$$=) and LaTeX environment
126| =:lines "5-10"= | Only those lines; either end may be left out. | 126| =:lines "5-10"= | Only those lines; either end may be left out. |
127| =:minlevel 2= | Shift the included headings so the shallowest is at that level. | 127| =:minlevel 2= | Shift the included headings so the shallowest is at that level. |
128 128
129A file that cannot be read is replaced by an empty line. 129A file that cannot be read is replaced by an empty line. In a file included as Org from another folder, relative =file:= links are rewritten relative to the Org file, as Org does: =[[file:pic.png]]= in =sub/part.org= becomes =[[file:sub/pic.png]]=. A link written without =file:=, such as =[[./pic.png]]=, comes back as =[[sub/pic.png]]=, which Org then reads as a link to a heading.
130 130
131** Macros 131** Macros
132 132
@@ -248,6 +248,23 @@ For Org's own ASCII layout, with underlined headings and drawn tables, use Expor
248 248
249*Copy as Rich Text* (the command palette on the Mac, the Export menu on iOS) puts the selection, or the whole file when nothing is selected, on the clipboard as HTML, RTF and plain text. Paste it into Mail, Pages, Word or a web form to get the formatted text. On iOS it copies the whole file. 249*Copy as Rich Text* (the command palette on the Mac, the Export menu on iOS) puts the selection, or the whole file when nothing is selected, on the clipboard as HTML, RTF and plain text. Paste it into Mail, Pages, Word or a web form to get the formatted text. On iOS it copies the whole file.
250 250
251* ODT export
252
253Export to ODT writes an OpenDocument text file (=.odt=) for LibreOffice, Pages or Word. orgstar writes it itself, on the Mac and on iOS, the way Emacs's =ox-odt= does under =emacs -Q=: the same headings, paragraphs, lists, tables, links, notes and images, with ox-odt's style names, so a template that restyles ox-odt's output restyles this one too.
254
255- The title, subtitle (=#+SUBTITLE:=), author and date come first, then the table of contents and the text. On the Mac, without =#+AUTHOR:=, the author is your account's full name, as =user-full-name= is in Emacs. Without =#+TITLE:= there is no title.
256- Headings are numbered by the word processor, to the depth =num= gives (=num:t= numbers every level). Headings deeper than =H= become list items. =#+TOC: headlines= puts a table of contents where it is; =local= limits it to the section, counts the depth from there and leaves out the title.
257- Footnotes are the word processor's own notes, numbered as ox-odt numbers them: those referred to in the text first, then those referred to only from other notes. A note referred to again shows its number.
258- Tables keep their header rows, alignment cookies, column groups and cell borders. A table inside a list item ends the list, sits indented below it, and the list carries on after it, as in ox-odt.
259- Images from =file:= links (PNG, JPEG, GIF and SVG) are put inside the file. Their size is their pixels at 96 to the inch, or =#+ATTR_ODT: :width=, =:length= (the height) or =:scale=, and no more than 17 by 20 cm. A caption or =#+NAME:= numbers figures, tables and source blocks, and a link to the name shows the number.
260- LaTeX fragments and environments are kept as written, in code style, as ox-odt does without a MathML converter. Source blocks are not colored; a language Emacs has no mode for gets ox-odt's plain code style.
261- Without =:exports=, every source block exports its code, =dot=, =plantuml=, =ditaa=, =gnuplot=, =latex= and =lilypond= included: =emacs -Q= loads no Babel library to give them =results=. A line of only spaces in a source block is exported empty, unless =-i= keeps the indentation.
262- Of the =#+OPTIONS=, =\n=, =f=, =|=, =e= and =d= (=t= or =nil=) are read, along with those every export reads.
263- =#+ODT:= lines, =#+BEGIN_EXPORT odt= blocks and =@@odt:...@@= snippets go in as they are.
264- The styles (=styles.xml=) are orgstar's own: A4 pages with 2 cm margins. =#+ODT_STYLES_FILE:= is not read.
265
266The export stops with a message, instead of writing something different from ox-odt, for: a link that leads nowhere, an image file that can't be read, inline tasks, table templates (=#+ATTR_ODT: :style=), a link without a description to a =<<target>>= or to a code line that isn't numbered, an inline source block exported as code, a table in a quote or other block inside a list, an annotation in a dated document, =#+TOC:= with =:target=, and these =#+OPTIONS= at other than their default: =p=, =c=, =prop=, =broken-links=, =:=, =*=, =stat=, =tasks=, =<=, =arch=, =email=, ='=, =tex= other than =t= or =nil=, and =d= with a list of drawers. ODT export is always the whole document: the export dialog's *Body only* doesn't apply.
267
251* Markdown export 268* Markdown export
252 269
253Markdown export writes GitHub-flavored Markdown: 270Markdown export writes GitHub-flavored Markdown:
@@ -291,7 +308,7 @@ Differences from Org: diary sexps (=%%(…)= lines and =<%%(…)>= timestamps) a
291 308
292* Publishing 309* Publishing
293 310
294Publishing (=org-publish=) exports a folder of Org files to a folder of HTML, Markdown or LaTeX files, copies other files beside them, and can write a sitemap. Projects are =[[publish]]= tables in =config.toml=, as =org-publish-project-alist= entries are in Emacs: 311Publishing (=org-publish=) exports a folder of Org files to a folder of HTML, Markdown, LaTeX or ODT files, copies other files beside them, and can write a sitemap. Projects are =[[publish]]= tables in =config.toml=, as =org-publish-project-alist= entries are in Emacs:
295 312
296#+BEGIN_SRC toml 313#+BEGIN_SRC toml
297[[publish]] 314[[publish]]
@@ -324,7 +341,7 @@ components = "notes static"
324| =recursive= | Files in subfolders too | =false= | 341| =recursive= | Files in subfolders too | =false= |
325| =exclude= | An Emacs regexp on the file's path under =base-directory=; matching files are left out | | 342| =exclude= | An Emacs regexp on the file's path under =base-directory=; matching files are left out | |
326| =include= | More files, relative to =base-directory=, separated by spaces | | 343| =include= | More files, relative to =base-directory=, separated by spaces | |
327| =publishing-function= | =org-html-publish-to-html=, =org-md-publish-to-md=, =org-latex-publish-to-latex= or =org-publish-attachment= (copied as they are), several separated by spaces | =org-html-publish-to-html= | 344| =publishing-function= | =org-html-publish-to-html=, =org-md-publish-to-md=, =org-latex-publish-to-latex=, =org-odt-publish-to-odt= or =org-publish-attachment= (copied as they are), several separated by spaces | =org-html-publish-to-html= |
328| =body-only= | The export's body only | =false= | 345| =body-only= | The export's body only | =false= |
329| =auto-sitemap= | Write a sitemap into =base-directory= and publish it with the rest | =false= | 346| =auto-sitemap= | Write a sitemap into =base-directory= and publish it with the rest | =false= |
330| =sitemap-filename= | The sitemap's name | ="sitemap.org"= | 347| =sitemap-filename= | The sitemap's name | ="sitemap.org"= |
@@ -350,12 +367,11 @@ A file whose published copy is newer than it is skipped, as Org skips files that
350 367
351* Exporting through Emacs 368* Exporting through Emacs
352 369
353On the Mac, PDF, ODT and plain text exports are done by Emacs, with the =ox= functions Emacs's dispatcher uses: 370On the Mac, PDF and plain text exports are done by Emacs, with the =ox= functions Emacs's dispatcher uses:
354 371
355| Format | Function | 372| Format | Function |
356|------------+-----------------------------| 373|------------+-----------------------------|
357| PDF | =org-latex-export-to-pdf= | 374| PDF | =org-latex-export-to-pdf= |
358| ODT | =org-odt-export-to-odt= |
359| Plain text | =org-ascii-export-to-ascii= | 375| Plain text | =org-ascii-export-to-ascii= |
360 376
361LaTeX goes to Emacs (=org-latex-export-to-latex=) only for a file orgstar's own LaTeX export can't write as Emacs would; see /LaTeX export/. The [[file:../install.org][Mac App Store version]] doesn't run Emacs and has none of these exports. 377LaTeX goes to Emacs (=org-latex-export-to-latex=) only for a file orgstar's own LaTeX export can't write as Emacs would; see /LaTeX export/. The [[file:../install.org][Mac App Store version]] doesn't run Emacs and has none of these exports.
docs/manual/guide/14-ios.org +3 −3
@@ -329,9 +329,9 @@ The app icon's badge counts the entries in the agenda's Overdue section that are
329 329
330* Export 330* Export
331 331
332Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, iCalendar and LaTeX, and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does. For a file the LaTeX export can't write as Emacs would, the share sheet stops and "Can't export to LaTeX: " and the reason show at the bottom of the screen. 332Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, ODT, iCalendar and LaTeX, and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does. For a file the LaTeX export can't write as Emacs would, the share sheet stops and "Can't export to LaTeX: " and the reason show at the bottom of the screen.
333 333
334PDF export follows =pdf-margin=, =pdf-font= and =pdf-page-numbers= in =config.toml=, and Word files get heading styles and the file's images, as on the Mac. ODT, ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]]. 334PDF export follows =pdf-margin=, =pdf-font= and =pdf-page-numbers= in =config.toml=, and Word files get heading styles and the file's images, as on the Mac. ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]].
335 335
336* Code blocks and tables 336* Code blocks and tables
337 337
@@ -436,7 +436,7 @@ Quick Look in the Files app shows org files as the HTML export renders them.
436* What the Mac has that iOS doesn't 436* What the Mac has that iOS doesn't
437 437
438- In the download version: running code blocks in languages other than Emacs Lisp and JavaScript, Emacs Lisp beyond orgstar's interpreter, JavaScript that needs node, and tables that need Emacs. 438- In the download version: running code blocks in languages other than Emacs Lisp and JavaScript, Emacs Lisp beyond orgstar's interpreter, JavaScript that needs node, and tables that need Emacs.
439- Publishing, and in the download version ODT, ASCII and LaTeX-made PDF export. 439- Publishing, and in the download version ASCII and LaTeX-made PDF export.
440- Idle detection while a clock runs. 440- Idle detection while a clock runs.
441- Import from Emacs of agenda folders. 441- Import from Emacs of agenda folders.
442- The Columns inspector, the buffer list and tab bar, and resizing panes by dragging their divider. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]). 442- The Columns inspector, the buffer list and tab bar, and resizing panes by dragging their divider. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]).
docs/manual/guide/15-alongside-emacs.org +2 −2
@@ -120,9 +120,9 @@ Some features run Emacs in batch mode on the Mac. Everything else works without
120| Emacs Lisp source blocks (=emacs-lisp=, =elisp=) | The block, in =emacs -Q --batch= | 120| Emacs Lisp source blocks (=emacs-lisp=, =elisp=) | The block, in =emacs -Q --batch= |
121| Table formulas outside what orgstar computes itself | =org-table-recalculate= on a copy of the file; the table's new text replaces the old one if the table didn't change meanwhile | 121| Table formulas outside what orgstar computes itself | =org-table-recalculate= on a copy of the file; the table's new text replaces the old one if the table didn't change meanwhile |
122| Lisp table formulas that orgstar's Emacs Lisp interpreter can't evaluate | The same; orgstar first asks whether to run Lisp (yes, no, always) | 122| Lisp table formulas that orgstar's Emacs Lisp interpreter can't evaluate | The same; orgstar first asks whether to run Lisp (yes, no, always) |
123| Export to PDF, ODT and plain text, and LaTeX orgstar can't write itself | =org-latex-export-to-pdf=, =org-odt-export-to-odt=, =org-ascii-export-to-ascii= or =org-latex-export-to-latex= | 123| Export to PDF and plain text, and LaTeX orgstar can't write itself | =org-latex-export-to-pdf=, =org-ascii-export-to-ascii= or =org-latex-export-to-latex= |
124 124
125HTML, Markdown and LaTeX export don't use Emacs. See [[file:11-code-blocks.org][Code blocks]], [[file:10-tables.org][Tables]] and [[file:12-export.org][Export]]. 125HTML, Markdown, ODT and LaTeX export don't use Emacs. See [[file:11-code-blocks.org][Code blocks]], [[file:10-tables.org][Tables]] and [[file:12-export.org][Export]].
126 126
127** How Emacs is found 127** How Emacs is found
128 128
docs/manual/install.org +14 −14
@@ -7,7 +7,7 @@
7- macOS 26 or later. 7- macOS 26 or later.
8- Optional, for the download version: GNU Emacs, for the features that hand work to it 8- Optional, for the download version: GNU Emacs, for the features that hand work to it
9 (Emacs Lisp code blocks that need full Emacs, Lisp table formulas the built-in 9 (Emacs Lisp code blocks that need full Emacs, Lisp table formulas the built-in
10 interpreter can't run, and export to PDF through LaTeX, ODT and ASCII). See 10 interpreter can't run, and export to PDF through LaTeX and ASCII). See
11 [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]]. 11 [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]].
12 12
13* The Mac app 13* The Mac app
@@ -52,19 +52,19 @@ App Store version.
52 52
53** What it does differently 53** What it does differently
54 54
55| Feature | Mac App Store version | Download version | 55| Feature | Mac App Store version | Download version |
56|----------------------------+--------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------| 56|----------------------------+-------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------|
57| Code blocks | Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore | Every language installed; Emacs Lisp in Emacs; JavaScript in node, or JavaScriptCore without it | 57| Code blocks | Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore | Every language installed; Emacs Lisp in Emacs; JavaScript in node, or JavaScriptCore without it |
58| Sessions, graphics | JavaScript sessions; no graphics | Yes | 58| Sessions, graphics | JavaScript sessions; no graphics | Yes |
59| Tangling | Yes | Yes | 59| Tangling | Yes | Yes |
60| Table formulas | Those orgstar computes itself | The rest in Emacs as well | 60| Table formulas | Those orgstar computes itself | The rest in Emacs as well |
61| Plots | Drawn with Swift Charts | gnuplot when installed, else Swift Charts | 61| Plots | Drawn with Swift Charts | gnuplot when installed, else Swift Charts |
62| Export | HTML, Markdown, PDF, Word, RTF, plain text, iCalendar, LaTeX; publishing | Also PDF through LaTeX, ODT and ASCII, in Emacs | 62| Export | HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX; publishing | Also PDF through LaTeX and ASCII, in Emacs |
63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= | 63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= |
64| Files outside your folders | After you grant access to their folder | Directly | 64| Files outside your folders | After you grant access to their folder | Directly |
65| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked | 65| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked |
66| Updates | The Mac App Store | Built in, or Homebrew | 66| Updates | The Mac App Store | Built in, or Homebrew |
67| orgstar+ | In-app purchase, shared with iPhone and iPad | License key | 67| orgstar+ | In-app purchase, shared with iPhone and iPad | License key |
68 68
69A block in another language reports "/language/ blocks don't run in this version of 69A block in another language reports "/language/ blocks don't run in this version of
70orgstar." An Emacs Lisp block that uses more than the interpreter has reports "This block uses 70orgstar." An Emacs Lisp block that uses more than the interpreter has reports "This block uses
l10n/Localizable.xcstrings +6 −6
@@ -11714,37 +11714,37 @@
11714 } 11714 }
11715 } 11715 }
11716 }, 11716 },
11717 "Export to ODT with Emacs": { 11717 "Export to ODT": {
11718 "comment": "Command title", 11718 "comment": "Command title",
11719 "localizations": { 11719 "localizations": {
11720 "de": { 11720 "de": {
11721 "stringUnit": { 11721 "stringUnit": {
11722 "state": "translated", 11722 "state": "translated",
11723 "value": "Mit Emacs als ODT exportieren" 11723 "value": "Als ODT exportieren"
11724 } 11724 }
11725 }, 11725 },
11726 "es": { 11726 "es": {
11727 "stringUnit": { 11727 "stringUnit": {
11728 "state": "translated", 11728 "state": "translated",
11729 "value": "Exportar a ODT con Emacs" 11729 "value": "Exportar a ODT"
11730 } 11730 }
11731 }, 11731 },
11732 "fr": { 11732 "fr": {
11733 "stringUnit": { 11733 "stringUnit": {
11734 "state": "translated", 11734 "state": "translated",
11735 "value": "Exporter en ODT avec Emacs" 11735 "value": "Exporter en ODT"
11736 } 11736 }
11737 }, 11737 },
11738 "ja": { 11738 "ja": {
11739 "stringUnit": { 11739 "stringUnit": {
11740 "state": "translated", 11740 "state": "translated",
11741 "value": "EmacsでODTに書き出す" 11741 "value": "ODTに書き出す"
11742 } 11742 }
11743 }, 11743 },
11744 "pt-BR": { 11744 "pt-BR": {
11745 "stringUnit": { 11745 "stringUnit": {
11746 "state": "translated", 11746 "state": "translated",
11747 "value": "Exportar para ODT com o Emacs" 11747 "value": "Exportar para ODT"
11748 } 11748 }
11749 } 11749 }
11750 } 11750 }