Commit 170754362d

170754362d73a02a243ce6434e8b36e71758546a

parent: 54187b18af

Verified · cmc

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

Match ox-odt on numbering, footnotes, TOCs, tables and options

Number headings past H for num:t, number footnotes body first and find
inline definitions, count TOC depth from a local scope and inherit
notoc, ignore cookie rows for table headers, name table styles by
table count, and give src blocks without an Emacs mode ox-odt's plain
style. Honor \n, f, |, e and d in #+OPTIONS and refuse the other
options ox-odt reads. List described and included images for sandbox
access, and define the priority and Sect1 styles. The oracle test now
compares style names, spans and line breaks.

Layout: unified · split

Sources/OrgCore/Export/ODTExport.swift +217 −61
@@ -27,12 +27,19 @@ public enum ODTExport {
2727 }
2828
2929 /// The image files `text` embeds, for the sandbox to reach before exporting.
30 /// Images in `#+INCLUDE`d files and images shown as a link's description count.
3031 public static func imageFiles(_ text: String, settings: OrgSettings = .default, path: String) -> [String] {
3132 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
33 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, setup: settings.setupKeywords)
3234 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
35 guard node.kind == .link else { return nil }
36 let file: String?
37 if let description = node.firstChild(.linkDescription) {
38 file = ODTRenderer.describedImage(description)
39 } else {
40 file = ODTRenderer.filePath(node.tokens.first { $0.kind == .linkPath }?.text ?? "").flatMap { ODTRenderer.isImage($0) ? $0 : nil }
41 }
42 return file.map { ODTRenderer.expand($0, directory: directory).path }
3643 }
3744 }
3845
@@ -46,6 +53,7 @@ public enum ODTExport {
4653 let meta = HTMLExport.metadata(text, settings: settings)
4754 let keywords = Self.keywords(text, settings: settings)
4855 let renderer = ODTRenderer(settings: settings, options: options, directory: directory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath))
56 try Self.read(settings.setupKeywords + text, into: renderer)
4957 renderer.language = meta.language ?? language
5058
5159 // The title isn't part of the document Org processes citations in: they drop out.
@@ -88,13 +96,49 @@ public enum ODTExport {
8896
8997 var parts: [(name: String, data: Data)] = [("mimetype", Data(ODTTemplate.mimetype.utf8))]
9098 parts.append(("content.xml", Data(contents.utf8)))
91 parts.append(("styles.xml", Data(ODTTemplate.styles(numbered: options.num ?? 0).utf8)))
99 parts.append(("styles.xml", Data(ODTTemplate.styles(numbered: min(renderer.numbered ?? 0, 10)).utf8)))
92100 parts.append(("meta.xml", Data(metaXML.utf8)))
93101 parts += renderer.images.map { ($0.name, $0.data) }
94102 parts.append(("META-INF/manifest.xml", Data(ODTTemplate.manifest(images: renderer.images.map(\.name)).utf8)))
95103 return parts
96104 }
97105
106 /// The `#+OPTIONS` items ox-odt reads that `ExportOptions` doesn't, or reads differently:
107 /// `num` to any depth, `\\n`, `f`, `|`, `e` and `d` honored; other items at a value other
108 /// than their default stop the export.
109 static func read(_ text: String, into renderer: ODTRenderer) throws {
110 var items: [String: String] = [:]
111 for line in text.matches(of: #/(?mi)^[ \t]*#\+OPTIONS:[ \t]*(.*?)[ \t]*$/#) {
112 for item in line.1.matches(of: /(\S+?):(\S+)/) { items[String(item.1)] = String(item.2) }
113 }
114 let defaults = [
115 "p": "nil", "broken-links": "nil", "c": "nil", "prop": "nil", ":": "t", "*": "t", "stat": "t",
116 "tasks": "t", "<": "t", "arch": "headline", "email": "nil", "'": "nil",
117 ]
118 for (key, value) in items.sorted(by: { $0.key < $1.key }) {
119 if let standard = defaults[key], value != standard {
120 throw Failure(message: "ODT export doesn't support #+OPTIONS: \(key):\(value)")
121 }
122 }
123 if let tex = items["tex"], tex != "t", tex != "nil" { throw Failure(message: "ODT export doesn't support #+OPTIONS: tex:\(tex)") }
124 switch items["d"] {
125 case nil: renderer.drawers = nil
126 case "nil": renderer.drawers = false
127 case "t": renderer.drawers = true
128 case let value?: throw Failure(message: "ODT export doesn't support #+OPTIONS: d:\(value)")
129 }
130 // `org-export-numbered-headline-p`: `t` numbers every level, `N` levels to N, past `H`.
131 switch items["num"] {
132 case "nil": renderer.numbered = nil
133 case let value?: renderer.numbered = Int(value) ?? Int.max
134 case nil: renderer.numbered = Int.max
135 }
136 renderer.preserveBreaks = items["\\n"].map { $0 != "nil" } ?? false
137 renderer.withFootnotes = items["f"] != "nil"
138 renderer.withTables = items["|"] != "nil"
139 renderer.withEntities = items["e"] != "nil"
140 }
141
98142 /// `#+SUBTITLE`, `#+KEYWORDS` and `#+DESCRIPTION`: lines of the same keyword joined.
99143 static func keywords(_ text: String, settings: OrgSettings) -> [String: String] {
100144 let tree = OrgParser.parse(text, defaults: settings)
@@ -132,6 +176,16 @@ final class ODTRenderer {
132176 private(set) var failure: ODTExport.Failure?
133177 private(set) var images: [(name: String, data: Data)] = []
134178
179 /// `num`: headings numbered to this relative level, `Int.max` for all; nil for none.
180 var numbered: Int? = Int.max
181 /// `\\n`, `f`, `|` and `e`.
182 var preserveBreaks = false
183 var withFootnotes = true
184 var withTables = true
185 var withEntities = true
186 /// `d`: nil for every drawer but `LOGBOOK`, true for every drawer, false for none.
187 var drawers: Bool?
188
135189 init(settings: OrgSettings, options: ExportOptions, directory: URL) {
136190 self.settings = settings
137191 self.options = options
@@ -176,7 +230,8 @@ final class ODTRenderer {
176230 private var selected: Set<Int>?
177231 private var documentTree: OrgTree?
178232 private var blockLocs: [String: [Int?]] = [:]
179 private var definitions: [String: (text: String, base: Int)] = [:]
233 /// Footnote definitions by label: the last in the document, a definition or an inline one.
234 private var definitions: [String: (text: String, base: Int, inline: Bool)] = [:]
180235
181236 /// Where the tree being read starts in the document, so elements read from a block's or a
182237 /// footnote's contents keep their place; how deep in such contents it is.
@@ -204,11 +259,8 @@ final class ODTRenderer {
204259 heading.relative = heading.level - top + 1
205260 heading.lowLevel = heading.relative > options.headlineLevels
206261 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 {
262 let unnumbered = unnumberedValue(heading).map { $0 != "nil" } ?? false
263 if let numbered, heading.relative <= numbered, !unnumbered {
212264 let index = heading.relative - 1
213265 if counters.count <= index { counters += Array(repeating: 0, count: index + 1 - counters.count) }
214266 counters[index] += 1
@@ -229,6 +281,16 @@ final class ODTRenderer {
229281 }
230282 }
231283
284 /// `UNNUMBERED` of the heading or its closest ancestor that has it.
285 private func unnumberedValue(_ heading: Heading) -> String? {
286 for key in [heading.key] + heading.ancestors.reversed() {
287 if let value = headings[key]?.info?.properties.last(where: { $0.key.uppercased() == "UNNUMBERED" })?.value {
288 return value.trimmingCharacters(in: .whitespaces)
289 }
290 }
291 return nil
292 }
293
232294 private func collect(_ node: SyntaxNode, ancestors: [Int], infos: [Int: HeadingInfo]) {
233295 var affiliated: [String: String] = [:]
234296 for child in node.children {
@@ -260,6 +322,7 @@ final class ODTRenderer {
260322 let inner = child.kind == .target ? child.text.dropFirst(2).dropLast(2) : child.text.dropFirst(3).dropLast(3)
261323 targets.append((Self.words(inner.uppercased()), key, newReference()))
262324 case .table:
325 guard withTables else { continue }
263326 if captioned { enumerables.append((key, "Table", ancestors)) }
264327 collect(child, ancestors: ancestors, infos: infos)
265328 case .paragraph:
@@ -271,7 +334,7 @@ final class ODTRenderer {
271334 if ["src", "example", "export", "comment", "verse"].contains(type) { continue }
272335 within(body.text, base: key + body.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
273336 case .drawer, .dynamicBlock:
274 guard let inner = Self.inner(child) else { continue }
337 guard let inner = inner(child) else { continue }
275338 within(inner.text, base: key + inner.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
276339 default:
277340 collect(child, ancestors: ancestors, infos: infos)
@@ -279,13 +342,13 @@ final class ODTRenderer {
279342 }
280343 }
281344
282 /// A drawer's or dynamic block's contents and their offset in it; nil for `LOGBOOK`, which
283 /// isn't exported.
284 static func inner(_ node: SyntaxNode) -> (text: String, offset: Int)? {
345 /// A drawer's or dynamic block's contents and their offset in it; nil for a drawer `d`
346 /// leaves out.
347 private func inner(_ node: SyntaxNode) -> (text: String, offset: Int)? {
285348 var lines = node.text.components(separatedBy: "\n")
286349 if lines.last == "" { lines.removeLast() }
287350 guard let first = lines.first else { return nil }
288 if node.kind == .drawer, first.trimmingCharacters(in: .whitespaces).uppercased() == ":LOGBOOK:" { return nil }
351 if node.kind == .drawer, !(drawers ?? (first.trimmingCharacters(in: .whitespaces).uppercased() != ":LOGBOOK:")) { return nil }
289352 return (lines.dropFirst().dropLast().joined(separator: "\n"), first.utf16.count + 1)
290353 }
291354
@@ -333,10 +396,11 @@ final class ODTRenderer {
333396 end = sibling.range.upperBound
334397 }
335398 }
336 definitions[String(m.1)] = (ns.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .newlines), start)
399 definitions[String(m.1)] = (ns.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .newlines), start, false)
337400 }
338401 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
339402 collect(tree)
403 if footnotePass == nil, withFootnotes { numberFootnotes(text) }
340404 return rendering(tree, text) { tree.root.children.map(element).joined() }
341405 }
342406
@@ -357,14 +421,19 @@ final class ODTRenderer {
357421 /// `org-odt-toc` for the whole document: headings to `toc`, or nothing.
358422 func tableOfContents() -> String {
359423 guard let depth = options.toc else { return "" }
360 return toc(depth: depth, scope: nil)
424 return toc(depth: depth, scope: nil, template: true)
361425 }
362426
363 private func toc(depth: Int, scope: Int?) -> String {
427 /// `org-export-collect-headlines`: `depth` relative to `scope`, within `H`, without the
428 /// headings `org-export-excluded-from-toc-p` leaves out.
429 /// In the `template` one, ox-odt reads `org-done-keywords` outside the Org buffer, where
430 /// it's empty: every keyword is a TODO one.
431 private func toc(depth: Int, scope: Int?, template: Bool = false) -> String {
432 let limit = min(scope.flatMap { headings[$0].map { $0.relative + depth } } ?? depth, options.headlineLevels)
364433 let keys = headingOrder.filter { key in
365434 let heading = headings[key]!
366 let notoc = heading.info?.properties.last { $0.key.uppercased() == "UNNUMBERED" }?.value.trimmingCharacters(in: .whitespaces) == "notoc"
367 return heading.relative <= depth && !notoc && (scope.map { heading.ancestors.contains($0) } ?? true)
435 let excluded = heading.lowLevel || unnumberedValue(heading) == "notoc" || options.toc.map { heading.relative > $0 } ?? false
436 return heading.relative <= limit && !excluded && (scope.map { heading.ancestors.contains($0) } ?? true)
368437 }
369438 guard !keys.isEmpty else { return "" }
370439 let title = scope == nil ? ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8) : nil
@@ -392,7 +461,7 @@ final class ODTRenderer {
392461 let heading = headings[key]!
393462 var entry = heading.number.map { $0.map(String.init).joined(separator: ".") + ". " } ?? ""
394463 let parts = headlineParts(heading.node)
395 if let todo = parts.todo { entry += "<text:span text:style-name=\"\(settings.isDone(todo) ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
464 if let todo = parts.todo { entry += "<text:span text:style-name=\"\(settings.isDone(todo) && !template ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
396465 if let priority = parts.priority { entry += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
397466 entry += parts.title
398467 if options.tagsInTOC, !parts.tags.isEmpty { entry += " " + tagsSpan(parts.tags) }
@@ -446,13 +515,13 @@ final class ODTRenderer {
446515 case .plainList:
447516 return list(node)
448517 case .table:
449 return table(node)
518 return withTables ? table(node) : ""
450519 case .block:
451520 return block(node)
452521 case .horizontalRule:
453522 return "\n<text:p text:style-name=\"Horizontal_20_Line\"></text:p>"
454523 case .drawer, .dynamicBlock:
455 guard let inner = Self.inner(node) else { return "" }
524 guard let inner = inner(node) else { return "" }
456525 return blocks(inner.text, base: base + node.range.lowerBound + inner.offset)
457526 case .inlineTask:
458527 // `emacs -Q` doesn't load org-inlinetask, so ox-odt reads them as headings.
@@ -469,7 +538,7 @@ final class ODTRenderer {
469538 return code(lines)
470539 case .tableEl:
471540 // ox-odt strips table.el tables, the list around them closed and opened again.
472 return frames.isEmpty ? "" : "\n" + reopening(nil, for: node)
541 return frames.isEmpty || !withTables ? "" : "\n" + reopening(nil, for: node)
473542 default:
474543 // Comments, property drawers, planning, clocks, footnote definitions, formulas.
475544 return ""
@@ -555,7 +624,13 @@ final class ODTRenderer {
555624 imageCaption = affiliated["CAPTION"]
556625 imageAttributes = affiliated["ATTR_ODT"]
557626 defer { imageKey = nil; imageCaptioned = false; imageCaption = nil; imageAttributes = nil }
558 return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(inline(node).trimmingCharacters(in: .whitespacesAndNewlines))</text:p>"
627 var contents = inline(node)
628 // The paragraph's own last newline isn't a line break.
629 if preserveBreaks, node.text.hasSuffix("\n"), node.text.range(of: "\\\\\\\\[ \t]*\n$", options: .regularExpression) == nil,
630 contents.hasSuffix("<text:line-break/>") {
631 contents.removeLast("<text:line-break/>".count)
632 }
633 return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(contents.trimmingCharacters(in: .whitespacesAndNewlines))</text:p>"
559634 }
560635
561636 /// The link of a paragraph that is only an image link.
@@ -695,6 +770,7 @@ final class ODTRenderer {
695770 // MARK: - Tables
696771
697772 private var tableStyles: [(name: String, width: String)] = []
773 private var tableCount = 0
698774
699775 private func table(_ node: SyntaxNode) -> String {
700776 let attributeLine = affiliated["ATTR_ODT"]
@@ -756,10 +832,11 @@ final class ODTRenderer {
756832 if kinds[r] == .rule, seen { current += 1; seen = false }
757833 if kinds[r] == .data { group[r] = current; seen = true }
758834 }
759 let firstData = rows.indices.first { kinds[$0] == .data || kinds[$0] == .special }
835 // `org-export-table-has-header-p`: a rule between data rows; special rows don't count.
836 let firstData = data.first
760837 let hasHeader = firstData.map { start in
761838 guard let rule = rows.indices.first(where: { $0 > start && kinds[$0] == .rule }) else { return false }
762 return rule + 1 < rows.count
839 return data.contains { $0 > rule }
763840 } ?? false
764841 let headerColumns = attributes["header-columns"].map { Int($0) ?? 1 } ?? 0
765842 var body = ""
@@ -784,9 +861,11 @@ final class ODTRenderer {
784861 body += "\n<table:table-row>\n\(row)\n</table:table-row>"
785862 if ends { body += header ? "\n</table:table-header-rows>" : "\n</table:table-rows>" }
786863 }
864 // Every table counts toward the automatic style names, given only with `#+ATTR_ODT`.
865 tableCount += 1
787866 var style = "OrgTable"
788867 if attributeLine != nil {
789 style = "OrgTable\(tableStyles.count + 1)"
868 style = "OrgTable\(tableCount)"
790869 tableStyles.append((style, attributes["rel-width"] ?? "96"))
791870 }
792871 let firstRow = data.first.map { cells[$0] } ?? []
@@ -831,7 +910,8 @@ final class ODTRenderer {
831910 case "src":
832911 let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? ""
833912 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
834 let formatted = numbered(lines, Self.dedent(unescaped))
913 let language = parameters.split(whereSeparator: \.isWhitespace).first.map(String.init).flatMap { $0.hasPrefix("-") || $0.hasPrefix(":") ? nil : $0 }
914 let formatted = numbered(lines, Self.dedent(unescaped), fontified: language.map(ODTSourceModes.fontified) ?? true)
835915 if let textbox = attributes["textbox"], textbox != "nil" {
836916 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>"
837917 }
@@ -874,23 +954,31 @@ final class ODTRenderer {
874954 }
875955
876956 /// The code of a src or example block, labels and numbers as its switches ask.
877 private func numbered(_ block: [String], _ body: [String]) -> String {
957 private func numbered(_ block: [String], _ body: [String], fontified: Bool = true) -> String {
878958 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
879959 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
880960 let key = block.joined(separator: "\n")
881961 let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
882 return code(lines, refs: refs, retain: switches.retainLabels, loc: switches.numberLines == nil ? nil : loc)
962 return code(lines, refs: refs, retain: switches.retainLabels, loc: switches.numberLines == nil ? nil : loc, fontified: fontified)
883963 }
884964
885 /// `org-odt-do-format-code`: one paragraph per line, the last one styled apart.
886 private func code(_ lines: [String], refs: [Int: String] = [:], retain: Bool = false, loc: Int? = nil, emptyLast: Bool = false) -> String {
965 /// `org-odt-do-format-code`: one paragraph per line. From the line `org-split-string`
966 /// counts as the last, which leaves out a leading and a trailing empty line, the style is
967 /// the last line's. Without a mode for the language, no fontifying: another style and
968 /// spaces encoded as in text.
969 private func code(_ lines: [String], refs: [Int: String] = [:], retain: Bool = false, loc: Int? = nil, emptyLast: Bool = false, fontified: Bool = true) -> String {
887970 let lines = emptyLast ? lines + [""] : lines
971 let joined = lines.joined(separator: "\n")
972 let last = lines.count - (joined.hasPrefix("\n") ? 1 : 0) - (joined.hasSuffix("\n") ? 1 : 0)
973 let style = fontified ? "OrgSrcBlock" : "OrgFixedWidthBlock"
888974 let out = lines.enumerated().map { index, line -> String in
889975 var text = line
890976 if let ref = refs[index + 1], retain { text += " (\(ref))" }
891 var encoded = Self.escape(text, quotes: true).replacingOccurrences(of: " ", with: "<text:s/>").replacingOccurrences(of: "\t", with: "<text:tab/>")
977 var encoded = fontified
978 ? Self.escape(text, quotes: true).replacingOccurrences(of: " ", with: "<text:s/>").replacingOccurrences(of: "\t", with: "<text:tab/>")
979 : Self.encodeSpaces(Self.escape(text))
892980 if let ref = refs[index + 1] { encoded = Self.target(encoded, "coderef-" + ref) }
893 let paragraph = "\n<text:p text:style-name=\"OrgSrcBlock\(index == lines.count - 1 ? "LastLine" : "")\">\(encoded)</text:p>"
981 let paragraph = "\n<text:p text:style-name=\"\(style)\(last > 0 && index >= last - 1 ? "LastLine" : "")\">\(encoded)</text:p>"
894982 return loc == nil ? paragraph : "\n<text:list-item>\(paragraph)\n</text:list-item>"
895983 }.joined()
896984 guard let loc else { return out }
@@ -944,6 +1032,11 @@ final class ODTRenderer {
9441032 return file
9451033 }
9461034
1035 /// `org-export-insert-image-links`: the image a link's description shows, if it is one.
1036 static func describedImage(_ description: SyntaxNode) -> String? {
1037 filePath(description.text.trimmingCharacters(in: .whitespaces).replacing(/^\[\[(.*)\]\]$/) { String($0.1) }).flatMap { isImage($0) ? $0 : nil }
1038 }
1039
9471040 static func isImage(_ file: String) -> Bool {
9481041 file.range(of: "\\.(jpeg|jpg|png|gif|svg)", options: [.regularExpression, .caseInsensitive]) != nil
9491042 }
@@ -1003,6 +1096,8 @@ final class ODTRenderer {
10031096 afterFootnote = false
10041097 var out = ""
10051098 var text = ""
1099 // A line break object takes the newline after it, as Org's does.
1100 var afterBreak = false
10061101 for element in node.elements {
10071102 switch element {
10081103 case .token(let token):
@@ -1010,13 +1105,15 @@ final class ODTRenderer {
10101105 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
10111106 continue
10121107 default:
1013 text += token.text
1108 text += afterBreak && text.isEmpty && token.text.hasPrefix("\n") ? String(token.text.dropFirst()) : token.text
1109 afterBreak = false
10141110 }
10151111 case .node(let child):
10161112 if !text.isEmpty { afterFootnote = false }
10171113 out += plainText(text)
10181114 text = ""
10191115 out += object(child)
1116 afterBreak = child.kind == .lineBreak
10201117 }
10211118 }
10221119 if !text.isEmpty { afterFootnote = false }
@@ -1051,7 +1148,7 @@ final class ODTRenderer {
10511148 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
10521149 if options.tex { out += "<text:span text:style-name=\"OrgCode\">\(Self.escape(whole))</text:span>" }
10531150 } else if let name = group(5) {
1054 out += OrgEntities.display[name].map { Self.escape($0) } ?? plain(whole)
1151 out += withEntities ? OrgEntities.display[name].map { Self.escape($0) } ?? plain(whole) : plain(whole)
10551152 } else if let marker = group(7), let body = group(8) {
10561153 let braced = body.hasPrefix("{")
10571154 if options.scripts == .off || (options.scripts == .braces && !braced) {
@@ -1067,7 +1164,8 @@ final class ODTRenderer {
10671164 return out + plain(ns.substring(from: at))
10681165 }
10691166
1070 /// Escaped text with special strings, its line breaks as spaces outside verse.
1167 /// Escaped text with special strings, its line breaks as spaces outside verse, or as line
1168 /// breaks with `\\n`.
10711169 private func plain(_ text: String) -> String {
10721170 var out = Self.escape(text)
10731171 if options.specialStrings {
@@ -1076,7 +1174,9 @@ final class ODTRenderer {
10761174 .replacingOccurrences(of: "--([^-])", with: "&#x2013;$1", options: .regularExpression)
10771175 .replacingOccurrences(of: "...", with: "&#x2026;")
10781176 }
1079 return verse ? out : out.replacingOccurrences(of: "\n", with: " ")
1177 if verse { return out }
1178 if preserveBreaks { return out.replacingOccurrences(of: "[ \t]*\n", with: "<text:line-break/>", options: .regularExpression) }
1179 return out.replacingOccurrences(of: "\n", with: " ")
10801180 }
10811181
10821182 private func span(_ style: String, _ content: String) -> String {
@@ -1103,12 +1203,12 @@ final class ODTRenderer {
11031203 if text.hasPrefix("<%%") { return plain(text) }
11041204 return span(text.hasPrefix("<") ? "OrgActiveTimestamp" : "OrgInactiveTimestamp", plain(text))
11051205 case .footnoteReference:
1106 if tocEntry { return "" }
1206 if tocEntry || !withFootnotes { return "" }
11071207 let comma = afterFootnote ? span("OrgSuperscript", ",") : ""
1108 return comma + footnote(node.text)
1208 return comma + footnote(node)
11091209 case .entity:
11101210 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
1111 return OrgEntities.display[name].map { Self.escape($0) } ?? plain(node.text)
1211 return withEntities ? OrgEntities.display[name].map { Self.escape($0) } ?? plain(node.text) : plain(node.text)
11121212 case .radioTarget:
11131213 let inner = plain(String(node.text.dropFirst(3).dropLast(3)))
11141214 if tocEntry { return inner }
@@ -1166,35 +1266,91 @@ final class ODTRenderer {
11661266
11671267 // MARK: - Footnotes
11681268
1269 /// Numbers by footnote, a label or `@` and an anonymous reference's place, and the place
1270 /// of each one's first reference.
11691271 private var footnoteNumbers: [String: Int] = [:]
1170 private var anonymous = 0
1272 private var firstReferences: [String: Int] = [:]
1273
1274 /// The passes that number footnotes as ox-odt does, `org-export-get-footnote-number` with
1275 /// BODY-FIRST: the references in the body in order, then those in the definitions of
1276 /// these, each definition entered at its first reference.
1277 private enum FootnotePass { case body, definitions }
1278 private var footnotePass: FootnotePass?
1279 private var referencesMet: [(id: String, key: Int)] = []
1280 private var labelsSeen: Set<String> = []
1281 private var definitionsWaiting: [(label: String?, inline: (text: String, base: Int)?)] = []
1282
1283 private func numberFootnotes(_ text: String) {
1284 let pass = ODTRenderer(settings: settings, options: options, directory: directory)
1285 pass.language = language
1286 pass.author = author
1287 pass.dated = dated
1288 pass.numbered = numbered
1289 pass.preserveBreaks = preserveBreaks
1290 pass.withTables = withTables
1291 pass.withEntities = withEntities
1292 pass.drawers = drawers
1293 pass.footnotePass = .body
1294 _ = pass.document(text)
1295 pass.footnotePass = .definitions
1296 for waiting in pass.definitionsWaiting { _ = pass.definition(label: waiting.label, inline: waiting.inline) }
1297 for reference in pass.referencesMet where footnoteNumbers[reference.id] == nil {
1298 footnoteNumbers[reference.id] = footnoteNumbers.count + 1
1299 firstReferences[reference.id] = reference.key
1300 }
1301 definitions = pass.definitions
1302 }
1303
1304 /// A footnote's definition rendered: an anonymous one's own, else the label's.
1305 private func definition(label: String?, inline: (text: String, base: Int)?) -> String? {
1306 if label == nil, let inline { return inlineDefinition(inline.text, base: inline.base) }
1307 guard let label, let found = definitions[label] else { return nil }
1308 if found.inline { return inlineDefinition(found.text, base: found.base) }
1309 return blocks(found.text, base: found.base).trimmingCharacters(in: .whitespacesAndNewlines)
1310 }
1311
1312 private func inlineDefinition(_ text: String, base: Int) -> String {
1313 let rendered = within(text, base: base) { tree -> String in
1314 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
1315 return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
1316 }
1317 return "\n<text:p text:style-name=\"Footnote\">\(rendered)</text:p>"
1318 }
11711319
1172 private func footnote(_ text: String) -> String {
1320 private func footnote(_ node: SyntaxNode) -> String {
1321 let text = node.text
11731322 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return plain(text) }
1174 var label = String(m.1)
1175 let inlineText = m.2.map(String.init)
1176 if label.isEmpty {
1177 anonymous += 1
1178 label = "anonymous-\(anonymous)"
1323 let key = base + node.range.lowerBound
1324 let label = m.1.isEmpty ? nil : String(m.1)
1325 let id = label ?? "@\(key)"
1326 let inline = m.2.map { (text: String($0), base: key + text.utf16.distance(from: text.startIndex, to: $0.startIndex)) }
1327 if let label, let inline, definitions[label].map({ $0.base < inline.base }) ?? true {
1328 definitions[label] = (inline.text, inline.base, true)
1329 }
1330 if let pass = footnotePass {
1331 referencesMet.append((id, key))
1332 if let label, !labelsSeen.insert(label).inserted { return "" }
1333 if pass == .body {
1334 definitionsWaiting.append((label, inline))
1335 } else {
1336 _ = definition(label: label, inline: inline)
1337 }
1338 return ""
1339 }
1340 if footnoteNumbers[id] == nil {
1341 footnoteNumbers[id] = (footnoteNumbers.values.max() ?? 0) + 1
1342 firstReferences[id] = key
11791343 }
1180 if let n = footnoteNumbers[label] {
1344 let n = footnoteNumbers[id]!
1345 if label != nil, firstReferences[id] != key {
11811346 return span("OrgSuperscript", "<text:note-ref text:note-class=\"footnote\" text:reference-format=\"text\" text:ref-name=\"fn\(n)\">\(n)</text:note-ref>")
11821347 }
1183 let n = footnoteNumbers.count + 1
1184 footnoteNumbers[label] = n
11851348 let saved = (paragraphStyles, container, frames, afterFootnote)
11861349 paragraphStyles = ("Footnote", "OrgFootnoteCenter", "OrgFootnoteQuotations")
11871350 container = nil
11881351 frames = []
11891352 defer { (paragraphStyles, container, frames, afterFootnote) = saved }
1190 let definition: String
1191 if let inlineText {
1192 definition = "\n<text:p text:style-name=\"Footnote\">\(inlineString(inlineText))</text:p>"
1193 } else if let found = definitions[label] {
1194 definition = blocks(found.text, base: found.base).trimmingCharacters(in: .whitespacesAndNewlines)
1195 } else {
1196 return fail("Definition not found for footnote \(m.1)")
1197 }
1353 guard let definition = definition(label: label, inline: inline) else { return fail("Definition not found for footnote \(m.1)") }
11981354 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>"
11991355 }
12001356
@@ -1236,7 +1392,7 @@ final class ODTRenderer {
12361392 let descriptionNode = node.firstChild(.linkDescription)
12371393 var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 }
12381394 // `org-export-insert-image-links`: a description that is an image's path shows it.
1239 let describedImage = descriptionNode.flatMap { Self.filePath($0.text.trimmingCharacters(in: .whitespaces).replacing(/^\[\[(.*)\]\]$/) { String($0.1) }) }.flatMap { Self.isImage($0) ? $0 : nil }
1395 let describedImage = descriptionNode.flatMap(Self.describedImage)
12401396 if let describedImage, !tocEntry { description = image(describedImage) }
12411397 guard let path else {
12421398 // A radio link refers to its target.
Sources/OrgCore/Export/ODTSourceModes.swift added +90
@@ -0,0 +1,90 @@
1/// The names `NAME-mode` is a function for in `emacs -Q` (Emacs 31.1, Org 9.8.7, ox-odt
2/// loaded): the source block languages ox-odt fontifies, after `org-src-lang-modes`.
3enum ODTSourceModes {
4 static func fontified(_ language: String) -> Bool {
5 modes.contains(langModes[language] ?? language)
6 }
7
8 /// `org-src-lang-modes`.
9 static let langModes: [String: String] = [
10 "C": "c", "C++": "c++", "asymptote": "asy", "beamer": "latex", "calc": "fundamental", "cpp": "c++",
11 "ditaa": "artist", "desktop": "conf-desktop", "dot": "graphviz-dot", "elisp": "emacs-lisp",
12 "ocaml": "tuareg", "screen": "shell-script", "sqlite": "sql", "toml": "conf-toml", "shell": "sh",
13 "ash": "sh", "sh": "sh", "bash": "sh", "jsh": "sh", "bash2": "sh", "dash": "sh", "dtksh": "sh",
14 "ksh": "sh", "es": "sh", "rc": "sh", "itcsh": "sh", "tcsh": "sh", "jcsh": "sh", "csh": "sh",
15 "ksh88": "sh", "oash": "sh", "pdksh": "sh", "mksh": "sh", "posix": "sh", "wksh": "sh", "wsh": "sh",
16 "zsh": "sh", "rpm": "sh",
17 ]
18
19 static let modes: Set<String> = Set("""
20 *table--cell-describe Buffer-menu Buffer-menu-group-by Info LaTeX TeX abbrev add-minor allout
21 allout-widgets antlr antlr-v4 archive array artist asm authinfo auto-composition auto-compression
22 auto-encryption auto-fill auto-image-file auto-insert auto-lower auto-raise auto-revert
23 auto-revert-tail auto-save auto-save-visited autoconf awk bash-ts bat bibtex bibtex-style
24 binary-overwrite blink-cursor bovine-grammar buffer-face bug-reference bug-reference-prog button c
25 c++ c++-ts c-initialize-cc c-or-c++ c-or-c++-ts c-ts calendar capitalized-words center-line
26 cfengine-auto cfengine2 cfengine3 change-log checkdoc-minor cl-font-lock-built-in
27 cl-old-struct-compat clean cmake-ts column-number comint comint-fontify-input common-lisp compilation
28 compilation-minor compilation-shell-minor completion-in-region completion-list completion-preview
29 conf conf-colon conf-desktop conf-javaprop conf-npmrc conf-ppd conf-space conf-toml conf-unix
30 conf-windows conf-xdefaults context-menu cperl csharp csharp-ts css css-ts cua cua-rectangle-mark
31 cua-selection current-input cursor-face-highlight cursor-intangible cursor-sensor custom-group-of
32 custom-set-minor customize cvs-status cwarn dcl decipher delete-selection delete-selection-local
33 delete-trailing-whitespace delphi describe describe-minor desktop-save diary dictionary
34 dictionary-tooltip diff diff-minor dired dirtrack display-battery display-fill-column-indicator
35 display-line-numbers display-time dns doc-view doc-view-minor dockerfile-ts doctex double dsssl
36 dynamic-completion ebrowse-member ebrowse-tree edit-abbrevs editorconfig editorconfig-conf eldoc
37 electric-indent electric-indent-local electric-layout electric-layout-local electric-pair
38 electric-pair-local electric-quote electric-quote-local elide-head elisp-byte-code elixir-ts
39 emacs-authors emacs-lisp emacs-lock emacs-news emacs-news-view enriched epa-global-mail epa-mail erts
40 eshell etags-regen etc-authors eww f90 fido fido-vertical file-name-shadow find-function flymake
41 flyspell flyspell-prog follow font-lock font-lock-change font-lock-value-in-major footnote forms
42 fortran frame--current-background frame--current-backround frame-set-background
43 frame-terminal-default-bg fundamental gdb-script generic glasses global-auto-composition
44 global-auto-revert global-completion-preview global-cwarn global-dictionary-tooltip
45 global-display-fill-column-indicator global-display-line-numbers global-ede global-eldoc
46 global-font-lock global-goto-address global-hi-lock global-highlight-changes global-hl-line
47 global-prettify-symbols global-reveal global-so-long global-subword global-superword global-tab-line
48 global-visual-line global-visual-wrap-prefix global-whitespace global-whitespace-newline
49 global-window-tool-bar global-word-wrap-whitespace global-xref-mouse glyphless-display
50 gnus-mailing-list gnus-score go-mod-ts go-ts go-work-ts goto-address goto-address-prog gpm-mouse grep
51 gud-tooltip header-line-indent heex-ts help hexl hi-lock hide-ifdef highlight-changes
52 highlight-changes-visible hl-line hs-indentation hs-minor html html-ts icalendar icomplete
53 icomplete-vertical icon idl ido iimage image image-dired-minor image-minor indent-according-to
54 indent-tabs indented-text isearch isearch--describe-regexp isearch--describe-word isearch-describe
55 isearch-fold-quotes ispell-minor iswitchb java java-ts javascript jit-lock jit-lock-debug js js-base
56 js-json js-jsx js-ts json-ts kill-ring-deindent latex ld-script less-css line-number lisp lisp-data
57 lisp-interaction lock-file log-view lost-selection lua lua-ts m2 m4 mail mail-abbrevs makefile
58 makefile-automake makefile-bsdmake makefile-gmake makefile-imake makefile-makepp master menu-bar
59 menu-bar-display-line-numbers mercury message messages-buffer metafont metapost mh-folder mhtml
60 mhtml-ts midnight minibuffer minibuffer-depth-indicate minibuffer-electric-default
61 minibuffer-inactive minibuffer-nonselected minibuffer-regexp mixal mode-line-invisible modula-2
62 mouse-avoidance mouse-shift-adjust mouse-wheel msb next-error-follow-minor normal
63 normal-erase-is-backspace nroff nxml objc occur occur-edit octave octave-maybe opascal org org-agenda
64 org-agenda-archives org-agenda-clockreport org-agenda-entry-text org-agenda-follow org-agenda-log
65 org-babel-interpret-file org-beamer org-cdlatex org-check-for-org org-element--next org-export-stack
66 org-fontify-like-in-org org-indent org-list-checkbox-radio org-num org-run-like-in-org org-src
67 org-src-get-lang org-table-follow-field org-table-header-line orgtbl outline outline-minor overwrite
68 package-autosuggest paragraph-indent-minor paragraph-indent-text pascal pending-delete perl php-ts
69 picture pike pixel-scroll pixel-scroll-precision plain-TeX plain-tex plstore pr-toggle pr-txt
70 prettify-special-glyphs prettify-symbols process-menu prog prolog ps python python-base python-ts
71 rcirc-track-minor read-extended-command read-only recentf rectangle-mark refill reftex
72 reftex-index-phrases reftex-isearch-minor repeat reveal rmail rng-validate rst rst-minor ruby
73 ruby-base ruby-ts ruler rust-ts save-place save-place-local savehist scheme scroll-all scroll-lock
74 scss semantic server ses set-auto set-binary set-buffer-major set-input set-input-interrupt
75 set-input-meta sgml sh sh--redirect-bash-ts sh-base sh-electric-here-document shell-script show-paren
76 show-paren-local sieve simula size-indication slitex smerge snmp snmpv2 so-long so-long-minor special
77 speedbar-frame speedbar-window sql srecode-template srt strokes subword superword system-taskbar
78 tab-bar tab-bar-history tab-line tab-switcher table-fixed-width tabulated-list tags-table tar tcl
79 temp-buffer-resize tex texinfo text tildify todo todo-archive todo-filtered-items toggle-rot13
80 toggle-viper toml-ts tooltip tooltip-show-help-non transient-mark treesit--explorer-tree
81 treesit--read-major treesit-explore treesit-inspect tsx-ts tty-tip turn-off-follow
82 turn-on-auto-revert turn-on-auto-revert-tail turn-on-eldoc turn-on-follow turn-on-gnus-dired
83 turn-on-gnus-mailing-list turn-on-prettify-symbols turn-on-visual-line type-break typescript-ts
84 typescript-ts-base undelete-frame universal-argument- url-handler variable-pitch vc vc-auto-revert
85 vera verilog vhdl view viper visible visual-line visual-wrap-prefix wdired-change-to-wdired
86 which-function which-key which-key-show-full-major which-key-show-major whitespace whitespace-newline
87 whitespace-page-delimiters widget-minor windmove window-divider window-tool-bar winner wisent-grammar
88 word-wrap-whitespace xml xref-mouse xterm-mouse yaml-ts zone
89 """.split(whereSeparator: \.isWhitespace).map(String.init))
90}
Sources/OrgCore/Export/ODTTemplate.swift +9
@@ -55,6 +55,12 @@ enum ODTTemplate {
5555
5656 """
5757 }
58 styles += """
59 <style:style style:name="Sect1" style:family="section">
60 <style:section-properties style:editable="false"/>
61 </style:style>
62
63 """
5864 let sequences = ["Table", "Illustration", "Text", "Equation", "Listing"].map {
5965 "<text:sequence-decl text:display-outline-level=\"2\" text:name=\"\($0)\"/>"
6066 }.joined(separator: "\n")
@@ -151,6 +157,8 @@ enum ODTTemplate {
151157 styles += paragraph("OrgVerse", parent: "Text_20_body", "fo:margin-left=\"1cm\"")
152158 styles += paragraph("OrgSrcBlock", parent: "Standard", "fo:margin-top=\"0cm\" fo:margin-bottom=\"0cm\" fo:background-color=\"#f0f0f0\"", text: mono)
153159 styles += paragraph("OrgSrcBlockLastLine", parent: "OrgSrcBlock", "fo:margin-bottom=\"0.212cm\"")
160 styles += paragraph("OrgFixedWidthBlock", parent: "Standard", "fo:margin-top=\"0cm\" fo:margin-bottom=\"0cm\" fo:background-color=\"#f0f0f0\"", text: mono)
161 styles += paragraph("OrgFixedWidthBlockLastLine", parent: "OrgFixedWidthBlock", "fo:margin-bottom=\"0.212cm\"")
154162 styles += paragraph("Footnote", parent: "Standard", "fo:margin-left=\"0.5cm\" fo:text-indent=\"-0.5cm\"", text: "fo:font-size=\"10pt\"")
155163 styles += paragraph("OrgFootnoteCenter", parent: "Footnote", "fo:text-align=\"center\"")
156164 styles += paragraph("OrgFootnoteQuotations", parent: "Footnote", "fo:margin-left=\"1cm\" fo:margin-right=\"1cm\"")
@@ -178,6 +186,7 @@ enum ODTTemplate {
178186 styles += span("OrgTags", "fo:font-size=\"85%\"")
179187 styles += span("OrgTag", "fo:font-weight=\"bold\"")
180188 styles += span("OrgPriority", "fo:font-weight=\"bold\"")
189 for priority in ["A", "B", "C"] { styles += span("OrgPriority-\(priority)", "fo:font-weight=\"bold\"") }
181190 styles += span("OrgActiveTimestamp", "fo:color=\"#555555\"")
182191 styles += span("OrgInactiveTimestamp", "fo:color=\"#888888\"")
183192 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\"")
Tests/OrgCoreTests/ODTExportTests.swift +149 −9
@@ -5,13 +5,14 @@ import Testing
55@testable import OrgCore
66
77/// `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.
8/// their outline level, paragraphs, lists, sections, spans, tables and their rows and cells,
9/// links and images with their targets, notes and frames, the style names of these, and the
10/// text runs. `text:s` counts as spaces; tabs and line breaks are tokens of their own;
11/// references are numbered in order of appearance, since ox-odt's are random. The spans
12/// ox-odt colors source code with are left out: the export doesn't fontify.
1213enum ODTSkeleton {
1314 static let kept: Set<String> = [
14 "text:h", "text:p", "text:list", "text:list-item", "text:list-header", "text:section", "text:note",
15 "text:h", "text:p", "text:span", "text:list", "text:list-item", "text:list-header", "text:section", "text:note",
1516 "table:table", "table:table-header-rows", "table:table-rows", "table:table-row", "table:table-cell", "table:covered-table-cell",
1617 "text:a", "draw:a", "draw:frame", "draw:image", "draw:text-box", "text:table-of-content", "text:index-body",
1718 ]
@@ -22,6 +23,7 @@ enum ODTSkeleton {
2223 var lines: [String] = []
2324 var text = ""
2425 var references: [String: Int] = [:]
26 var spans: [Bool] = []
2527 func flush() {
2628 let collapsed = Skeleton.decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ")
2729 if !collapsed.isEmpty { lines.append("\"" + collapsed + "\"") }
@@ -45,18 +47,29 @@ enum ODTSkeleton {
4547 text += String(repeating: " ", count: count)
4648 continue
4749 case "text:tab", "text:line-break":
48 text += " "
50 flush()
51 lines.append("<\(name)/>")
4952 continue
5053 default:
5154 break
5255 }
5356 guard kept.contains(name) else { continue }
57 if name == "text:span", !tag.hasSuffix("/") {
58 if closing {
59 if spans.popLast() == false { continue }
60 } else {
61 let colored = tag.contains("text:style-name=\"OrgSrcFontLock")
62 spans.append(!colored)
63 if colored { continue }
64 }
65 }
5466 flush()
5567 if closing {
5668 lines.append("</\(name)>")
5769 continue
5870 }
5971 var attributes = ""
72 if let style = tag.firstMatch(of: /(?:text|table):style-name="([^"]*)"/) { attributes += " style=\(style.1)" }
6073 if let level = tag.firstMatch(of: /text:outline-level="([0-9]+)"/) { attributes += " level=\(level.1)" }
6174 if let href = tag.firstMatch(of: /xlink:href="([^"]*)"/) {
6275 var value = String(href.1)
@@ -351,6 +364,101 @@ struct ODTExportTests {
351364 Text -- here a_b and a_{b} and \\(x\\).
352365 * Second
353366 """,
367 "deep-headings": """
368 #+OPTIONS: toc:nil
369 * One
370 ** Two
371 *** Three
372 **** Four
373 See [[Four]].
374 **** Five
375 """,
376 "num-past-h": """
377 #+OPTIONS: toc:nil num:3 H:1
378 * A
379 ** B
380 *** C
381 **** D
382 """,
383 "nested-footnotes": """
384 #+OPTIONS: toc:nil
385 A[fn:1] B[fn:2] C[fn:4].
386
387 [fn:1] One[fn:3][fn:4].
388
389 [fn:2] Two.
390
391 [fn:3] Three.
392
393 [fn:4] Four.
394 """,
395 "inline-footnotes": """
396 #+OPTIONS: toc:nil
397 First[fn:x] then[fn:x: inline /def/] and an anonymous[fn:: one[fn:y]] note.
398
399 [fn:y] Nested in an anonymous one.
400 """,
401 "tocs": """
402 #+OPTIONS: toc:nil
403 * Top
404 #+TOC: headlines 1 local
405 ** Child A
406 ** DONE Child B
407 *** Grand
408 * Appendix
409 :PROPERTIES:
410 :UNNUMBERED: notoc
411 :END:
412 ** Inside appendix
413 *** Deeper
414 :PROPERTIES:
415 :UNNUMBERED: nil
416 :END:
417 * Last
418 #+TOC: headlines 5
419 """,
420 "cookie-header": """
421 #+OPTIONS: toc:nil
422 | <r> | <l> |
423 |-----+-----|
424 | a | b |
425 """,
426 "preserve-breaks": """
427 #+OPTIONS: toc:nil \\n:t
428 Line one
429 line two.
430
431 Ends with a break\\\\
432 next line\\\\
433 """,
434 "no-footnotes-tables-entities": """
435 #+OPTIONS: toc:nil f:nil |:nil e:nil
436 Text[fn:1] with \\alpha and \\beta{} here.
437
438 #+CAPTION: Dropped
439 | a | b |
440
441 - item
442 | c |
443
444 [fn:1] Note.
445 """,
446 "no-drawers": """
447 #+OPTIONS: toc:nil d:nil
448 * H
449 :NOTES:
450 Hidden.
451 :END:
452 Shown.
453 """,
454 "all-drawers": """
455 #+OPTIONS: toc:nil d:t
456 * H
457 :LOGBOOK:
458 - Note taken on [2024-01-01 Mon 10:00]
459 :END:
460 Shown.
461 """,
354462 ]
355463
356464 /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the
@@ -491,13 +599,45 @@ struct ODTExportTests {
491599 "Code src_python[:exports code]{1 + 1} here.\n",
492600 "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n",
493601 "- a quote\n #+begin_quote\n | q |\n #+end_quote\n",
602 "#+OPTIONS: p:t\n* H\nSCHEDULED: <2024-01-01 Mon>\n",
603 "#+OPTIONS: broken-links:t\nSee [[nowhere]].\n",
604 "#+OPTIONS: c:t\n* H\nCLOCK: [2024-01-01 Mon 10:00]--[2024-01-01 Mon 11:00] => 1:00\n",
605 "#+OPTIONS: prop:t\n* H\n:PROPERTIES:\n:A: 1\n:END:\n",
606 "#+OPTIONS: ::nil\n: fixed\n",
607 "#+OPTIONS: *:nil\n*bold*\n",
608 "#+OPTIONS: stat:nil\n* H [1/2]\n",
609 "#+OPTIONS: tasks:nil\n* TODO H\n",
610 "#+OPTIONS: <:nil\n<2024-01-01 Mon>\n",
611 "#+OPTIONS: arch:nil\n* H :ARCHIVE:\nBody.\n",
612 "#+OPTIONS: email:t\n#+EMAIL: a@b.c\nText.\n",
613 "#+OPTIONS: ':t\n\"quoted\"\n",
614 "#+OPTIONS: tex:verbatim\n\\(x\\)\n",
615 "#+OPTIONS: d:(\"NOTES\")\n:NOTES:\nx\n:END:\n",
494616 ])
495617 func refuses(_ text: String) {
496618 #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") }
497619 }
498620
499 @Test func imageFiles() {
500 let files = ODTExport.imageFiles("[[file:a.png]] [[./b.jpg][desc]] [[https://x/c.png]] [[/abs/d.svg]]\n", path: "/doc/notes.org")
501 #expect(files == ["/doc/a.png", "/abs/d.svg"])
621 @Test func imageFiles() throws {
622 let files = ODTExport.imageFiles("[[file:a.png]] [[./b.jpg][desc]] [[https://x/c.png]] [[/abs/d.svg]] [[https://x][file:e.png]]\n", path: "/doc/notes.org")
623 #expect(files == ["/doc/a.png", "/abs/d.svg", "/doc/e.png"])
624 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
625 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
626 defer { try? FileManager.default.removeItem(at: folder) }
627 try "[[file:/elsewhere/f.png]]\n".write(to: folder.appendingPathComponent("part.org"), atomically: true, encoding: .utf8)
628 #expect(ODTExport.imageFiles("#+INCLUDE: \"part.org\"\n", path: folder.appendingPathComponent("doc.org").path) == ["/elsewhere/f.png"])
629 }
630
631 /// Every style `content.xml` names is in `styles.xml` or its automatic styles.
632 @Test func stylesDefined() throws {
633 let text = "#+OPTIONS: pri:t\n* TODO [#A] One\n* [#B] Two\n* DONE [#C] Three\n"
634 let parts = try ODTExport.parts(text, path: "/tmp/doc.org")
635 let content = String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
636 let styles = String(decoding: parts.first { $0.name == "styles.xml" }!.data, as: UTF8.self)
637 let used = Set(content.matches(of: /text:style-name="([^"]+)"/).map { String($0.1) })
638 #expect(used.isSuperset(of: ["OrgPriority-A", "OrgPriority-B", "OrgPriority-C"]))
639 for name in used {
640 #expect(styles.contains("style:name=\"\(name)\"") || content.contains("style:name=\"\(name)\""), "\(name)")
641 }
502642 }
503643}
docs/manual/guide/12-export.org +5 −4
@@ -253,15 +253,16 @@ For Org's own ASCII layout, with underlined headings and drawn tables, use Expor
253253Export to ODT writes an OpenDocument text file (=.odt=) for LibreOffice, Pages or Word. orgstar writes it itself, on the Mac and on iOS, the way Emacs's =ox-odt= does under =emacs -Q=: the same headings, paragraphs, lists, tables, links, notes and images, with ox-odt's style names, so a template that restyles ox-odt's output restyles this one too.
254254
255255- The title, subtitle (=#+SUBTITLE:=), author and date come first, then the table of contents and the text. On the Mac, without =#+AUTHOR:=, the author is your account's full name, as =user-full-name= is in Emacs. Without =#+TITLE:= there is no title.
256- Headings are numbered by the word processor, to the depth =num= gives. Headings deeper than =H= become list items. =#+TOC: headlines= puts a table of contents where it is; =local= limits it to the section.
257- Footnotes are the word processor's own notes. A note referred to again shows its number.
256- Headings are numbered by the word processor, to the depth =num= gives (=num:t= numbers every level). Headings deeper than =H= become list items. =#+TOC: headlines= puts a table of contents where it is; =local= limits it to the section and counts the depth from there.
257- Footnotes are the word processor's own notes, numbered as ox-odt numbers them: those referred to in the text first, then those referred to only from other notes. A note referred to again shows its number.
258258- Tables keep their header rows, alignment cookies, column groups and cell borders. A table inside a list item ends the list, sits indented below it, and the list carries on after it, as in ox-odt.
259259- Images from =file:= links (PNG, JPEG, GIF and SVG) are put inside the file. Their size is their pixels at 96 to the inch, or =#+ATTR_ODT: :width=, =:length= (the height) or =:scale=, and no more than 17 by 20 cm. A caption or =#+NAME:= numbers figures, tables and source blocks, and a link to the name shows the number.
260- LaTeX fragments and environments are kept as written, in code style, as ox-odt does without a MathML converter. Source blocks are not colored.
260- LaTeX fragments and environments are kept as written, in code style, as ox-odt does without a MathML converter. Source blocks are not colored; a language Emacs has no mode for gets ox-odt's plain code style.
261- Of the =#+OPTIONS=, =\n=, =f=, =|=, =e= and =d= (=t= or =nil=) are read, along with those every export reads.
261262- =#+ODT:= lines, =#+BEGIN_EXPORT odt= blocks and =@@odt:...@@= snippets go in as they are.
262263- The styles (=styles.xml=) are orgstar's own: A4 pages with 2 cm margins. =#+ODT_STYLES_FILE:= is not read.
263264
264The export stops with a message, instead of writing something different from ox-odt, for: a link that leads nowhere, an image file that can't be read, inline tasks, table templates (=#+ATTR_ODT: :style=), a link without a description to a =<<target>>= or to a code line that isn't numbered, an inline source block exported as code, a table in a quote or other block inside a list, an annotation in a dated document, and =#+TOC:= with =:target=. ODT export is always the whole document: the export dialog's *Body only* doesn't apply.
265The export stops with a message, instead of writing something different from ox-odt, for: a link that leads nowhere, an image file that can't be read, inline tasks, table templates (=#+ATTR_ODT: :style=), a link without a description to a =<<target>>= or to a code line that isn't numbered, an inline source block exported as code, a table in a quote or other block inside a list, an annotation in a dated document, =#+TOC:= with =:target=, and these =#+OPTIONS= at other than their default: =p=, =c=, =prop=, =broken-links=, =:=, =*=, =stat=, =tasks=, =<=, =arch=, =email=, ='=, =tex= other than =t= or =nil=, and =d= with a list of drawers. ODT export is always the whole document: the export dialog's *Body only* doesn't apply.
265266
266267* Markdown export
267268