Commit 32027d8982

32027d89826a5120985d63ced2ca8d96b3525b9a

parent: bcf0a0e2cb

Verified · cmc

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

Native ODT export from the parse tree

Layout: unified · split

Sources/OrgApp/DocxWriter.swift +1 −48
@@ -1,4 +1,5 @@
11import Foundation
2import OrgCore
23#if os(macOS)
34import AppKit
45typealias DocxFont = NSFont
@@ -302,51 +303,3 @@ enum DocxWriter {
302303 .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
303304 }
304305}
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/OrgCore/Export/ODTExport.swift added +1361
@@ -0,0 +1,1361 @@
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 public static func imageFiles(_ text: String, settings: OrgSettings = .default, path: String) -> [String] {
31 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
32 return OrgParser.parse(text, defaults: settings).root.descendants().compactMap { node in
33 guard node.kind == .link, node.firstChild(.linkDescription) == nil,
34 let file = ODTRenderer.filePath(node.tokens.first { $0.kind == .linkPath }?.text ?? ""), ODTRenderer.isImage(file) else { return nil }
35 return ODTRenderer.expand(file, directory: directory).path
36 }
37 }
38
39 static func parts(
40 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(),
41 author: String? = nil, language: String = "en"
42 ) throws -> [(name: String, data: Data)] {
43 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
44 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
45 let options = ExportOptions.parse(settings.setupKeywords + text)
46 let meta = HTMLExport.metadata(text, settings: settings)
47 let keywords = Self.keywords(text, settings: settings)
48 let renderer = ODTRenderer(settings: settings, options: options, directory: directory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath))
49 renderer.language = meta.language ?? language
50
51 // The title isn't part of the document Org processes citations in: they drop out.
52 renderer.inTitle = true
53 let title = meta.title.map(renderer.inlineString) ?? ""
54 let subtitle = keywords["SUBTITLE"].map(renderer.inlineString) ?? ""
55 let authorName = (meta.author ?? author).flatMap { $0.isEmpty ? nil : $0 }.map(renderer.inlineString)
56 renderer.inTitle = false
57 renderer.author = authorName
58 renderer.dated = !(meta.date ?? "").isEmpty
59 renderer.citations = CiteProcessor(text: text, directory: directory)
60 let body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
61 let date = options.date ? meta.date.flatMap { $0.isEmpty ? nil : renderer.inlineString($0) } : nil
62 if let failure = renderer.failure { throw failure }
63
64 var preamble = ""
65 if options.title, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
66 preamble += "\n<text:p text:style-name=\"OrgTitle\">\n<text:title>\(title)</text:title></text:p>\n"
67 preamble += "\n<text:p text:style-name=\"OrgTitle\"/>\n"
68 if !subtitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
69 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"
70 preamble += "<text:p text:style-name=\"OrgSubtitle\"/>\n"
71 }
72 }
73 if options.author, let authorName {
74 preamble += "\n<text:p text:style-name=\"OrgSubtitle\"><text:initial-creator>\(authorName)</text:initial-creator></text:p>"
75 preamble += "\n<text:p text:style-name=\"OrgSubtitle\"/>"
76 }
77 if let date { preamble += "\n<text:p text:style-name=\"OrgSubtitle\">\(date)</text:p><text:p text:style-name=\"OrgSubtitle\"/>" }
78 let contents = ODTTemplate.content(automaticStyles: renderer.automaticStyles(), body: preamble + renderer.tableOfContents() + body)
79
80 let stamp = meta.date.flatMap(Timestamp.parse).map { stamp -> String in
81 let p = stamp.start
82 return String(format: "%04d-%02d-%02dT%02d:%02d:00", p.year, p.month, p.day, p.hour ?? 0, p.minute ?? 0)
83 } ?? Self.isoDate(now)
84 let metaXML = ODTTemplate.meta(
85 author: authorName.map(ODTRenderer.stripped) ?? "", date: options.date ? stamp : nil, keywords: keywords["KEYWORDS"] ?? "",
86 description: keywords["DESCRIPTION"] ?? "", title: ODTRenderer.stripped(title), subtitle: ODTRenderer.stripped(subtitle)
87 )
88
89 var parts: [(name: String, data: Data)] = [("mimetype", Data(ODTTemplate.mimetype.utf8))]
90 parts.append(("content.xml", Data(contents.utf8)))
91 parts.append(("styles.xml", Data(ODTTemplate.styles(numbered: options.num ?? 0).utf8)))
92 parts.append(("meta.xml", Data(metaXML.utf8)))
93 parts += renderer.images.map { ($0.name, $0.data) }
94 parts.append(("META-INF/manifest.xml", Data(ODTTemplate.manifest(images: renderer.images.map(\.name)).utf8)))
95 return parts
96 }
97
98 /// `#+SUBTITLE`, `#+KEYWORDS` and `#+DESCRIPTION`: lines of the same keyword joined.
99 static func keywords(_ text: String, settings: OrgSettings) -> [String: String] {
100 let tree = OrgParser.parse(text, defaults: settings)
101 let own = tree.root.children.filter { $0.kind == .zerothSection }.flatMap { $0.children.filter { $0.kind == .keyword } }.map(\.text)
102 var values: [String: String] = [:]
103 for line in settings.setupKeywords.split(separator: "\n").map(String.init) + own {
104 guard let m = line.firstMatch(of: /^[ \t]*#\+([A-Za-z_]+):[ \t]*(.*?)[ \t]*\n?$/) else { continue }
105 let key = m.1.uppercased()
106 guard ["SUBTITLE", "KEYWORDS", "DESCRIPTION"].contains(key) else { continue }
107 values[key] = values[key].map { $0 + (key == "DESCRIPTION" ? "\n" : " ") + m.2 } ?? String(m.2)
108 }
109 return values
110 }
111
112 static func isoDate(_ date: Date) -> String {
113 let formatter = DateFormatter()
114 formatter.locale = Locale(identifier: "en_US_POSIX")
115 formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
116 return formatter.string(from: date)
117 }
118}
119
120final class ODTRenderer {
121 let settings: OrgSettings
122 let options: ExportOptions
123 let directory: URL
124 var language = "en"
125 var citations: CiteProcessor?
126 /// Rendering the title, where Org exports citations as nothing.
127 var inTitle = false
128 /// The document's author, rendered, and whether it has a date, for annotations.
129 var author: String?
130 var dated = false
131 /// The first error, which stops the export as ox-odt's errors do.
132 private(set) var failure: ODTExport.Failure?
133 private(set) var images: [(name: String, data: Data)] = []
134
135 init(settings: OrgSettings, options: ExportOptions, directory: URL) {
136 self.settings = settings
137 self.options = options
138 self.directory = directory
139 }
140
141 private func fail(_ message: String) -> String {
142 if failure == nil { failure = ODTExport.Failure(message: message) }
143 return ""
144 }
145
146 // MARK: - Collecting
147
148 /// An exported heading, by its start in the document.
149 struct Heading {
150 var key: Int
151 var level: Int
152 var ancestors: [Int]
153 var info: HeadingInfo?
154 var node: SyntaxNode
155 var relative = 1
156 var number: [Int]?
157 var lowLevel = false
158 var reference = ""
159 }
160
161 /// A captioned or named table, source block or image: its category, sequence and label.
162 struct Label {
163 var category: String
164 var variable: String
165 var sequence: String
166 var reference: String?
167 }
168
169 private var headings: [Int: Heading] = [:]
170 private var headingOrder: [Int] = []
171 private var targets: [(words: [String], key: Int, reference: String)] = []
172 private var names: [(words: [String], key: Int)] = []
173 private var labels: [Int: Label] = [:]
174 private var enumerables: [(key: Int, category: String, ancestors: [Int])] = []
175 private var references = 0
176 private var selected: Set<Int>?
177 private var documentTree: OrgTree?
178 private var blockLocs: [String: [Int?]] = [:]
179 private var definitions: [String: (text: String, base: Int)] = [:]
180
181 /// Where the tree being read starts in the document, so elements read from a block's or a
182 /// footnote's contents keep their place; how deep in such contents it is.
183 private var base = 0
184 private var depth = 0
185 /// Elements after a footnote definition that belong to it, by their start.
186 private var absorbed: Set<Int> = []
187
188 private func newReference() -> String {
189 references += 1
190 return String(format: "org%07x", references &* 2_654_435_761 & 0xFFF_FFFF)
191 }
192
193 private static func words(_ s: String) -> [String] { s.split(whereSeparator: \.isWhitespace).map(String.init) }
194
195 private func collect(_ tree: OrgTree) {
196 let model = DocumentModel(tree: tree)
197 var infos: [Int: HeadingInfo] = [:]
198 for heading in model.headings { infos[heading.headingRange.lowerBound] = heading }
199 collect(tree.root, ancestors: [], infos: infos)
200 let top = headingOrder.compactMap { headings[$0]?.level }.min() ?? 1
201 var counters: [Int] = []
202 for key in headingOrder {
203 var heading = headings[key]!
204 heading.relative = heading.level - top + 1
205 heading.lowLevel = heading.relative > options.headlineLevels
206 heading.reference = newReference()
207 let unnumbered = (heading.ancestors + [key]).contains { key in
208 guard let value = headings[key]?.info?.properties.last(where: { $0.key.uppercased() == "UNNUMBERED" })?.value else { return false }
209 return value.trimmingCharacters(in: .whitespaces) != "nil"
210 }
211 if let num = options.num, heading.relative <= num, !unnumbered {
212 let index = heading.relative - 1
213 if counters.count <= index { counters += Array(repeating: 0, count: index + 1 - counters.count) }
214 counters[index] += 1
215 for i in (index + 1)..<counters.count { counters[i] = 0 }
216 heading.number = Array(counters.prefix(index + 1))
217 }
218 headings[key] = heading
219 }
220 // `org-odt--enumerate`: numbered within the closest numbered heading at level 2 or
221 // above, else through the document.
222 var counts: [String: Int] = [:]
223 for (index, item) in enumerables.enumerated() {
224 let scope = item.ancestors.reversed().first { headings[$0].map { $0.relative <= 2 && $0.number != nil } ?? false }
225 let ordinal = enumerables[...index].filter { $0.category == item.category && (scope.map($0.ancestors.contains) ?? true) }.count
226 counts[item.category, default: 0] += 1
227 let sequence = (scope.flatMap { headings[$0]?.number }.map { $0.map(String.init).joined(separator: ".") + "." } ?? "") + String(ordinal)
228 let named = names.contains { $0.key == item.key }
229 let variable = ["Table": "Table", "Figure": "Illustration", "Listing": "Listing"][item.category]!
230 labels[item.key] = Label(category: item.category, variable: variable, sequence: sequence, reference: named ? newReference() : nil)
231 }
232 }
233
234 private func collect(_ node: SyntaxNode, ancestors: [Int], infos: [Int: HeadingInfo]) {
235 var affiliated: [String: String] = [:]
236 for child in node.children {
237 if child.kind == .affiliatedKeyword {
238 if let m = child.text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
239 affiliated[m.1.uppercased()] = String(m.2)
240 }
241 continue
242 }
243 defer { affiliated = [:] }
244 if depth == 0, absorbed.contains(child.range.lowerBound) { continue }
245 let key = base + child.range.lowerBound
246 if let name = affiliated["NAME"] { names.append((Self.words(name), key)) }
247 let captioned = affiliated["CAPTION"] != nil || affiliated["NAME"] != nil
248 switch child.kind {
249 case .section:
250 guard let heading = child.firstChild(.heading) else { collect(child, ancestors: ancestors, infos: infos); continue }
251 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
252 if export == .nothing { continue }
253 let headingKey = base + heading.range.lowerBound
254 let level = heading.tokens.first { $0.kind == .stars }?.text.count ?? 1
255 headings[headingKey] = Heading(key: headingKey, level: level, ancestors: ancestors, info: infos[heading.range.lowerBound], node: heading)
256 headingOrder.append(headingKey)
257 collect(heading, ancestors: ancestors, infos: infos)
258 if export == .all { collect(child, ancestors: ancestors + [headingKey], infos: infos) }
259 case .heading, .footnoteDefinition:
260 continue
261 case .target, .radioTarget:
262 let inner = child.kind == .target ? child.text.dropFirst(2).dropLast(2) : child.text.dropFirst(3).dropLast(3)
263 targets.append((Self.words(inner.uppercased()), key, newReference()))
264 case .table:
265 if captioned { enumerables.append((key, "Table", ancestors)) }
266 collect(child, ancestors: ancestors, infos: infos)
267 case .paragraph:
268 if captioned, soleImage(child) != nil { enumerables.append((key, "Figure", ancestors)) }
269 collect(child, ancestors: ancestors, infos: infos)
270 case .block:
271 let (type, _, _, body) = Self.blockParts(child)
272 if type == "src", captioned { enumerables.append((key, "Listing", ancestors)) }
273 if ["src", "example", "export", "comment", "verse"].contains(type) { continue }
274 within(body.text, base: key + body.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
275 case .drawer, .dynamicBlock:
276 guard let inner = Self.inner(child) else { continue }
277 within(inner.text, base: key + inner.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
278 default:
279 collect(child, ancestors: ancestors, infos: infos)
280 }
281 }
282 }
283
284 /// A drawer's or dynamic block's contents and their offset in it; nil for `LOGBOOK`, which
285 /// isn't exported.
286 static func inner(_ node: SyntaxNode) -> (text: String, offset: Int)? {
287 var lines = node.text.components(separatedBy: "\n")
288 if lines.last == "" { lines.removeLast() }
289 guard let first = lines.first else { return nil }
290 if node.kind == .drawer, first.trimmingCharacters(in: .whitespaces).uppercased() == ":LOGBOOK:" { return nil }
291 return (lines.dropFirst().dropLast().joined(separator: "\n"), first.utf16.count + 1)
292 }
293
294 /// `body` with `text`, which starts at `base` in the document, parsed.
295 private func within<T>(_ text: String, base: Int, _ body: (OrgTree) -> T) -> T {
296 let saved = self.base
297 self.base = base
298 depth += 1
299 defer { self.base = saved; depth -= 1 }
300 return body(OrgParser.parse(text, defaults: settings))
301 }
302
303 // MARK: - Document
304
305 private var source: ExportSource?
306
307 /// `body` with `tree` as the source of `:exports`.
308 private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
309 let saved = source
310 source = ExportSource(tree: tree, text: text)
311 defer { source = saved }
312 return body()
313 }
314
315 func document(_ text: String) -> String {
316 let tree = OrgParser.parse(text, defaults: settings)
317 documentTree = tree
318 let codeBlocks = Coderef.blocks(tree)
319 for (lines, loc) in zip(codeBlocks, Coderef.locs(codeBlocks.compactMap(Coderef.block))) {
320 blockLocs[lines.joined(separator: "\n"), default: []].append(loc)
321 }
322 // A definition runs to the next definition or heading, or two blank lines.
323 let ns = text as NSString
324 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
325 guard let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) else { continue }
326 let start = node.range.lowerBound + node.text.utf16.distance(from: node.text.startIndex, to: m.range.upperBound)
327 var end = node.range.upperBound
328 let siblings = node.parent?.children ?? []
329 if let index = siblings.firstIndex(where: { $0.range == node.range }) {
330 for sibling in siblings[(index + 1)...] {
331 if [.footnoteDefinition, .section, .heading].contains(sibling.kind) { break }
332 let gap = ns.substring(with: NSRange(location: node.range.lowerBound, length: sibling.range.lowerBound - node.range.lowerBound))
333 if gap.range(of: "\n[ \t]*\n[ \t]*\n[ \t]*$", options: .regularExpression) != nil { break }
334 absorbed.insert(sibling.range.lowerBound)
335 end = sibling.range.upperBound
336 }
337 }
338 definitions[String(m.1)] = (ns.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .newlines), start)
339 }
340 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
341 collect(tree)
342 return rendering(tree, text) { tree.root.children.map(element).joined() }
343 }
344
345 /// Org text that starts at `base` in the document, rendered as elements.
346 private func blocks(_ text: String, base: Int) -> String {
347 within(text, base: base) { tree in rendering(tree, text) { tree.root.children.map(element).joined() } }
348 }
349
350 /// One line of org text rendered inline.
351 func inlineString(_ text: String) -> String {
352 let tree = OrgParser.parse(text, defaults: settings)
353 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
354 return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
355 }
356
357 // MARK: - Table of contents
358
359 /// `org-odt-toc` for the whole document: headings to `toc`, or nothing.
360 func tableOfContents() -> String {
361 guard let depth = options.toc else { return "" }
362 return toc(depth: depth, scope: nil)
363 }
364
365 private func toc(depth: Int, scope: Int?) -> String {
366 let keys = headingOrder.filter { key in
367 let heading = headings[key]!
368 let notoc = heading.info?.properties.last { $0.key.uppercased() == "UNNUMBERED" }?.value.trimmingCharacters(in: .whitespaces) == "notoc"
369 return heading.relative <= depth && !notoc && (scope.map { heading.ancestors.contains($0) } ?? true)
370 }
371 guard !keys.isEmpty else { return "" }
372 let title = scope == nil ? ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8) : nil
373 var out = "\n<text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">\n"
374 out += " <text:table-of-content-source text:outline-level=\"\(depth)\">"
375 if let title { out += "\n <text:index-title-template text:style-name=\"Contents_20_Heading\">\(Self.escape(title))</text:index-title-template>\n" }
376 for level in 1...10 {
377 out += """
378
379 <text:table-of-content-entry-template text:outline-level="\(level)" text:style-name="Contents_20_\(level)">
380 <text:index-entry-link-start text:style-name="Internet_20_link"/>
381 <text:index-entry-chapter/>
382 <text:index-entry-text/>
383 <text:index-entry-link-end/>
384 </text:table-of-content-entry-template>
385
386 """
387 }
388 out += "\n </text:table-of-content-source>\n <text:index-body>"
389 if let title {
390 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"
391 }
392 tocEntry = true
393 out += keys.map { key in
394 let heading = headings[key]!
395 var entry = heading.number.map { $0.map(String.init).joined(separator: ".") + ". " } ?? ""
396 let parts = headlineParts(heading.node)
397 if let todo = parts.todo { entry += "<text:span text:style-name=\"\(settings.isDone(todo) ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
398 if let priority = parts.priority { entry += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
399 entry += parts.title
400 if options.tagsInTOC, !parts.tags.isEmpty { entry += " " + tagsSpan(parts.tags) }
401 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>"
402 }.joined(separator: "\n")
403 tocEntry = false
404 return out + "\n </text:index-body>\n</text:table-of-content>"
405 }
406
407 /// Rendering a table of contents entry: footnotes and targets drop out, links become text.
408 private var tocEntry = false
409
410 // MARK: - Elements
411
412 private var affiliated: [String: String] = [:]
413 /// `:exports` of the last src block or call: its results are exported only for `results`
414 /// and `both`; nothing runs.
415 private var lastExports = "code"
416
417 func element(_ node: SyntaxNode) -> String {
418 if depth == 0, absorbed.contains(node.range.lowerBound) { return "" }
419 defer { if node.kind != .affiliatedKeyword { affiliated = [:] } }
420 if node.kind != .affiliatedKeyword, affiliated["RESULTS"] != nil {
421 defer { lastExports = "code" }
422 if lastExports != "results", lastExports != "both" { return "" }
423 }
424 if node.kind == .block || node.kind == .keyword, let exports = source?.exports(at: node.range.lowerBound) {
425 lastExports = exports
426 if exports == "results" || exports == "none" { return "" }
427 }
428 switch node.kind {
429 case .section:
430 guard let heading = node.firstChild(.heading) else { fallthrough }
431 switch HTMLRenderer.sectionExport(heading, options: options, selected: selected) {
432 case .nothing: return ""
433 case .heading: return section(node, heading: heading, contents: false)
434 case .all: return section(node, heading: heading, contents: true)
435 }
436 case .zerothSection, .document:
437 return node.children.map(element).joined()
438 case .affiliatedKeyword:
439 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
440 if let m = line.firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
441 affiliated[m.1.uppercased()] = String(m.2)
442 }
443 return ""
444 case .paragraph:
445 return paragraph(node)
446 case .keyword:
447 return keyword(node)
448 case .plainList:
449 return list(node)
450 case .table:
451 return table(node)
452 case .block:
453 return block(node)
454 case .horizontalRule:
455 return "\n<text:p text:style-name=\"Horizontal_20_Line\"></text:p>"
456 case .drawer, .dynamicBlock:
457 guard let inner = Self.inner(node) else { return "" }
458 return blocks(inner.text, base: base + node.range.lowerBound + inner.offset)
459 case .inlineTask:
460 // `emacs -Q` doesn't load org-inlinetask, so ox-odt reads them as headings.
461 return fail("ODT export doesn't support inline tasks")
462 case .latexEnvironment:
463 guard options.tex else { return "" }
464 // Its value ends with a newline, which ox-odt writes as an empty last line.
465 return code(Self.dedent(node.text.trimmingCharacters(in: .newlines).components(separatedBy: "\n")), emptyLast: node.text.hasSuffix("\n"))
466 case .fixedWidth:
467 let lines = node.text.trimmingCharacters(in: .newlines).split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
468 let trimmed = line.drop { $0 == " " || $0 == "\t" }
469 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
470 }
471 return code(lines)
472 case .tableEl:
473 // ox-odt strips table.el tables, the list around them closed and opened again.
474 return frames.isEmpty ? "" : "\n" + reopening(nil)
475 default:
476 // Comments, property drawers, planning, clocks, footnote definitions, formulas.
477 return ""
478 }
479 }
480
481 // MARK: - Headings
482
483 private func headlineParts(_ node: SyntaxNode) -> (todo: String?, priority: String?, title: String, tags: [String]) {
484 let tokens = node.tokens
485 let todo = options.todo ? tokens.first { $0.kind == .todoKeyword }?.text : nil
486 let priority = options.priority ? tokens.first { $0.kind == .priority }?.text.firstMatch(of: /\[#(.+)\]/).map { String($0.1) } : nil
487 let title = node.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
488 let tags = options.tags ? tokens.first { $0.kind == .tags }?.text.split(separator: ":").map(String.init) ?? [] : []
489 return (todo, priority, title, tags)
490 }
491
492 private func tagsSpan(_ tags: [String]) -> String {
493 "<text:span text:style-name=\"OrgTags\">[" + tags.map { "<text:span text:style-name=\"OrgTag\">\(Self.escape($0))</text:span>" }.joined(separator: " : ") + "]</text:span>"
494 }
495
496 /// `org-odt-format-headline-default-function`.
497 private func headline(_ node: SyntaxNode) -> String {
498 let parts = headlineParts(node)
499 var out = ""
500 if let todo = parts.todo { out += "<text:span text:style-name=\"\(settings.isDone(todo) ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
501 if let priority = parts.priority { out += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
502 out += parts.title
503 if !parts.tags.isEmpty { out += "<text:tab/>" + tagsSpan(parts.tags) }
504 return out
505 }
506
507 private static func target(_ text: String, _ id: String) -> String {
508 "\n<text:bookmark-start text:name=\"OrgXref.\(id)\"/>\n<text:bookmark text:name=\"\(id)\"/>\(text)\n<text:bookmark-end text:name=\"OrgXref.\(id)\"/>"
509 }
510
511 private func section(_ node: SyntaxNode, heading node0: SyntaxNode, contents: Bool) -> String {
512 guard let heading = headings[base + node0.range.lowerBound] else { return "" }
513 let extra = heading.info?.id.map { Self.target("", "ID-" + $0) } ?? ""
514 let anchored = Self.target(headline(node0), heading.reference)
515 let numbered = heading.number != nil
516 headingStack.append(heading.key)
517 defer { headingStack.removeLast() }
518 guard heading.lowLevel else {
519 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>"
520 return open + (contents ? node.children.filter { $0.kind != .heading }.map(element).joined() : "")
521 }
522 // A heading deeper than `H` is a list item, its siblings in one list.
523 let siblings = (node.parent?.children ?? []).filter { section in
524 section.kind == .section && section.firstChild(.heading).map { headings[base + $0.range.lowerBound] != nil } ?? false
525 }
526 let style = numbered ? "OrgNumberedList" : "OrgBulletedList"
527 var out = ""
528 if siblings.first?.range == node.range {
529 let parentLow = heading.ancestors.last.flatMap { headings[$0]?.lowLevel } ?? false
530 out += "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"\(parentLow)\">"
531 }
532 frames.append(Frame(style: style))
533 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() : "")
534 let frame = frames.removeLast()
535 out += "\n<text:list-item>\n\(body)\n\(frame.header ? "</text:list-header>" : "</text:list-item>")"
536 if siblings.last?.range == node.range { out += "</text:list>" }
537 return out
538 }
539
540 // MARK: - Paragraphs
541
542 private enum Container { case quote, center }
543 /// The quote or center block paragraphs are in.
544 private var container: Container?
545 /// Paragraph styles outside, in a center block and in a quote block.
546 private var paragraphStyles = ("Text_20_body", "OrgCenter", "Quotations")
547 /// Rendering a paragraph that is only an image link.
548 private var standalone = false
549
550 private func paragraph(_ node: SyntaxNode, prefix: String = "", style: String? = nil) -> String {
551 let named = style ?? paragraphStyles.0
552 let chosen = container == .quote ? paragraphStyles.2 : container == .center ? paragraphStyles.1 : named
553 standalone = soleImage(node) != nil
554 defer { standalone = false }
555 imageKey = base + node.range.lowerBound
556 imageCaptioned = affiliated["CAPTION"] != nil || affiliated["NAME"] != nil
557 imageCaption = affiliated["CAPTION"]
558 imageAttributes = affiliated["ATTR_ODT"]
559 defer { imageKey = nil; imageCaptioned = false; imageCaption = nil; imageAttributes = nil }
560 return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(inline(node).trimmingCharacters(in: .whitespacesAndNewlines))</text:p>"
561 }
562
563 /// The link of a paragraph that is only an image link.
564 private func soleImage(_ node: SyntaxNode) -> SyntaxNode? {
565 let links = node.children.filter { $0.kind == .link }
566 guard links.count == 1, node.children.count == 1,
567 node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }),
568 links[0].firstChild(.linkDescription) == nil,
569 let file = Self.filePath(links[0].tokens.first { $0.kind == .linkPath }?.text ?? ""), Self.isImage(file) else { return nil }
570 return links[0]
571 }
572
573 private func keyword(_ node: SyntaxNode) -> String {
574 guard let m = node.text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) else { return "" }
575 let value = String(m.2)
576 switch m.1.uppercased() {
577 case "ODT":
578 return value
579 case "TOC":
580 guard value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil else { return "" }
581 let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) } ?? options.headlineLevels
582 if value.range(of: ":target", options: .caseInsensitive) != nil { return fail("ODT export doesn't support #+TOC with :target") }
583 let local = value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil
584 return toc(depth: depth, scope: local ? currentHeading() : nil)
585 case "PRINT_BIBLIOGRAPHY":
586 guard let citations else { return "" }
587 return citations.bibliography.map { "\n<text:p text:style-name=\"Text_20_body\">" + render($0) + "</text:p>" }.joined()
588 default:
589 return ""
590 }
591 }
592
593 /// The heading whose section is being rendered.
594 private var headingStack: [Int] = []
595 private func currentHeading() -> Int? { headingStack.last }
596
597 // MARK: - Lists
598
599 /// An open list item, closed and opened again around a table.
600 private struct Frame {
601 var style: String
602 var header = false
603 }
604
605 private var frames: [Frame] = []
606
607 private func list(_ node: SyntaxNode) -> String {
608 let items = node.children.filter { $0.kind == .item }
609 guard let first = items.first else { return "" }
610 let bullet = first.tokens.first { $0.kind == .bullet }?.text ?? "-"
611 let ordered = bullet.first.map { $0.isNumber || $0.isLetter } ?? false
612 let descriptive = !ordered && first.firstChild(.itemTag) != nil
613 let style = ordered ? "OrgNumberedList" : descriptive ? "OrgDescriptionList" : "OrgBulletedList"
614 let nested = node.parent?.kind == .item
615 var out = "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"\(nested)\">\n"
616 for item in items {
617 let box = checkbox(item)
618 if descriptive {
619 // As `org-odt--translate-description-lists`: the term in bold, the definition
620 // an item of a list inside.
621 frames.append(Frame(style: style))
622 let term = item.firstChild(.itemTag).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "(no term)"
623 var body = paragraphText(term, prefix: box, style: "Text_20_body_20_bold")
624 body += "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"true\">\n"
625 body += itemBody(item, prefix: "")
626 body += "</text:list>"
627 out += close(body, start: nil)
628 } else {
629 frames.append(Frame(style: style))
630 let counter = item.tokens.first { $0.kind == .counter }?.text.firstMatch(of: /\[@([0-9A-Za-z]+)\]/).map { String($0.1) }
631 out += closeItem(item, prefix: box, start: counter)
632 }
633 }
634 return out + "</text:list>"
635 }
636
637 private func itemBody(_ item: SyntaxNode, prefix: String) -> String {
638 frames.append(Frame(style: "OrgDescriptionList"))
639 return closeItem(item, prefix: prefix, start: nil)
640 }
641
642 /// The item's contents, the first paragraph after `prefix`, in the open frame.
643 private func closeItem(_ item: SyntaxNode, prefix: String, start: String?) -> String {
644 var body = ""
645 for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
646 body += index == 0 && child.kind == .paragraph ? paragraph(child, prefix: prefix) : element(child)
647 }
648 return close(body, start: start)
649 }
650
651 private func close(_ body: String, start: String?) -> String {
652 let frame = frames.removeLast()
653 return "\n<text:list-item\(start.map { " text:start-value=\"\($0)\"" } ?? "")>\n\(body)\n\(frame.header ? "</text:list-header>" : "</text:list-item>")"
654 }
655
656 private func paragraphText(_ content: String, prefix: String, style: String) -> String {
657 let chosen = container == .quote ? paragraphStyles.2 : container == .center ? paragraphStyles.1 : style
658 return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(content)</text:p>"
659 }
660
661 private func checkbox(_ item: SyntaxNode) -> String {
662 guard let box = item.tokens.first(where: { $0.kind == .checkbox })?.text else { return "" }
663 let mark = ["[X]": "[&#x2713;] ", "[x]": "[&#x2713;] ", "[-]": "[-] "][box] ?? "[ ] "
664 return "<text:span text:style-name=\"OrgCode\">\(mark)</text:span>"
665 }
666
667 /// `org-odt-table`'s list handling: the open lists closed, `inner` in an indented section,
668 /// the lists opened again, the innermost item as a header.
669 private func reopening(_ inner: String?) -> String {
670 var closing: [String] = []
671 for frame in frames.reversed() {
672 closing.append(frame.header ? "</text:list-header>" : "</text:list-item>")
673 closing.append("</text:list>")
674 }
675 var opening: [String] = []
676 for (index, frame) in frames.enumerated() {
677 opening.append("\n<text:list text:style-name=\"\(frame.style)\" text:continue-numbering=\"true\">")
678 opening.append(index == frames.count - 1 || frame.header ? "<text:list-header>" : "<text:list-item>")
679 }
680 if !frames.isEmpty { frames[frames.count - 1].header = true }
681 let section = inner.map { inner -> String in
682 sections += 1
683 return "\n<text:section text:style-name=\"OrgIndentedSection-Level-\(closing.count / 2)\" text:name=\"Section\(sections)\">\n\(inner)\n</text:section>"
684 } ?? ""
685 return closing.joined(separator: "\n") + section + opening.joined(separator: "\n")
686 }
687
688 private var sections = 0
689
690 // MARK: - Tables
691
692 private var tableStyles: [(name: String, width: String)] = []
693
694 private func table(_ node: SyntaxNode) -> String {
695 let attributeLine = affiliated["ATTR_ODT"]
696 let attributes = attributeLine.map(Self.attributes) ?? [:]
697 if attributes["style"] != nil { return fail("ODT export doesn't support table templates (#+ATTR_ODT: :style)") }
698 let caption = label(base + node.range.lowerBound, caption: affiliated["CAPTION"])
699 let rows = node.children.filter { $0.kind == .tableRow }
700 enum Kind { case rule, special, data }
701 var cells: [[SyntaxNode]] = rows.map { $0.children.filter { $0.kind == .tableCell } }
702 var kinds: [Kind] = rows.indices.map { cells[$0].isEmpty && rows[$0].text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") ? .rule : .data }
703 func value(_ cell: SyntaxNode) -> String { cell.text.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "|")).trimmingCharacters(in: .whitespaces) }
704 // `org-export-table-has-special-column-p`.
705 let firsts = rows.indices.filter { kinds[$0] == .data }.map { cells[$0].first.map(value) ?? "" }
706 let specialColumn = firsts.contains { !$0.isEmpty } && firsts.allSatisfy { ["", "/", "#", "!", "$", "*", "_", "^"].contains($0) }
707 for r in rows.indices where kinds[r] == .data {
708 let values = cells[r].map(value)
709 let cookies = values.allSatisfy { $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil } && values.contains { !$0.isEmpty }
710 if values.first == "/" || (specialColumn && ["^", "_", "$", "!"].contains(values.first ?? "")) || cookies { kinds[r] = .special }
711 }
712 let firstValues = rows.indices.map { cells[$0].first.map(value) ?? "" }
713 if specialColumn { cells = cells.map { Array($0.dropFirst()) } }
714 let columns = rows.indices.filter { kinds[$0] != .rule }.map { cells[$0].count }.max() ?? 0
715 // Alignment and width cookies, and column groups.
716 var align = Array(repeating: "", count: columns)
717 var width = Array(repeating: 0, count: columns)
718 var groups = Array(repeating: "", count: columns)
719 for r in rows.indices where kinds[r] == .special {
720 let values = cells[r].map(value)
721 for (c, v) in values.enumerated() {
722 if let m = v.firstMatch(of: /^<([lrc])?([0-9]+)?>$/) {
723 if let a = m.1 { align[c] = String(a) }
724 if let w = m.2 { width[c] = Int(w) ?? 0 }
725 }
726 if firstValues[r] == "/" { groups[c] = v }
727 }
728 }
729 let data = rows.indices.filter { kinds[$0] == .data }
730 for c in 0..<columns where align[c].isEmpty {
731 var numbers = 0
732 var total = 0
733 var previousNumber = false
734 for r in data {
735 let v = c < cells[r].count ? value(cells[r][c]) : ""
736 total += 1
737 if TablePlot.isNumber(v) || (v.isEmpty && previousNumber) {
738 previousNumber = true
739 numbers += 1
740 } else {
741 previousNumber = false
742 }
743 }
744 align[c] = total > 0 && Double(numbers) / Double(total) >= 0.5 ? "r" : "l"
745 }
746 // Row groups: data rows between rules.
747 var group: [Int: Int] = [:]
748 var current = 1
749 var seen = false
750 for r in rows.indices {
751 if kinds[r] == .rule, seen { current += 1; seen = false }
752 if kinds[r] == .data { group[r] = current; seen = true }
753 }
754 let firstData = rows.indices.first { kinds[$0] == .data || kinds[$0] == .special }
755 let hasHeader = firstData.map { start in
756 guard let rule = rows.indices.first(where: { $0 > start && kinds[$0] == .rule }) else { return false }
757 return rule + 1 < rows.count
758 } ?? false
759 let headerColumns = attributes["header-columns"].map { Int($0) ?? 1 } ?? 0
760 var body = ""
761 for (index, r) in data.enumerated() {
762 let previous = rows.indices.reversed().first { $0 < r && kinds[$0] != .special }
763 let next = rows.indices.first { $0 > r && kinds[$0] != .special }
764 let starts = previous.map { kinds[$0] == .rule } ?? true
765 let ends = next.map { kinds[$0] == .rule } ?? true
766 let header = group[r] == 1 && hasHeader
767 if starts { body += header ? "\n<table:table-header-rows>" : "\n<table:table-rows>" }
768 var row = ""
769 for c in 0..<columns {
770 let cell = c < cells[r].count ? cells[r][c] : nil
771 let startsGroup = c == 0 || ["<", "<>"].contains(groups[c]) || [">", "<>"].contains(groups[c - 1])
772 let style = "OrgTblCell" + (starts || index == 0 ? "T" : "") + (ends ? "B" : "") + (startsGroup && c != 0 ? "L" : "")
773 let paragraph = (header || c < headerColumns ? "OrgTableHeading" : "OrgTableContents") + ["l": "Left", "r": "Right", "c": "Center"][align[c]]!
774 let span = width[c]
775 row += "\n<table:table-cell table:style-name=\"\(style)\"\(span > 0 ? " table:number-columns-spanned=\"\(span + 1)\"" : "")>\n"
776 row += "\n<text:p text:style-name=\"\(paragraph)\">\(cell.map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "")</text:p>"
777 row += "\n</table:table-cell>" + String(repeating: "\n<table:covered-table-cell/>", count: span) + "\n"
778 }
779 body += "\n<table:table-row>\n\(row)\n</table:table-row>"
780 if ends { body += header ? "\n</table:table-header-rows>" : "\n</table:table-rows>" }
781 }
782 var style = "OrgTable"
783 if attributeLine != nil {
784 style = "OrgTable\(tableStyles.count + 1)"
785 tableStyles.append((style, attributes["rel-width"] ?? "96"))
786 }
787 let firstRow = data.first.map { cells[$0] } ?? []
788 let columnSpecs = firstRow.indices.map { c in
789 String(repeating: "\n<table:table-column table:style-name=\"OrgTableColumn\"/>", count: (c < width.count ? width[c] : 0) + 1)
790 }.joined(separator: "\n")
791 var out = caption.map { "\n<text:p text:style-name=\"Table\">\($0)</text:p>" } ?? ""
792 out += "\n<table:table table:style-name=\"\(style)\">" + columnSpecs + "\n" + body + "</table:table>"
793 return "\n" + reopening(out)
794 }
795
796 /// `org-odt-format-label` as a definition: a bookmark, then the category, sequence number
797 /// and caption; nil without a caption or name.
798 private func label(_ key: Int, caption: String?) -> String? {
799 guard let label = labels[key] else { return nil }
800 let reference = label.reference ?? "nil"
801 let category = ExportDictionary.translate(label.category, language: language, encoding: .utf8)
802 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>"
803 let format = ExportDictionary.translate("%e %n: %c", language: language, encoding: .utf8)
804 let text = format.replacingOccurrences(of: "%e", with: category).replacingOccurrences(of: "%n", with: number)
805 .replacingOccurrences(of: "%c", with: caption.map(inlineString) ?? "")
806 return "\n<text:bookmark text:name=\"\(reference)\"/>" + text
807 }
808
809 // MARK: - Blocks
810
811 /// A block's type, parameters, its first line and its contents with their offset in the block.
812 static func blockParts(_ node: SyntaxNode) -> (type: String, parameters: String, lines: [String], body: (text: String, offset: Int)) {
813 var lines = node.text.components(separatedBy: "\n")
814 if lines.last == "" { lines.removeLast() }
815 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return ("", "", lines, ("", 0)) }
816 let body = lines.dropFirst().dropLast().map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
817 return (m.1.lowercased(), String(m.2), lines, (body.joined(separator: "\n"), first.utf16.count + 1))
818 }
819
820 private func block(_ node: SyntaxNode) -> String {
821 let (type, parameters, lines, body) = Self.blockParts(node)
822 guard !lines.isEmpty, !type.isEmpty else { return "" }
823 let key = base + node.range.lowerBound
824 let unescaped = body.text.isEmpty && lines.count <= 2 ? [] : body.text.components(separatedBy: "\n")
825 switch type {
826 case "src":
827 let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? ""
828 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
829 let formatted = numbered(lines, Self.dedent(unescaped))
830 if let textbox = attributes["textbox"], textbox != "nil" {
831 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>"
832 }
833 return caption + formatted
834 case "example":
835 return numbered(lines, Self.dedent(unescaped))
836 case "quote", "center":
837 let saved = container
838 container = type == "quote" ? .quote : .center
839 defer { container = saved }
840 return blocks(body.text, base: key + body.offset)
841 case "verse":
842 let rendered = unescaped.map { line -> String in
843 inlineString(line, verse: true).replacingOccurrences(of: "[ \\t]+$", with: "", options: .regularExpression)
844 }
845 var out = rendered.map { $0 + "<text:line-break/>" }.joined()
846 if let indent = out.firstMatch(of: /^[ \t]+/) {
847 out = Self.encodeSpaces(String(indent.output)) + out[indent.range.upperBound...]
848 }
849 return "\n<text:p text:style-name=\"OrgVerse\">\(out)</text:p>"
850 case "export":
851 return parameters.split(separator: " ").first?.lowercased() == "odt" ? Self.dedent(unescaped).joined(separator: "\n") : ""
852 case "comment":
853 return ""
854 default:
855 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
856 let contents = blocks(body.text, base: key + body.offset)
857 switch type {
858 case "textbox":
859 let size = { (key: String) in attributes[key].flatMap(Double.init) }
860 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>"
861 case "annotation":
862 if attributes["date"] != nil || dated { return fail("ODT export doesn't support dated annotations") }
863 let author = attributes["author"].map { Self.escape($0) } ?? author
864 return "\n<text:p><office:annotation>\n\(author.map { "<dc:creator>\($0)</dc:creator>" } ?? "")\(contents)\n</office:annotation></text:p>"
865 default:
866 return contents
867 }
868 }
869 }
870
871 /// The code of a src or example block, labels and numbers as its switches ask.
872 private func numbered(_ block: [String], _ body: [String]) -> String {
873 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
874 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
875 let key = block.joined(separator: "\n")
876 let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
877 return code(lines, refs: refs, retain: switches.retainLabels, loc: switches.numberLines == nil ? nil : loc)
878 }
879
880 /// `org-odt-do-format-code`: one paragraph per line, the last one styled apart.
881 private func code(_ lines: [String], refs: [Int: String] = [:], retain: Bool = false, loc: Int? = nil, emptyLast: Bool = false) -> String {
882 var lines = lines
883 if emptyLast { lines.append("") }
884 let out = lines.enumerated().map { index, line -> String in
885 var text = line
886 if let ref = refs[index + 1], retain { text += " (\(ref))" }
887 var encoded = Self.escape(text, quotes: true).replacingOccurrences(of: " ", with: "<text:s/>").replacingOccurrences(of: "\t", with: "<text:tab/>")
888 if let ref = refs[index + 1] { encoded = Self.target(encoded, "coderef-" + ref) }
889 let paragraph = "\n<text:p text:style-name=\"OrgSrcBlock\(index == lines.count - 1 ? "LastLine" : "")\">\(encoded)</text:p>"
890 return loc == nil ? paragraph : "\n<text:list-item>\(paragraph)\n</text:list-item>"
891 }.joined()
892 guard let loc else { return out }
893 return "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\" text:continue-numbering=\"\(loc != 0)\">\(out)</text:list>"
894 }
895
896 static func dedent(_ lines: [String]) -> [String] {
897 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
898 let common = indents.min() ?? 0
899 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
900 }
901
902 // MARK: - Frames
903
904 private var frameCount = 0
905
906 /// `org-odt--frame`.
907 private func frame(_ text: String, width: Double?, height: Double?, style: String?, extra: String?, anchor: String?) -> String {
908 frameCount += 1
909 var attributes = width.map { String(format: " svg:width=\"%0.2fcm\"", $0) } ?? ""
910 attributes += height.map { String(format: " svg:height=\"%0.2fcm\"", $0) } ?? ""
911 attributes += (extra ?? "") + " text:anchor-type=\"\(anchor ?? "paragraph")\" draw:name=\"Frame\(frameCount)\""
912 return "\n<draw:frame draw:style-name=\"\(style ?? "nil")\"\(attributes)>\n\(text)\n</draw:frame>"
913 }
914
915 /// `org-odt--textbox`.
916 private func textbox(_ text: String, width: Double?, height: Double?, style: String?, extra: String?, anchor: String?) -> String {
917 let box = String(format: " fo:min-height=\"%0.2fcm\"", height ?? 0.2) + (width == nil ? String(format: " fo:min-width=\"%0.2fcm\"", 0.2) : "")
918 return frame("\n<draw:text-box \(box)>\(text)\n</draw:text-box>", width: width, height: nil, style: style, extra: extra, anchor: anchor)
919 }
920
921 // MARK: - Images
922
923 /// The paragraph holding the image being rendered, and its caption and attributes.
924 private var imageKey: Int?
925 private var imageCaptioned = false
926 private var imageCaption: String?
927 private var imageAttributes: String?
928
929 /// A link's file, for `file:` links and paths Org reads as files.
930 static func filePath(_ path: String) -> String? {
931 var file: String
932 if path.hasPrefix("file:") {
933 file = String(path.dropFirst(5))
934 } else if ["/", "./", "../", "~/"].contains(where: path.hasPrefix) {
935 file = path
936 } else {
937 return nil
938 }
939 if let range = file.range(of: "::") { file = String(file[..<range.lowerBound]) }
940 return file
941 }
942
943 static func isImage(_ file: String) -> Bool {
944 file.range(of: "\\.(jpeg|jpg|png|gif|svg)", options: [.regularExpression, .caseInsensitive]) != nil
945 }
946
947 static func expand(_ file: String, directory: URL) -> URL {
948 let path = OrgPaths.expandingTilde(file)
949 return path.hasPrefix("/") ? URL(fileURLWithPath: path) : directory.appendingPathComponent(path).standardizedFileURL
950 }
951
952 /// `org-odt-link--inline-image`: the file embedded under `Images/`, sized from its pixels
953 /// at 96 dpi or `#+ATTR_ODT`, within 17 by 20 cm.
954 private func image(_ file: String) -> String {
955 let url = Self.expand(file, directory: directory)
956 guard let data = try? Data(contentsOf: url) else { return fail("Opening input file: No such file or directory, \(url.path)") }
957 let ext = (file as NSString).pathExtension
958 let name = String(format: "Images/%04d.%@", images.count + 1, ext)
959 images.append((name, data))
960 let attributes = imageAttributes.map(Self.attributes) ?? [:]
961 let user = { (key: String) in attributes[key].flatMap(Double.init) }
962 let scale = user("scale")
963 let userWidth = scale == nil ? user("width") : nil
964 let userHeight = scale == nil ? user("length") : nil
965 var size = (width: 5.0, height: 5.0)
966 if userWidth == nil || userHeight == nil {
967 if let source = CGImageSourceCreateWithData(data as CFData, nil),
968 let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
969 let w = properties[kCGImagePropertyPixelWidth] as? Double, let h = properties[kCGImagePropertyPixelHeight] as? Double {
970 size = (w / 96 * 2.54, h / 96 * 2.54)
971 }
972 }
973 if let scale {
974 size = (size.width * scale, size.height * scale)
975 } else if let userWidth, let userHeight {
976 size = (userWidth, userHeight)
977 } else if let userHeight {
978 size = (userHeight * size.width / size.height, userHeight)
979 } else if let userWidth {
980 size = (userWidth, userWidth * size.height / size.width)
981 }
982 if size.width > 17 || size.height > 20 {
983 let factor = min(17 / size.width, 20 / size.height)
984 size = (size.width * factor, size.height * factor)
985 }
986 let href = "\n<draw:image xlink:href=\"\(name)\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
987 if !standalone, imageCaptioned { return fail("Don't know how to format label for an image inside text") }
988 let caption = standalone ? imageKey.flatMap { label($0, caption: imageCaption) } : nil
989 guard let caption else {
990 return frame(href, width: size.width, height: size.height, style: standalone ? "OrgDisplayImage" : "OrgInlineImage", extra: nil, anchor: standalone ? "paragraph" : "as-char")
991 }
992 let inner = frame(href, width: size.width, height: size.height, style: "OrgCaptionedImage", extra: " style:rel-width=\"100%\" style:rel-height=\"scale\"", anchor: "paragraph")
993 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")
994 }
995
996 // MARK: - Inline
997
998 func inline(_ node: SyntaxNode) -> String {
999 afterFootnote = false
1000 var out = ""
1001 var text = ""
1002 for element in node.elements {
1003 switch element {
1004 case .token(let token):
1005 switch token.kind {
1006 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1007 continue
1008 default:
1009 text += token.text
1010 }
1011 case .node(let child):
1012 if !text.isEmpty { afterFootnote = false }
1013 out += plainText(text)
1014 text = ""
1015 out += object(child)
1016 }
1017 }
1018 if !text.isEmpty { afterFootnote = false }
1019 return out + plainText(text)
1020 }
1021
1022 private var verse = false
1023
1024 private func inlineString(_ text: String, verse: Bool) -> String {
1025 let saved = self.verse
1026 self.verse = verse
1027 defer { self.verse = saved }
1028 let tree = OrgParser.parse(text, defaults: settings)
1029 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
1030 return rendering(tree, text) { inline(paragraph) }
1031 }
1032
1033 static let textObjects = HTMLRenderer.textObjects
1034
1035 /// `org-odt-plain-text`, with the LaTeX fragments, entities and scripts the parser leaves in
1036 /// text.
1037 private func plainText(_ text: String) -> String {
1038 guard !text.isEmpty else { return "" }
1039 let ns = text as NSString
1040 var out = ""
1041 var at = 0
1042 for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
1043 out += plain(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
1044 at = NSMaxRange(m.range)
1045 let whole = ns.substring(with: m.range)
1046 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
1047 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
1048 if options.tex { out += "<text:span text:style-name=\"OrgCode\">\(Self.escape(whole))</text:span>" }
1049 } else if let name = group(5) {
1050 out += OrgEntities.display[name].map { Self.escape($0) } ?? plain(whole)
1051 } else if let marker = group(7), let body = group(8) {
1052 let braced = body.hasPrefix("{")
1053 if options.scripts == .off || (options.scripts == .braces && !braced) {
1054 out += plain(whole)
1055 continue
1056 }
1057 let inner = braced ? String(body.dropFirst().dropLast()) : body
1058 out += "<text:span text:style-name=\"\(marker == "_" ? "OrgSubscript" : "OrgSuperscript")\">\(plain(inner))</text:span>"
1059 } else {
1060 out += plain(whole)
1061 }
1062 }
1063 return out + plain(ns.substring(from: at))
1064 }
1065
1066 /// Escaped text with special strings, its line breaks as spaces outside verse.
1067 private func plain(_ text: String) -> String {
1068 var out = Self.escape(text)
1069 if options.specialStrings {
1070 out = out.replacingOccurrences(of: "\\\\-", with: "&#x00ad;", options: .regularExpression)
1071 .replacingOccurrences(of: "---([^-])", with: "&#x2014;$1", options: .regularExpression)
1072 .replacingOccurrences(of: "--([^-])", with: "&#x2013;$1", options: .regularExpression)
1073 .replacingOccurrences(of: "...", with: "&#x2026;")
1074 }
1075 return verse ? out : out.replacingOccurrences(of: "\n", with: " ")
1076 }
1077
1078 private func span(_ style: String, _ content: String) -> String {
1079 "<text:span text:style-name=\"\(style)\">\(content)</text:span>"
1080 }
1081
1082 /// The previous object was a footnote reference, for the comma between two.
1083 private var afterFootnote = false
1084
1085 private func object(_ node: SyntaxNode) -> String {
1086 defer { afterFootnote = node.kind == .footnoteReference && !tocEntry }
1087 switch node.kind {
1088 case .bold: return span("Bold", inline(node))
1089 case .italic: return span("Emphasis", inline(node))
1090 case .underline: return span("Underline", inline(node))
1091 case .strikeThrough: return span("Strikethrough", inline(node))
1092 case .verbatim, .code:
1093 let value = node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1094 return span("OrgCode", Self.encodeSpaces(Self.escape(value)))
1095 case .link: return link(node)
1096 case .linkDescription: return inline(node)
1097 case .timestamp:
1098 let text = node.text.trimmingCharacters(in: .whitespaces)
1099 if text.hasPrefix("<%%") { return plain(text) }
1100 return span(text.hasPrefix("<") ? "OrgActiveTimestamp" : "OrgInactiveTimestamp", plain(text))
1101 case .footnoteReference:
1102 if tocEntry { return "" }
1103 let comma = afterFootnote ? span("OrgSuperscript", ",") : ""
1104 return comma + footnote(node.text)
1105 case .entity:
1106 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
1107 return OrgEntities.display[name].map { Self.escape($0) } ?? plain(node.text)
1108 case .radioTarget:
1109 let inner = plain(String(node.text.dropFirst(3).dropLast(3)))
1110 if tocEntry { return inner }
1111 return Self.target(inner, targets.first { $0.key == base + node.range.lowerBound }?.reference ?? "nil")
1112 case .target:
1113 if tocEntry { return "" }
1114 return Self.target("", targets.first { $0.key == base + node.range.lowerBound }?.reference ?? "nil")
1115 case .superscript, .subscript:
1116 let text = node.text
1117 let body = text.dropFirst()
1118 let braced = body.hasPrefix("{") && body.hasSuffix("}")
1119 if options.scripts == .off || (options.scripts == .braces && !braced) { return plain(text) }
1120 let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
1121 return span(text.hasPrefix("_") ? "OrgSubscript" : "OrgSuperscript", plain(inner))
1122 case .lineBreak: return "<text:line-break/>"
1123 case .macro:
1124 guard case .some(let value) = source?.resultsMacro(node) else { return "" }
1125 return value.map(inlineString) ?? ""
1126 case .inlineSourceBlock:
1127 let exports = source?.exports(at: node.range.lowerBound) ?? "results"
1128 source?.inlineResults = exports == "results" || exports == "both"
1129 guard exports == "code" || exports == "both" else { return "" }
1130 // ox-odt has no transcoder for them.
1131 return fail("ODT export doesn't support inline source blocks")
1132 case .latexFragment:
1133 guard options.tex else { return "" }
1134 return span("OrgCode", Self.escape(node.text))
1135 case .statisticsCookie: return span("OrgCode", Self.escape(node.text))
1136 case .exportSnippet:
1137 guard node.tokens.first?.text.lowercased() == "@@odt:" else { return "" }
1138 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1139 case .citation:
1140 if inTitle { return "" }
1141 guard let pieces = citations?.next(node.text) else { return plain(node.text) }
1142 return render(pieces)
1143 case .inlineBabelCall:
1144 source?.inlineResults = (source?.exports(at: node.range.lowerBound) ?? "results") == "results"
1145 return ""
1146 default: return inline(node)
1147 }
1148 }
1149
1150 /// A citation's or a bibliography entry's pieces.
1151 private func render(_ pieces: [CiteProcessor.Piece]) -> String {
1152 pieces.map { piece in
1153 switch piece {
1154 case .text(let s): plain(s)
1155 case .italic(let s): span("Emphasis", plain(s))
1156 case .org(let s) where s.allSatisfy(\.isWhitespace): s
1157 case .org(let s):
1158 String(s.prefix { $0.isWhitespace }) + inlineString(s) + String(s.reversed().prefix { $0.isWhitespace })
1159 }
1160 }.joined()
1161 }
1162
1163 // MARK: - Footnotes
1164
1165 private var footnoteNumbers: [String: Int] = [:]
1166 private var anonymous = 0
1167
1168 private func footnote(_ text: String) -> String {
1169 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return plain(text) }
1170 var label = String(m.1)
1171 let inlineText = m.2.map(String.init)
1172 if label.isEmpty {
1173 anonymous += 1
1174 label = "anonymous-\(anonymous)"
1175 }
1176 if let n = footnoteNumbers[label] {
1177 return span("OrgSuperscript", "<text:note-ref text:note-class=\"footnote\" text:reference-format=\"text\" text:ref-name=\"fn\(n)\">\(n)</text:note-ref>")
1178 }
1179 let n = footnoteNumbers.count + 1
1180 footnoteNumbers[label] = n
1181 let saved = (paragraphStyles, container, frames, afterFootnote)
1182 paragraphStyles = ("Footnote", "OrgFootnoteCenter", "OrgFootnoteQuotations")
1183 container = nil
1184 frames = []
1185 defer { (paragraphStyles, container, frames, afterFootnote) = saved }
1186 let definition: String
1187 if let inlineText {
1188 definition = "\n<text:p text:style-name=\"Footnote\">\(inlineString(inlineText))</text:p>"
1189 } else if let found = definitions[label] {
1190 definition = blocks(found.text, base: found.base).trimmingCharacters(in: .whitespacesAndNewlines)
1191 } else {
1192 return fail("Definition not found for footnote \(m.1)")
1193 }
1194 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>"
1195 }
1196
1197 // MARK: - Links
1198
1199 private enum Destination {
1200 case heading(Heading)
1201 case target(String)
1202 case element(Int)
1203 }
1204
1205 private func titleWords(_ heading: Heading) -> [String] {
1206 let title = heading.info?.title ?? heading.node.firstChild(.title)?.text ?? ""
1207 return Self.words(title.replacingOccurrences(of: "\\[[0-9]*(%|/[0-9]*)\\]", with: " ", options: .regularExpression).uppercased())
1208 }
1209
1210 /// `org-export-resolve-fuzzy-link`: a target or name first, else the last heading with the
1211 /// title.
1212 private func resolve(_ path: String) -> Destination? {
1213 let all = headingOrder.compactMap { headings[$0] }
1214 if path.hasPrefix("*") {
1215 let words = Self.words(String(path.dropFirst()).uppercased())
1216 return all.last { titleWords($0) == words }.map(Destination.heading)
1217 }
1218 if path.hasPrefix("#") {
1219 let id = String(path.dropFirst())
1220 return all.last { $0.info?.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value == id }.map(Destination.heading)
1221 }
1222 let words = Self.words(path)
1223 let upper = words.map { $0.uppercased() }
1224 if let name = names.last(where: { $0.words == words }) { return .element(name.key) }
1225 if let target = targets.last(where: { $0.words == upper }) { return .target(target.reference) }
1226 if let name = names.last(where: { $0.words == upper }) { return .element(name.key) }
1227 return all.last { titleWords($0) == upper }.map(Destination.heading)
1228 }
1229
1230 private func link(_ node: SyntaxNode) -> String {
1231 let path = node.tokens.first { $0.kind == .linkPath }?.text
1232 let descriptionNode = node.firstChild(.linkDescription)
1233 var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 }
1234 // `org-export-insert-image-links`: a description that is an image's path shows it.
1235 let describedImage = descriptionNode.flatMap { Self.filePath($0.text.trimmingCharacters(in: .whitespaces).replacing(/^\[\[(.*)\]\]$/) { String($0.1) }) }.flatMap { Self.isImage($0) ? $0 : nil }
1236 if let describedImage, !tocEntry { description = image(describedImage) }
1237 guard let path else {
1238 // A radio link refers to its target.
1239 if !node.text.hasPrefix("<"), !node.text.contains(":") {
1240 let words = Self.words(node.text.uppercased())
1241 let text = plain(node.text)
1242 if tocEntry { return text }
1243 guard let target = targets.first(where: { $0.words == words }) else { return text }
1244 return "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.\(target.reference)\">\(text)</text:bookmark-ref>"
1245 }
1246 var target = node.text
1247 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
1248 if tocEntry { return plain(target) }
1249 return external(target, description: nil)
1250 }
1251 if tocEntry { return description ?? plain(path) }
1252 if let file = Self.filePath(path) {
1253 if description == nil, Self.isImage(file) { return image(file) }
1254 let uri = file.hasPrefix("/") || file.hasPrefix("~") ? "file://" + OrgPaths.expandingTilde(file) : "../" + file
1255 return external(uri, description: description, image: describedImage != nil)
1256 }
1257 // A code reference: its line's number.
1258 if path.hasPrefix("("), path.hasSuffix(")"), path.count >= 2 {
1259 let name = String(path.dropFirst().dropLast())
1260 guard let resolved = documentTree.flatMap({ Coderef.resolve(name, in: $0) }) else { return fail("Unable to resolve code reference: \(name)") }
1261 guard Int(resolved) != nil else { return fail("ODT export only resolves code references to numbered lines: \(name)") }
1262 let reference = "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.coderef-\(Self.escape(name, quotes: true))\">\(resolved)</text:bookmark-ref>"
1263 return Coderef.linkText(reference, description: description)
1264 }
1265 if let colon = path.firstIndex(of: ":"), Links.types.contains(String(path[..<colon])) {
1266 if path.hasPrefix("id:") {
1267 let id = String(path.dropFirst(3))
1268 guard let heading = headingOrder.compactMap({ headings[$0] }).first(where: { $0.info?.id == id }) else { return fail("Unable to resolve link: \"\(id)\"") }
1269 return toHeading(heading, description: description, customID: nil)
1270 }
1271 return external(path, description: description, image: describedImage != nil)
1272 }
1273 let search = path
1274 guard let destination = resolve(search) else { return fail("Unable to resolve link: \"\(search)\"") }
1275 switch destination {
1276 case .heading(let heading):
1277 return toHeading(heading, description: description, customID: search.hasPrefix("#") ? String(search.dropFirst()) : nil)
1278 case .target(let reference):
1279 guard let description else { return fail("ODT export doesn't number links to targets without a description: \(search)") }
1280 return "<text:a xlink:type=\"simple\" xlink:href=\"#\(reference)\">\(description)</text:a>"
1281 case .element(let key):
1282 guard let label = labels[key], let reference = label.reference else { return fail("FIXME: Unable to resolve \(search)") }
1283 guard let description else {
1284 return "<text:sequence-ref text:reference-format=\"value\" text:ref-name=\"\(reference)\">\(label.sequence)</text:sequence-ref>"
1285 }
1286 return "<text:a xlink:type=\"simple\" xlink:href=\"#\(reference)\">\(description)</text:a>"
1287 }
1288 }
1289
1290 /// A hyperlink, a clickable image when the description is only an image link.
1291 private func external(_ target: String, description: String?, image: Bool = false) -> String {
1292 let href = Self.escape(target, quotes: true)
1293 if image, let description { return "\n<draw:a xlink:type=\"simple\" xlink:href=\"\(href)\">\n\(description)\n</draw:a>" }
1294 return "<text:a xlink:type=\"simple\" xlink:href=\"\(href)\">\(description ?? Self.escape(target))</text:a>"
1295 }
1296
1297 /// A link to a heading: with a description, a hyperlink; without, its number or title.
1298 private func toHeading(_ heading: Heading, description: String?, customID: String?) -> String {
1299 if let description {
1300 return "<text:a xlink:type=\"simple\" xlink:href=\"#\(Self.escape(customID ?? heading.reference, quotes: true))\">\(description)</text:a>"
1301 }
1302 let chain = (heading.ancestors + [heading.key]).compactMap { headings[$0] }
1303 if chain.dropLast().contains(where: \.lowLevel) { return fail("ODT export doesn't number links to items under a heading deeper than H") }
1304 let regular = chain.reversed().first { !$0.lowLevel }
1305 if heading.number != nil, let numbered = chain.reversed().first(where: { !$0.lowLevel && $0.number != nil }) {
1306 return "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.\(heading.reference)\">\(numbered.number!.map(String.init).joined(separator: "."))</text:bookmark-ref>"
1307 }
1308 guard let regular else { return fail("FIXME?") }
1309 let title = regular.node.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
1310 return "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.\(heading.reference)\">\(title)</text:bookmark-ref>"
1311 }
1312
1313 // MARK: - Styles
1314
1315 /// The automatic styles of tables with `#+ATTR_ODT`.
1316 func automaticStyles() -> String {
1317 tableStyles.map {
1318 "\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"
1319 }.joined()
1320 }
1321
1322 // MARK: - Text
1323
1324 /// `:key value :other "quoted value"`.
1325 static func attributes(_ text: String) -> [String: String] {
1326 var pairs: [String: String] = [:]
1327 for m in text.matches(of: /:([A-Za-z_-]+)(?:[ \t]+("[^"]*"|[^:\s]\S*))?/) {
1328 var value = m.2.map(String.init) ?? "t"
1329 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
1330 pairs[m.1.lowercased()] = value
1331 }
1332 return pairs
1333 }
1334
1335 /// `&`, `<`, `>` (and `"` with `quotes`) escaped, characters XML forbids removed.
1336 static func escape(_ s: String, quotes: Bool = false) -> String {
1337 var out = ""
1338 for c in s.unicodeScalars {
1339 switch c {
1340 case "&": out += "&amp;"
1341 case "<": out += "&lt;"
1342 case ">": out += "&gt;"
1343 case "\"" where quotes: out += "&quot;"
1344 case "\t", "\n", "\r": out.unicodeScalars.append(c)
1345 case _ where c.value < 0x20 || c.value == 0xFFFE || c.value == 0xFFFF: continue
1346 default: out.unicodeScalars.append(c)
1347 }
1348 }
1349 return out
1350 }
1351
1352 /// `org-odt--encode-tabs-and-spaces`.
1353 static func encodeSpaces(_ s: String) -> String {
1354 s.replacing(/\t| {2,}/) { m in m.output == "\t" ? "<text:tab/>" : " <text:s text:c=\"\(m.output.count - 1)\"/>" }
1355 }
1356
1357 /// Rendered markup without its elements, for `meta.xml`.
1358 static func stripped(_ xml: String) -> String {
1359 xml.replacingOccurrences(of: "<[^>]*>", with: "", options: .regularExpression)
1360 }
1361}
Sources/OrgCore/Export/ODTTemplate.swift added +222
@@ -0,0 +1,222 @@
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 let sequences = ["Table", "Illustration", "Text", "Equation", "Listing"].map {
59 "<text:sequence-decl text:display-outline-level=\"2\" text:name=\"\($0)\"/>"
60 }.joined(separator: "\n")
61 return """
62 <?xml version="1.0" encoding="UTF-8"?>
63 <office:document-content
64 \(namespaces)>
65 <office:automatic-styles>
66 \(styles)\(automaticStyles) </office:automatic-styles>
67 <office:body>
68 <office:text>
69
70 <text:sequence-decls>
71 \(sequences)
72 </text:sequence-decls>\(body)
73 </office:text>
74 </office:body>
75 </office:document-content>
76
77 """
78 }
79
80 /// `author`, `title` and `subtitle` are XML text already.
81 static func meta(author: String, date: String?, keywords: String, description: String, title: String, subtitle: String) -> String {
82 let e = { ODTRenderer.escape($0) }
83 var out = """
84 <?xml version="1.0" encoding="UTF-8"?>
85 <office:document-meta
86 \(namespaces)>
87 <office:meta>
88 <dc:creator>\(author)</dc:creator>
89 <meta:initial-creator>\(author)</meta:initial-creator>
90
91 """
92 if let date { out += "<dc:date>\(date)</dc:date>\n<meta:creation-date>\(date)</meta:creation-date>\n" }
93 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"
94 if !subtitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
95 out += "<meta:user-defined meta:name=\"subtitle\">\(subtitle)</meta:user-defined>\n"
96 }
97 return out + "\n </office:meta>\n</office:document-meta>\n"
98 }
99
100 /// The manifest, which lists every part but `mimetype` (the package itself, `/`).
101 static func manifest(images: [String]) -> String {
102 var entries = [(mimetype, "/", " manifest:version=\"1.2\""), ("text/xml", "content.xml", ""), ("text/xml", "styles.xml", ""), ("text/xml", "meta.xml", "")]
103 if !images.isEmpty { entries.append(("", "Images/", "")) }
104 // ox-odt names the type after the extension.
105 entries += images.map { ("image/" + ($0 as NSString).pathExtension, $0, "") }
106 return """
107 <?xml version="1.0" encoding="UTF-8"?>
108 <manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
109 \(entries.map { "<manifest:file-entry manifest:media-type=\"\($0.0)\" manifest:full-path=\"\($0.1)\"\($0.2)/>" }.joined(separator: "\n"))
110 </manifest:manifest>
111
112 """
113 }
114
115 /// `styles.xml`: headings numbered to `numbered` levels, A4 pages with 2 cm margins.
116 static func styles(numbered: Int) -> String {
117 func paragraph(_ name: String, display: String? = nil, parent: String? = "Standard", _ properties: String = "", text: String = "") -> String {
118 var out = " <style:style style:name=\"\(name)\" style:display-name=\"\(display ?? name)\" style:family=\"paragraph\""
119 if let parent { out += " style:parent-style-name=\"\(parent)\"" }
120 out += ">"
121 if !properties.isEmpty { out += "<style:paragraph-properties \(properties)/>" }
122 if !text.isEmpty { out += "<style:text-properties \(text)/>" }
123 return out + "</style:style>\n"
124 }
125 func span(_ name: String, display: String? = nil, _ text: String) -> String {
126 " <style:style style:name=\"\(name)\" style:display-name=\"\(display ?? name)\" style:family=\"text\"><style:text-properties \(text)/></style:style>\n"
127 }
128 func graphic(_ name: String, _ properties: String) -> String {
129 " <style:style style:name=\"\(name)\" style:family=\"graphic\"><style:graphic-properties \(properties)/></style:style>\n"
130 }
131 let mono = "fo:font-family=\"Courier, monospace\" fo:font-size=\"10pt\""
132 let body = "fo:margin-top=\"0cm\" fo:margin-bottom=\"0.212cm\""
133 var styles = """
134 <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>
135 <style:style style:name="Standard" style:family="paragraph" style:class="text"/>
136
137 """
138 styles += paragraph("Text_20_body", display: "Text body", body)
139 styles += paragraph("Text_20_body_20_bold", display: "Text body bold", parent: "Text_20_body", text: "fo:font-weight=\"bold\"")
140 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\"")
141 let sizes = ["", "130%", "115%", "101%", "95%", "85%", "85%", "75%", "75%", "65%", "65%"]
142 for level in 1...10 {
143 let bold = "fo:font-size=\"\(sizes[level])\" fo:font-weight=\"bold\""
144 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"
145 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"
146 }
147 styles += paragraph("OrgTitle", "fo:text-align=\"center\" fo:margin-bottom=\"0.212cm\"", text: "fo:font-size=\"24pt\" fo:font-weight=\"bold\"")
148 styles += paragraph("OrgSubtitle", "fo:text-align=\"center\" fo:margin-bottom=\"0.212cm\"", text: "fo:font-size=\"14pt\"")
149 styles += paragraph("Quotations", parent: "Text_20_body", "fo:margin-left=\"1cm\" fo:margin-right=\"1cm\"")
150 styles += paragraph("OrgCenter", parent: "Text_20_body", "fo:text-align=\"center\"")
151 styles += paragraph("OrgVerse", parent: "Text_20_body", "fo:margin-left=\"1cm\"")
152 styles += paragraph("OrgSrcBlock", parent: "Standard", "fo:margin-top=\"0cm\" fo:margin-bottom=\"0cm\" fo:background-color=\"#f0f0f0\"", text: mono)
153 styles += paragraph("OrgSrcBlockLastLine", parent: "OrgSrcBlock", "fo:margin-bottom=\"0.212cm\"")
154 styles += paragraph("Footnote", parent: "Standard", "fo:margin-left=\"0.5cm\" fo:text-indent=\"-0.5cm\"", text: "fo:font-size=\"10pt\"")
155 styles += paragraph("OrgFootnoteCenter", parent: "Footnote", "fo:text-align=\"center\"")
156 styles += paragraph("OrgFootnoteQuotations", parent: "Footnote", "fo:margin-left=\"1cm\" fo:margin-right=\"1cm\"")
157 styles += paragraph("Table_20_Contents", display: "Table Contents", parent: "Standard")
158 for (name, align) in [("Left", "start"), ("Right", "end"), ("Center", "center")] {
159 styles += paragraph("OrgTableContents\(name)", parent: "Table_20_Contents", "fo:text-align=\"\(align)\"")
160 styles += paragraph("OrgTableHeading\(name)", parent: "Table_20_Contents", "fo:text-align=\"\(align)\"", text: "fo:font-weight=\"bold\"")
161 }
162 styles += paragraph("Contents_20_Heading", display: "Contents Heading", parent: "Heading", text: "fo:font-size=\"16pt\" fo:font-weight=\"bold\"")
163 for level in 1...10 {
164 styles += paragraph("Contents_20_\(level)", display: "Contents \(level)", parent: "Standard", "fo:margin-left=\"\(String(format: "%.3f", 0.499 * Double(level - 1)))cm\"")
165 }
166 styles += paragraph("Horizontal_20_Line", display: "Horizontal Line", parent: "Standard", "fo:margin-bottom=\"0.5cm\" fo:border-bottom=\"0.002cm solid #808080\"")
167 styles += paragraph("Caption", parent: "Standard", "fo:margin-top=\"0.212cm\" fo:margin-bottom=\"0.212cm\"", text: "fo:font-style=\"italic\" fo:font-size=\"10pt\"")
168 for name in ["Illustration", "Table", "Listing"] { styles += paragraph(name, parent: "Caption") }
169 styles += span("Emphasis", "fo:font-style=\"italic\"")
170 styles += span("Bold", "fo:font-weight=\"bold\"")
171 styles += span("Underline", "style:text-underline-style=\"solid\" style:text-underline-width=\"auto\" style:text-underline-color=\"font-color\"")
172 styles += span("Strikethrough", "style:text-line-through-style=\"solid\"")
173 styles += span("OrgCode", mono)
174 styles += span("OrgSubscript", "style:text-position=\"sub 58%\"")
175 styles += span("OrgSuperscript", "style:text-position=\"super 58%\"")
176 styles += span("OrgTodo", "fo:color=\"#b00000\" fo:font-weight=\"bold\"")
177 styles += span("OrgDone", "fo:color=\"#008000\" fo:font-weight=\"bold\"")
178 styles += span("OrgTags", "fo:font-size=\"85%\"")
179 styles += span("OrgTag", "fo:font-weight=\"bold\"")
180 styles += span("OrgPriority", "fo:font-weight=\"bold\"")
181 styles += span("OrgActiveTimestamp", "fo:color=\"#555555\"")
182 styles += span("OrgInactiveTimestamp", "fo:color=\"#888888\"")
183 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\"")
184 styles += graphic("OrgDisplayImage", "style:wrap=\"none\" style:vertical-pos=\"top\" style:vertical-rel=\"paragraph\" style:horizontal-pos=\"center\" style:horizontal-rel=\"paragraph\"")
185 styles += graphic("OrgInlineImage", "style:vertical-pos=\"middle\" style:vertical-rel=\"text\"")
186 styles += graphic("OrgCaptionedImage", "style:wrap=\"none\" style:vertical-pos=\"top\" style:vertical-rel=\"paragraph\" style:horizontal-pos=\"center\" style:horizontal-rel=\"paragraph\"")
187 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\"")
188 func list(_ name: String, _ level: (Int) -> String) -> String {
189 " <text:list-style style:name=\"\(name)\">\n" + (1...10).map(level).joined() + " </text:list-style>\n"
190 }
191 func position(_ level: Int) -> String {
192 let indent = String(format: "%.3fcm", 0.635 * Double(level))
193 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>"
194 }
195 styles += list("OrgBulletedList") { " <text:list-level-style-bullet text:level=\"\($0)\" text:bullet-char=\"•\">\(position($0))</text:list-level-style-bullet>\n" }
196 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" }
197 styles += list("OrgDescriptionList") { " <text:list-level-style-number text:level=\"\($0)\" style:num-format=\"\">\(position($0))</text:list-level-style-number>\n" }
198 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" }
199 styles += " <text:outline-style style:name=\"Outline\">\n"
200 for level in 1...10 {
201 let format = level <= numbered ? "style:num-format=\"1\" style:num-suffix=\".\" text:display-levels=\"\(level)\"" : "style:num-format=\"\""
202 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"
203 }
204 styles += " </text:outline-style>\n"
205 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"
206 return """
207 <?xml version="1.0" encoding="UTF-8"?>
208 <office:document-styles
209 \(namespaces)>
210 <office:styles>
211 \(styles) </office:styles>
212 <office:automatic-styles>
213 <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>
214 </office:automatic-styles>
215 <office:master-styles>
216 <style:master-page style:name="Standard" style:page-layout-name="OrgPage"/>
217 </office:master-styles>
218 </office:document-styles>
219
220 """
221 }
222}
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}
Tests/OrgCoreTests/ODTExportTests.swift added +502
@@ -0,0 +1,502 @@
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, tables and their rows and cells, links
9/// and images with their targets, notes and frames, and the text runs. Spaces written as
10/// elements count as spaces; references are numbered in order of appearance, since ox-odt's
11/// are random.
12enum ODTSkeleton {
13 static let kept: Set<String> = [
14 "text:h", "text:p", "text:list", "text:list-item", "text:list-header", "text:section", "text:note",
15 "table:table", "table:table-header-rows", "table:table-rows", "table:table-row", "table:table-cell", "table:covered-table-cell",
16 "text:a", "draw:a", "draw:frame", "draw:image", "draw:text-box", "text:table-of-content", "text:index-body",
17 ]
18
19 static func reduce(_ xml: String) -> String {
20 guard let start = xml.range(of: "<office:text>"), let end = xml.range(of: "</office:text>") else { return xml }
21 let body = xml[start.upperBound..<end.lowerBound]
22 var lines: [String] = []
23 var text = ""
24 var references: [String: Int] = [:]
25 func flush() {
26 let collapsed = Skeleton.decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ")
27 if !collapsed.isEmpty { lines.append("\"" + collapsed + "\"") }
28 text = ""
29 }
30 var i = body.startIndex
31 while i < body.endIndex {
32 guard body[i] == "<", let close = body[i...].firstIndex(of: ">") else {
33 text.append(body[i])
34 i = body.index(after: i)
35 continue
36 }
37 let tag = String(body[body.index(after: i)..<close])
38 i = body.index(after: close)
39 if tag.hasPrefix("!") || tag.hasPrefix("?") { continue }
40 let closing = tag.hasPrefix("/")
41 let name = String(tag.dropFirst(closing ? 1 : 0).prefix { !$0.isWhitespace && $0 != "/" })
42 switch name {
43 case "text:s":
44 let count = tag.firstMatch(of: /text:c="([0-9]+)"/).flatMap { Int($0.1) } ?? 1
45 text += String(repeating: " ", count: count)
46 continue
47 case "text:tab", "text:line-break":
48 text += " "
49 continue
50 default:
51 break
52 }
53 guard kept.contains(name) else { continue }
54 flush()
55 if closing {
56 lines.append("</\(name)>")
57 continue
58 }
59 var attributes = ""
60 if let level = tag.firstMatch(of: /text:outline-level="([0-9]+)"/) { attributes += " level=\(level.1)" }
61 if let href = tag.firstMatch(of: /xlink:href="([^"]*)"/) {
62 var value = String(href.1)
63 if value.hasPrefix("#") {
64 let n = references[value] ?? references.count + 1
65 references[value] = n
66 value = "#ref\(n)"
67 }
68 attributes += " href=\"\(value)\""
69 }
70 if let span = tag.firstMatch(of: /table:number-columns-spanned="([0-9]+)"/) { attributes += " span=\(span.1)" }
71 lines.append("<\(name)\(attributes)>")
72 if tag.hasSuffix("/") { lines.append("</\(name)>") }
73 }
74 flush()
75 return lines.joined(separator: "\n") + "\n"
76 }
77}
78
79/// Reads a zip's entries, stored or deflated, through `unzip` for the latter.
80enum ZipReader {
81 struct Entry {
82 var name: String
83 var method: UInt16
84 var extraLength: UInt16
85 var data: Data
86 }
87
88 /// The local entries in order.
89 static func entries(_ data: Data) -> [Entry] {
90 var out: [Entry] = []
91 var at = 0
92 let bytes = [UInt8](data)
93 func u16(_ i: Int) -> UInt16 { UInt16(bytes[i]) | UInt16(bytes[i + 1]) << 8 }
94 func u32(_ i: Int) -> UInt32 { UInt32(u16(i)) | UInt32(u16(i + 2)) << 16 }
95 while at + 30 <= bytes.count, u32(at) == 0x04034b50 {
96 let method = u16(at + 8)
97 let size = Int(u32(at + 18))
98 let nameLength = Int(u16(at + 26))
99 let extra = u16(at + 28)
100 let name = String(decoding: bytes[(at + 30)..<(at + 30 + nameLength)], as: UTF8.self)
101 let start = at + 30 + nameLength + Int(extra)
102 out.append(Entry(name: name, method: method, extraLength: extra, data: Data(bytes[start..<(start + size)])))
103 at = start + size
104 }
105 return out
106 }
107
108 /// The names the central directory lists.
109 static func directory(_ data: Data) -> [String] {
110 let bytes = [UInt8](data)
111 var names: [String] = []
112 var i = 0
113 while i + 46 <= bytes.count {
114 if bytes[i] == 0x50, bytes[i + 1] == 0x4b, bytes[i + 2] == 0x01, bytes[i + 3] == 0x02 {
115 let length = Int(bytes[i + 28]) | Int(bytes[i + 29]) << 8
116 names.append(String(decoding: bytes[(i + 46)..<(i + 46 + length)], as: UTF8.self))
117 i += 46 + length
118 } else {
119 i += 1
120 }
121 }
122 return names
123 }
124}
125
126struct ODTExportTests {
127 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable
128
129 /// A PNG of `width` by `height` pixels.
130 static func png(width: Int, height: Int) -> Data {
131 let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
132 space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
133 context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
134 context.fill(CGRect(x: 0, y: 0, width: width, height: height))
135 let data = NSMutableData()
136 let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)!
137 CGImageDestinationAddImage(destination, context.makeImage()!, nil)
138 CGImageDestinationFinalize(destination)
139 return data as Data
140 }
141
142 static let corpus = ["minimal", "core", "headings", "listblocks", "lists", "table", "blocks", "timestamps", "footnote", "tblfm"]
143
144 /// Documents for what the corpus doesn't cover. `PIC` is replaced by an image's path.
145 static let snippets: [String: String] = [
146 "images": """
147 #+TITLE: Images
148
149 [[file:PIC]]
150
151 #+CAPTION: A captioned picture
152 #+NAME: fig:one
153 [[file:PIC]]
154
155 Inline [[file:PIC]] in text and a [[file:PIC][described]] link.
156
157 #+ATTR_ODT: :width 3
158 [[file:PIC]]
159
160 See [[fig:one]] and [[fig:one][the figure]].
161
162 [[https://example.com][file:PIC]]
163 """,
164 "tables": """
165 #+TITLE: Tables
166 #+OPTIONS: toc:nil
167
168 * One
169 #+CAPTION: Scores
170 #+NAME: tbl:scores
171 | Name | <r> |
172 | Name | Score |
173 |-------+-------|
174 | alpha | 10 |
175 |-------+-------|
176 | beta | x |
177 | gamma | |
178
179 Refer to [[tbl:scores]].
180
181 | / | <> | |
182 | # | a | b |
183 | ! | x | y |
184 | # | 1 | 2 |
185
186 | <5> | b |
187 | 1 | 2 |
188
189 #+ATTR_ODT: :rel-width 50
190 | c | d |
191 """,
192 "list-tables": """
193 #+OPTIONS: toc:nil
194
195 1. first
196 - nested
197 | a | b |
198 | 1 | 2 |
199 after the table
200 - next nested
201 2. second
202 | x |
203 | y |
204 then text
205 | z |
206
207 - term :: definition
208 | t |
209 """,
210 "footnotes": """
211 #+OPTIONS: toc:nil
212
213 One[fn:a][fn:b] and again[fn:a], anonymous[fn:: inline /note/].
214
215 [fn:a] First note.
216
217 With a second paragraph.
218 [fn:b] Second note.
219 """,
220 "low-levels": """
221 #+OPTIONS: H:2
222
223 * Top
224 ** Second
225 *** Third
226 Text under third.
227 **** Fourth
228 | cell |
229 *** Third again
230 * Other
231 """,
232 "links": """
233 #+TITLE: Links
234
235 * Alpha
236 :PROPERTIES:
237 :CUSTOM_ID: alpha-id
238 :ID: 1234-abcd
239 :END:
240 Go to [[*Beta]], [[Beta][the beta]], [[#alpha-id][custom]], [[#alpha-id]], [[id:1234-abcd]] and <<here>>.
241 * Beta
242 A <<<radio word>>> and later the radio word again. [[here][back]].
243 Mail [[mailto:a@b.c][me]], a file [[file:notes.txt]], ./rel.txt and [[./dir/x.org][rel]].
244 #+begin_src emacs-lisp -n -r
245 (setq x 1) (ref:one)
246 (setq y 2)
247 #+end_src
248 Line [[(one)]] and [[(one)][line %s]].
249 * Gamma :noexport:
250 Excluded.
251 * COMMENT Delta
252 Commented.
253 """,
254 "inline": """
255 #+TITLE: Inline /markup/
256 #+SUBTITLE: The subtitle
257 #+AUTHOR: Someone
258 #+DATE: <2024-03-01 Fri>
259 #+OPTIONS: num:nil pri:t
260
261 * TODO [#B] Heading with =code= :tag:
262 Text with *bold*, /italic/, _under_, +strike+, ~code spaced~, =verb=.
263 Math \\(a+b\\) and $x$ and \\alpha and H_2O and x^{2} and e^x.
264 Dashes -- and --- and ... and a\\-b.
265 Line one\\\\
266 line two.
267 @@odt:<text:span>raw</text:span>@@ and @@html:<b>no</b>@@ and [2/3] cookie.
268 #+ODT: <text:p>raw paragraph</text:p>
269
270 -----
271
272 \\begin{equation}
273 E = mc^2
274 \\end{equation}
275
276 :NOTES:
277 Drawer contents.
278 :END:
279
280 #+begin_verse
281 Indented first
282 second line
283 #+end_verse
284
285 #+begin_example -n
286 one
287 two
288 #+end_example
289
290 #+CAPTION: A listing
291 #+begin_src python
292 print("x")
293 #+end_src
294
295 : fixed width
296 : lines
297
298 #+begin_center
299 Centered *text*.
300 #+end_center
301
302 #+TOC: headlines 1
303 """,
304 "more": """
305 #+OPTIONS: toc:nil
306
307 * Heading
308 #+begin_src python
309
310 x = 1
311
312 y = 2
313
314 #+end_src
315
316 #+begin_example
317 ex
318
319
320 #+end_example
321
322 3. [@3] third
323 4. fourth
324 - [X] term :: def
325 - [ ] other :: more
326
327 #+begin_quote
328 - a quoted item
329 #+end_quote
330
331 [2024-01-01 Mon]--[2024-01-02 Tue] and <2024-01-01 Mon 10:00>
332
333 #+TOC: headlines local
334
335 ** Sub
336 Text \\alpha{} \\beta and \\nbsp{}.
337
338 #+begin_textbox
339 Boxed.
340 #+end_textbox
341
342 #+begin_annotation
343 Noted.
344 #+end_annotation
345 """,
346 "options": """
347 #+OPTIONS: toc:1 num:1 todo:nil tags:nil author:nil date:nil title:nil -:nil ^:{} tex:nil
348
349 * DONE First :x:
350 ** Sub
351 Text -- here a_b and a_{b} and \\(x\\).
352 * Second
353 """,
354 ]
355
356 /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the
357 /// message.
358 static func emacs(_ files: [URL]) throws -> [String] {
359 let folder = files[0].deletingLastPathComponent()
360 let output = folder.appendingPathComponent("out.json")
361 let script = folder.appendingPathComponent("odt.el")
362 try """
363 ;;; -*- lexical-binding: t -*-
364 (require 'ox-odt)
365 (require 'json)
366 (setq user-full-name "Tester")
367 (let (results)
368 (dolist (file (split-string (getenv "ODT_FILES") "\\n" t))
369 (push (condition-case err
370 (with-current-buffer (find-file-noselect file)
371 (let ((odt (org-odt-export-to-odt)))
372 (with-temp-buffer
373 (let ((coding-system-for-read 'utf-8))
374 (call-process "unzip" nil t nil "-p" odt "content.xml"))
375 (buffer-string))))
376 (error (concat "ERROR: " (error-message-string err))))
377 results))
378 (let ((coding-system-for-write 'utf-8))
379 (with-temp-file (getenv "ODT_OUTPUT")
380 (insert (json-encode (vconcat (nreverse results)))))))
381 """.write(to: script, atomically: true, encoding: .utf8)
382 try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: [
383 "ODT_FILES": files.map(\.path).joined(separator: "\n"), "ODT_OUTPUT": output.path, "TZ": "UTC",
384 ])
385 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
386 }
387
388 static func content(_ text: String, path: String) throws -> String {
389 let parts = try ODTExport.parts(text, path: path, author: "Tester")
390 return String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
391 }
392
393 @Test(.enabled(if: oracle))
394 func matchesOxODT() throws {
395 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
396 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
397 defer { try? FileManager.default.removeItem(at: folder) }
398 let picture = folder.appendingPathComponent("pic.png")
399 try Self.png(width: 64, height: 48).write(to: picture)
400 var documents: [(name: String, text: String)] = []
401 for name in Self.corpus {
402 documents.append((name, try String(contentsOf: ExportTests.folder.appendingPathComponent("\(name).org"), encoding: .utf8)))
403 }
404 for (name, text) in Self.snippets.sorted(by: { $0.key < $1.key }) {
405 documents.append((name, text.replacingOccurrences(of: "PIC", with: picture.path) + "\n"))
406 }
407 let files = documents.map { folder.appendingPathComponent($0.name + ".org") }
408 for (document, file) in zip(documents, files) { try document.text.write(to: file, atomically: true, encoding: .utf8) }
409 let expected = try Self.emacs(files)
410 for (index, document) in documents.enumerated() {
411 let theirs = ODTSkeleton.reduce(expected[index])
412 let ours = ODTSkeleton.reduce(try Self.content(document.text, path: files[index].path))
413 #expect(ours == theirs, "\(document.name)\n--- ours\n\(ours)\n--- ox-odt\n\(theirs)")
414 }
415 }
416
417 /// Where ox-odt stops, the export stops with its message.
418 @Test(.enabled(if: oracle))
419 func failsLikeOxODT() throws {
420 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
421 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
422 defer { try? FileManager.default.removeItem(at: folder) }
423 let documents = [
424 "broken": "See [[nowhere]].\n",
425 "missing": "[[file:missing.png]]\n",
426 "elements": try String(contentsOf: ExportTests.folder.appendingPathComponent("elements.org"), encoding: .utf8),
427 ].sorted { $0.key < $1.key }
428 let files = documents.map { folder.appendingPathComponent($0.key + ".org") }
429 for (document, file) in zip(documents, files) { try document.value.write(to: file, atomically: true, encoding: .utf8) }
430 let expected = try Self.emacs(files)
431 for (index, document) in documents.enumerated() {
432 #expect(expected[index].hasPrefix("ERROR: "), "\(document.key)")
433 #expect(throws: ODTExport.Failure.self) { try Self.content(document.value, path: files[index].path) }
434 do {
435 _ = try Self.content(document.value, path: files[index].path)
436 } catch let failure as ODTExport.Failure {
437 #expect(expected[index].contains(failure.message), "\(document.key): \(failure.message) / \(expected[index])")
438 }
439 }
440 }
441
442 /// `mimetype` first and stored, with no extra field; the manifest lists every part; each
443 /// XML part parses.
444 @Test func package() throws {
445 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
446 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
447 defer { try? FileManager.default.removeItem(at: folder) }
448 try Self.png(width: 10, height: 10).write(to: folder.appendingPathComponent("a.png"))
449 let path = folder.appendingPathComponent("doc.org").path
450 let data = try ODTExport.document("#+TITLE: T & U\n\n* Heading\n[[./a.png]]\n\n| x | y |\n", path: path)
451 let entries = ZipReader.entries(data)
452 #expect(entries.first?.name == "mimetype")
453 #expect(entries.first?.method == 0)
454 #expect(entries.first?.extraLength == 0)
455 #expect(entries.first.map { String(decoding: $0.data, as: UTF8.self) } == "application/vnd.oasis.opendocument.text")
456 #expect(ZipReader.directory(data) == entries.map(\.name))
457 #expect(entries.map(\.name) == ["mimetype", "content.xml", "styles.xml", "meta.xml", "Images/0001.png", "META-INF/manifest.xml"])
458 let manifest = try XMLDocument(data: entries.last!.data)
459 let listed = try manifest.nodes(forXPath: "//*[local-name()='file-entry']/@*[local-name()='full-path']").compactMap(\.stringValue)
460 for entry in entries where !["mimetype", "META-INF/manifest.xml"].contains(entry.name) {
461 #expect(listed.contains(entry.name), "\(entry.name)")
462 }
463 #expect(listed.contains("/"))
464 for entry in entries where entry.name.hasSuffix(".xml") {
465 #expect(throws: Never.self) { try XMLDocument(data: entry.data) }
466 }
467 let content = try XMLDocument(data: entries[1].data)
468 #expect(try content.nodes(forXPath: "//*[local-name()='h']").count == 1)
469 #expect(try content.nodes(forXPath: "//*[local-name()='image']/@*[local-name()='href']").compactMap(\.stringValue) == ["Images/0001.png"])
470 #expect(try content.nodes(forXPath: "//*[local-name()='table-cell']").count == 2)
471 let meta = try XMLDocument(data: entries[3].data)
472 #expect(try meta.nodes(forXPath: "//*[local-name()='title']").first?.stringValue == "T & U")
473 }
474
475 /// The text system reads the file: headings, list items, table cells and notes.
476 @Test func opensInTextKit() throws {
477 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"
478 let data = try ODTExport.document(text, path: "/tmp/doc.org")
479 let string = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.openDocument], documentAttributes: nil).string
480 for word in ["Opened", "Heading", "item one", "item two", "a", "2", "A note."] {
481 #expect(string.contains(word), "\(word) in \(string)")
482 }
483 }
484
485 /// What the native export can't write the way ox-odt does stops the export instead.
486 @Test(arguments: [
487 "*************** Task\nBody.\n*************** END\n",
488 "Here <<there>> and [[there]].\n",
489 "#+begin_src emacs-lisp\n(x) (ref:a)\n#+end_src\n[[(a)]]\n",
490 "#+ATTR_ODT: :style TableWithHeaderRowAndColumn\n| a |\n",
491 "Code src_python[:exports code]{1 + 1} here.\n",
492 "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n",
493 ])
494 func refuses(_ text: String) {
495 #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") }
496 }
497
498 @Test func imageFiles() {
499 let files = ODTExport.imageFiles("[[file:a.png]] [[./b.jpg][desc]] [[https://x/c.png]] [[/abs/d.svg]]\n", path: "/doc/notes.org")
500 #expect(files == ["/doc/a.png", "/abs/d.svg"])
501 }
502}