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 {
27 } 27 }
28 28
29 /// The image files `text` embeds, for the sandbox to reach before exporting. 29 /// The image files `text` embeds, for the sandbox to reach before exporting.
30 /// Images in `#+INCLUDE`d files and images shown as a link's description count.
30 public static func imageFiles(_ text: String, settings: OrgSettings = .default, path: String) -> [String] { 31 public static func imageFiles(_ text: String, settings: OrgSettings = .default, path: String) -> [String] {
31 let directory = URL(fileURLWithPath: path).deletingLastPathComponent() 32 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
33 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, setup: settings.setupKeywords)
32 return OrgParser.parse(text, defaults: settings).root.descendants().compactMap { node in 34 return OrgParser.parse(text, defaults: settings).root.descendants().compactMap { node in
33 guard node.kind == .link, node.firstChild(.linkDescription) == nil, 35 guard node.kind == .link else { return nil }
34 let file = ODTRenderer.filePath(node.tokens.first { $0.kind == .linkPath }?.text ?? ""), ODTRenderer.isImage(file) else { return nil } 36 let file: String?
35 return ODTRenderer.expand(file, directory: directory).path 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 }
36 } 43 }
37 } 44 }
38 45
@@ -46,6 +53,7 @@ public enum ODTExport {
46 let meta = HTMLExport.metadata(text, settings: settings) 53 let meta = HTMLExport.metadata(text, settings: settings)
47 let keywords = Self.keywords(text, settings: settings) 54 let keywords = Self.keywords(text, settings: settings)
48 let renderer = ODTRenderer(settings: settings, options: options, directory: directory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)) 55 let renderer = ODTRenderer(settings: settings, options: options, directory: directory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath))
56 try Self.read(settings.setupKeywords + text, into: renderer)
49 renderer.language = meta.language ?? language 57 renderer.language = meta.language ?? language
50 58
51 // The title isn't part of the document Org processes citations in: they drop out. 59 // The title isn't part of the document Org processes citations in: they drop out.
@@ -88,13 +96,49 @@ public enum ODTExport {
88 96
89 var parts: [(name: String, data: Data)] = [("mimetype", Data(ODTTemplate.mimetype.utf8))] 97 var parts: [(name: String, data: Data)] = [("mimetype", Data(ODTTemplate.mimetype.utf8))]
90 parts.append(("content.xml", Data(contents.utf8))) 98 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)))
92 parts.append(("meta.xml", Data(metaXML.utf8))) 100 parts.append(("meta.xml", Data(metaXML.utf8)))
93 parts += renderer.images.map { ($0.name, $0.data) } 101 parts += renderer.images.map { ($0.name, $0.data) }
94 parts.append(("META-INF/manifest.xml", Data(ODTTemplate.manifest(images: renderer.images.map(\.name)).utf8))) 102 parts.append(("META-INF/manifest.xml", Data(ODTTemplate.manifest(images: renderer.images.map(\.name)).utf8)))
95 return parts 103 return parts
96 } 104 }
97 105
106 /// The `#+OPTIONS` items ox-odt reads that `ExportOptions` doesn't, or reads differently:
107 /// `num` to any depth, `\\n`, `f`, `|`, `e` and `d` honored; other items at a value other
108 /// than their default stop the export.
109 static func read(_ text: String, into renderer: ODTRenderer) throws {
110 var items: [String: String] = [:]
111 for line in text.matches(of: #/(?mi)^[ \t]*#\+OPTIONS:[ \t]*(.*?)[ \t]*$/#) {
112 for item in line.1.matches(of: /(\S+?):(\S+)/) { items[String(item.1)] = String(item.2) }
113 }
114 let defaults = [
115 "p": "nil", "broken-links": "nil", "c": "nil", "prop": "nil", ":": "t", "*": "t", "stat": "t",
116 "tasks": "t", "<": "t", "arch": "headline", "email": "nil", "'": "nil",
117 ]
118 for (key, value) in items.sorted(by: { $0.key < $1.key }) {
119 if let standard = defaults[key], value != standard {
120 throw Failure(message: "ODT export doesn't support #+OPTIONS: \(key):\(value)")
121 }
122 }
123 if let tex = items["tex"], tex != "t", tex != "nil" { throw Failure(message: "ODT export doesn't support #+OPTIONS: tex:\(tex)") }
124 switch items["d"] {
125 case nil: renderer.drawers = nil
126 case "nil": renderer.drawers = false
127 case "t": renderer.drawers = true
128 case let value?: throw Failure(message: "ODT export doesn't support #+OPTIONS: d:\(value)")
129 }
130 // `org-export-numbered-headline-p`: `t` numbers every level, `N` levels to N, past `H`.
131 switch items["num"] {
132 case "nil": renderer.numbered = nil
133 case let value?: renderer.numbered = Int(value) ?? Int.max
134 case nil: renderer.numbered = Int.max
135 }
136 renderer.preserveBreaks = items["\\n"].map { $0 != "nil" } ?? false
137 renderer.withFootnotes = items["f"] != "nil"
138 renderer.withTables = items["|"] != "nil"
139 renderer.withEntities = items["e"] != "nil"
140 }
141
98 /// `#+SUBTITLE`, `#+KEYWORDS` and `#+DESCRIPTION`: lines of the same keyword joined. 142 /// `#+SUBTITLE`, `#+KEYWORDS` and `#+DESCRIPTION`: lines of the same keyword joined.
99 static func keywords(_ text: String, settings: OrgSettings) -> [String: String] { 143 static func keywords(_ text: String, settings: OrgSettings) -> [String: String] {
100 let tree = OrgParser.parse(text, defaults: settings) 144 let tree = OrgParser.parse(text, defaults: settings)
@@ -132,6 +176,16 @@ final class ODTRenderer {
132 private(set) var failure: ODTExport.Failure? 176 private(set) var failure: ODTExport.Failure?
133 private(set) var images: [(name: String, data: Data)] = [] 177 private(set) var images: [(name: String, data: Data)] = []
134 178
179 /// `num`: headings numbered to this relative level, `Int.max` for all; nil for none.
180 var numbered: Int? = Int.max
181 /// `\\n`, `f`, `|` and `e`.
182 var preserveBreaks = false
183 var withFootnotes = true
184 var withTables = true
185 var withEntities = true
186 /// `d`: nil for every drawer but `LOGBOOK`, true for every drawer, false for none.
187 var drawers: Bool?
188
135 init(settings: OrgSettings, options: ExportOptions, directory: URL) { 189 init(settings: OrgSettings, options: ExportOptions, directory: URL) {
136 self.settings = settings 190 self.settings = settings
137 self.options = options 191 self.options = options
@@ -176,7 +230,8 @@ final class ODTRenderer {
176 private var selected: Set<Int>? 230 private var selected: Set<Int>?
177 private var documentTree: OrgTree? 231 private var documentTree: OrgTree?
178 private var blockLocs: [String: [Int?]] = [:] 232 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)] = [:]
180 235
181 /// Where the tree being read starts in the document, so elements read from a block's or a 236 /// 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. 237 /// footnote's contents keep their place; how deep in such contents it is.
@@ -204,11 +259,8 @@ final class ODTRenderer {
204 heading.relative = heading.level - top + 1 259 heading.relative = heading.level - top + 1
205 heading.lowLevel = heading.relative > options.headlineLevels 260 heading.lowLevel = heading.relative > options.headlineLevels
206 heading.reference = newReference() 261 heading.reference = newReference()
207 let unnumbered = (heading.ancestors + [key]).contains { key in 262 let unnumbered = unnumberedValue(heading).map { $0 != "nil" } ?? false
208 guard let value = headings[key]?.info?.properties.last(where: { $0.key.uppercased() == "UNNUMBERED" })?.value else { return false } 263 if let numbered, heading.relative <= numbered, !unnumbered {
209 return value.trimmingCharacters(in: .whitespaces) != "nil"
210 }
211 if let num = options.num, heading.relative <= num, !unnumbered {
212 let index = heading.relative - 1 264 let index = heading.relative - 1
213 if counters.count <= index { counters += Array(repeating: 0, count: index + 1 - counters.count) } 265 if counters.count <= index { counters += Array(repeating: 0, count: index + 1 - counters.count) }
214 counters[index] += 1 266 counters[index] += 1
@@ -229,6 +281,16 @@ final class ODTRenderer {
229 } 281 }
230 } 282 }
231 283
284 /// `UNNUMBERED` of the heading or its closest ancestor that has it.
285 private func unnumberedValue(_ heading: Heading) -> String? {
286 for key in [heading.key] + heading.ancestors.reversed() {
287 if let value = headings[key]?.info?.properties.last(where: { $0.key.uppercased() == "UNNUMBERED" })?.value {
288 return value.trimmingCharacters(in: .whitespaces)
289 }
290 }
291 return nil
292 }
293
232 private func collect(_ node: SyntaxNode, ancestors: [Int], infos: [Int: HeadingInfo]) { 294 private func collect(_ node: SyntaxNode, ancestors: [Int], infos: [Int: HeadingInfo]) {
233 var affiliated: [String: String] = [:] 295 var affiliated: [String: String] = [:]
234 for child in node.children { 296 for child in node.children {
@@ -260,6 +322,7 @@ final class ODTRenderer {
260 let inner = child.kind == .target ? child.text.dropFirst(2).dropLast(2) : child.text.dropFirst(3).dropLast(3) 322 let inner = child.kind == .target ? child.text.dropFirst(2).dropLast(2) : child.text.dropFirst(3).dropLast(3)
261 targets.append((Self.words(inner.uppercased()), key, newReference())) 323 targets.append((Self.words(inner.uppercased()), key, newReference()))
262 case .table: 324 case .table:
325 guard withTables else { continue }
263 if captioned { enumerables.append((key, "Table", ancestors)) } 326 if captioned { enumerables.append((key, "Table", ancestors)) }
264 collect(child, ancestors: ancestors, infos: infos) 327 collect(child, ancestors: ancestors, infos: infos)
265 case .paragraph: 328 case .paragraph:
@@ -271,7 +334,7 @@ final class ODTRenderer {
271 if ["src", "example", "export", "comment", "verse"].contains(type) { continue } 334 if ["src", "example", "export", "comment", "verse"].contains(type) { continue }
272 within(body.text, base: key + body.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) } 335 within(body.text, base: key + body.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
273 case .drawer, .dynamicBlock: 336 case .drawer, .dynamicBlock:
274 guard let inner = Self.inner(child) else { continue } 337 guard let inner = inner(child) else { continue }
275 within(inner.text, base: key + inner.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) } 338 within(inner.text, base: key + inner.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
276 default: 339 default:
277 collect(child, ancestors: ancestors, infos: infos) 340 collect(child, ancestors: ancestors, infos: infos)
@@ -279,13 +342,13 @@ final class ODTRenderer {
279 } 342 }
280 } 343 }
281 344
282 /// A drawer's or dynamic block's contents and their offset in it; nil for `LOGBOOK`, which 345 /// A drawer's or dynamic block's contents and their offset in it; nil for a drawer `d`
283 /// isn't exported. 346 /// leaves out.
284 static func inner(_ node: SyntaxNode) -> (text: String, offset: Int)? { 347 private func inner(_ node: SyntaxNode) -> (text: String, offset: Int)? {
285 var lines = node.text.components(separatedBy: "\n") 348 var lines = node.text.components(separatedBy: "\n")
286 if lines.last == "" { lines.removeLast() } 349 if lines.last == "" { lines.removeLast() }
287 guard let first = lines.first else { return nil } 350 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 }
289 return (lines.dropFirst().dropLast().joined(separator: "\n"), first.utf16.count + 1) 352 return (lines.dropFirst().dropLast().joined(separator: "\n"), first.utf16.count + 1)
290 } 353 }
291 354
@@ -333,10 +396,11 @@ final class ODTRenderer {
333 end = sibling.range.upperBound 396 end = sibling.range.upperBound
334 } 397 }
335 } 398 }
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)
337 } 400 }
338 selected = HTMLRenderer.selection(tree, tags: options.selectTags) 401 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
339 collect(tree) 402 collect(tree)
403 if footnotePass == nil, withFootnotes { numberFootnotes(text) }
340 return rendering(tree, text) { tree.root.children.map(element).joined() } 404 return rendering(tree, text) { tree.root.children.map(element).joined() }
341 } 405 }
342 406
@@ -357,14 +421,19 @@ final class ODTRenderer {
357 /// `org-odt-toc` for the whole document: headings to `toc`, or nothing. 421 /// `org-odt-toc` for the whole document: headings to `toc`, or nothing.
358 func tableOfContents() -> String { 422 func tableOfContents() -> String {
359 guard let depth = options.toc else { return "" } 423 guard let depth = options.toc else { return "" }
360 return toc(depth: depth, scope: nil) 424 return toc(depth: depth, scope: nil, template: true)
361 } 425 }
362 426
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)
364 let keys = headingOrder.filter { key in 433 let keys = headingOrder.filter { key in
365 let heading = headings[key]! 434 let heading = headings[key]!
366 let notoc = heading.info?.properties.last { $0.key.uppercased() == "UNNUMBERED" }?.value.trimmingCharacters(in: .whitespaces) == "notoc" 435 let excluded = heading.lowLevel || unnumberedValue(heading) == "notoc" || options.toc.map { heading.relative > $0 } ?? false
367 return heading.relative <= depth && !notoc && (scope.map { heading.ancestors.contains($0) } ?? true) 436 return heading.relative <= limit && !excluded && (scope.map { heading.ancestors.contains($0) } ?? true)
368 } 437 }
369 guard !keys.isEmpty else { return "" } 438 guard !keys.isEmpty else { return "" }
370 let title = scope == nil ? ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8) : nil 439 let title = scope == nil ? ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8) : nil
@@ -392,7 +461,7 @@ final class ODTRenderer {
392 let heading = headings[key]! 461 let heading = headings[key]!
393 var entry = heading.number.map { $0.map(String.init).joined(separator: ".") + ". " } ?? "" 462 var entry = heading.number.map { $0.map(String.init).joined(separator: ".") + ". " } ?? ""
394 let parts = headlineParts(heading.node) 463 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> " }
396 if let priority = parts.priority { entry += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " } 465 if let priority = parts.priority { entry += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
397 entry += parts.title 466 entry += parts.title
398 if options.tagsInTOC, !parts.tags.isEmpty { entry += " " + tagsSpan(parts.tags) } 467 if options.tagsInTOC, !parts.tags.isEmpty { entry += " " + tagsSpan(parts.tags) }
@@ -446,13 +515,13 @@ final class ODTRenderer {
446 case .plainList: 515 case .plainList:
447 return list(node) 516 return list(node)
448 case .table: 517 case .table:
449 return table(node) 518 return withTables ? table(node) : ""
450 case .block: 519 case .block:
451 return block(node) 520 return block(node)
452 case .horizontalRule: 521 case .horizontalRule:
453 return "\n<text:p text:style-name=\"Horizontal_20_Line\"></text:p>" 522 return "\n<text:p text:style-name=\"Horizontal_20_Line\"></text:p>"
454 case .drawer, .dynamicBlock: 523 case .drawer, .dynamicBlock:
455 guard let inner = Self.inner(node) else { return "" } 524 guard let inner = inner(node) else { return "" }
456 return blocks(inner.text, base: base + node.range.lowerBound + inner.offset) 525 return blocks(inner.text, base: base + node.range.lowerBound + inner.offset)
457 case .inlineTask: 526 case .inlineTask:
458 // `emacs -Q` doesn't load org-inlinetask, so ox-odt reads them as headings. 527 // `emacs -Q` doesn't load org-inlinetask, so ox-odt reads them as headings.
@@ -469,7 +538,7 @@ final class ODTRenderer {
469 return code(lines) 538 return code(lines)
470 case .tableEl: 539 case .tableEl:
471 // ox-odt strips table.el tables, the list around them closed and opened again. 540 // 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)
473 default: 542 default:
474 // Comments, property drawers, planning, clocks, footnote definitions, formulas. 543 // Comments, property drawers, planning, clocks, footnote definitions, formulas.
475 return "" 544 return ""
@@ -555,7 +624,13 @@ final class ODTRenderer {
555 imageCaption = affiliated["CAPTION"] 624 imageCaption = affiliated["CAPTION"]
556 imageAttributes = affiliated["ATTR_ODT"] 625 imageAttributes = affiliated["ATTR_ODT"]
557 defer { imageKey = nil; imageCaptioned = false; imageCaption = nil; imageAttributes = nil } 626 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>"
559 } 634 }
560 635
561 /// The link of a paragraph that is only an image link. 636 /// The link of a paragraph that is only an image link.
@@ -695,6 +770,7 @@ final class ODTRenderer {
695 // MARK: - Tables 770 // MARK: - Tables
696 771
697 private var tableStyles: [(name: String, width: String)] = [] 772 private var tableStyles: [(name: String, width: String)] = []
773 private var tableCount = 0
698 774
699 private func table(_ node: SyntaxNode) -> String { 775 private func table(_ node: SyntaxNode) -> String {
700 let attributeLine = affiliated["ATTR_ODT"] 776 let attributeLine = affiliated["ATTR_ODT"]
@@ -756,10 +832,11 @@ final class ODTRenderer {
756 if kinds[r] == .rule, seen { current += 1; seen = false } 832 if kinds[r] == .rule, seen { current += 1; seen = false }
757 if kinds[r] == .data { group[r] = current; seen = true } 833 if kinds[r] == .data { group[r] = current; seen = true }
758 } 834 }
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
760 let hasHeader = firstData.map { start in 837 let hasHeader = firstData.map { start in
761 guard let rule = rows.indices.first(where: { $0 > start && kinds[$0] == .rule }) else { return false } 838 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 }
763 } ?? false 840 } ?? false
764 let headerColumns = attributes["header-columns"].map { Int($0) ?? 1 } ?? 0 841 let headerColumns = attributes["header-columns"].map { Int($0) ?? 1 } ?? 0
765 var body = "" 842 var body = ""
@@ -784,9 +861,11 @@ final class ODTRenderer {
784 body += "\n<table:table-row>\n\(row)\n</table:table-row>" 861 body += "\n<table:table-row>\n\(row)\n</table:table-row>"
785 if ends { body += header ? "\n</table:table-header-rows>" : "\n</table:table-rows>" } 862 if ends { body += header ? "\n</table:table-header-rows>" : "\n</table:table-rows>" }
786 } 863 }
864 // Every table counts toward the automatic style names, given only with `#+ATTR_ODT`.
865 tableCount += 1
787 var style = "OrgTable" 866 var style = "OrgTable"
788 if attributeLine != nil { 867 if attributeLine != nil {
789 style = "OrgTable\(tableStyles.count + 1)" 868 style = "OrgTable\(tableCount)"
790 tableStyles.append((style, attributes["rel-width"] ?? "96")) 869 tableStyles.append((style, attributes["rel-width"] ?? "96"))
791 } 870 }
792 let firstRow = data.first.map { cells[$0] } ?? [] 871 let firstRow = data.first.map { cells[$0] } ?? []
@@ -831,7 +910,8 @@ final class ODTRenderer {
831 case "src": 910 case "src":
832 let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? "" 911 let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? ""
833 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:] 912 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)
835 if let textbox = attributes["textbox"], textbox != "nil" { 915 if let textbox = attributes["textbox"], textbox != "nil" {
836 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>" 916 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>"
837 } 917 }
@@ -874,23 +954,31 @@ final class ODTRenderer {
874 } 954 }
875 955
876 /// The code of a src or example block, labels and numbers as its switches ask. 956 /// 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 {
878 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil) 958 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
879 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat) 959 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
880 let key = block.joined(separator: "\n") 960 let key = block.joined(separator: "\n")
881 let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil 961 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)
883 } 963 }
884 964
885 /// `org-odt-do-format-code`: one paragraph per line, the last one styled apart. 965 /// `org-odt-do-format-code`: one paragraph per line. From the line `org-split-string`
886 private func code(_ lines: [String], refs: [Int: String] = [:], retain: Bool = false, loc: Int? = nil, emptyLast: Bool = false) -> 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 {
887 let lines = emptyLast ? lines + [""] : lines 970 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"
888 let out = lines.enumerated().map { index, line -> String in 974 let out = lines.enumerated().map { index, line -> String in
889 var text = line 975 var text = line
890 if let ref = refs[index + 1], retain { text += " (\(ref))" } 976 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))
892 if let ref = refs[index + 1] { encoded = Self.target(encoded, "coderef-" + ref) } 980 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>"
894 return loc == nil ? paragraph : "\n<text:list-item>\(paragraph)\n</text:list-item>" 982 return loc == nil ? paragraph : "\n<text:list-item>\(paragraph)\n</text:list-item>"
895 }.joined() 983 }.joined()
896 guard let loc else { return out } 984 guard let loc else { return out }
@@ -944,6 +1032,11 @@ final class ODTRenderer {
944 return file 1032 return file
945 } 1033 }
946 1034
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
947 static func isImage(_ file: String) -> Bool { 1040 static func isImage(_ file: String) -> Bool {
948 file.range(of: "\\.(jpeg|jpg|png|gif|svg)", options: [.regularExpression, .caseInsensitive]) != nil 1041 file.range(of: "\\.(jpeg|jpg|png|gif|svg)", options: [.regularExpression, .caseInsensitive]) != nil
949 } 1042 }
@@ -1003,6 +1096,8 @@ final class ODTRenderer {
1003 afterFootnote = false 1096 afterFootnote = false
1004 var out = "" 1097 var out = ""
1005 var text = "" 1098 var text = ""
1099 // A line break object takes the newline after it, as Org's does.
1100 var afterBreak = false
1006 for element in node.elements { 1101 for element in node.elements {
1007 switch element { 1102 switch element {
1008 case .token(let token): 1103 case .token(let token):
@@ -1010,13 +1105,15 @@ final class ODTRenderer {
1010 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter: 1105 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1011 continue 1106 continue
1012 default: 1107 default:
1013 text += token.text 1108 text += afterBreak && text.isEmpty && token.text.hasPrefix("\n") ? String(token.text.dropFirst()) : token.text
1109 afterBreak = false
1014 } 1110 }
1015 case .node(let child): 1111 case .node(let child):
1016 if !text.isEmpty { afterFootnote = false } 1112 if !text.isEmpty { afterFootnote = false }
1017 out += plainText(text) 1113 out += plainText(text)
1018 text = "" 1114 text = ""
1019 out += object(child) 1115 out += object(child)
1116 afterBreak = child.kind == .lineBreak
1020 } 1117 }
1021 } 1118 }
1022 if !text.isEmpty { afterFootnote = false } 1119 if !text.isEmpty { afterFootnote = false }
@@ -1051,7 +1148,7 @@ final class ODTRenderer {
1051 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil { 1148 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
1052 if options.tex { out += "<text:span text:style-name=\"OrgCode\">\(Self.escape(whole))</text:span>" } 1149 if options.tex { out += "<text:span text:style-name=\"OrgCode\">\(Self.escape(whole))</text:span>" }
1053 } else if let name = group(5) { 1150 } 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)
1055 } else if let marker = group(7), let body = group(8) { 1152 } else if let marker = group(7), let body = group(8) {
1056 let braced = body.hasPrefix("{") 1153 let braced = body.hasPrefix("{")
1057 if options.scripts == .off || (options.scripts == .braces && !braced) { 1154 if options.scripts == .off || (options.scripts == .braces && !braced) {
@@ -1067,7 +1164,8 @@ final class ODTRenderer {
1067 return out + plain(ns.substring(from: at)) 1164 return out + plain(ns.substring(from: at))
1068 } 1165 }
1069 1166
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`.
1071 private func plain(_ text: String) -> String { 1169 private func plain(_ text: String) -> String {
1072 var out = Self.escape(text) 1170 var out = Self.escape(text)
1073 if options.specialStrings { 1171 if options.specialStrings {
@@ -1076,7 +1174,9 @@ final class ODTRenderer {
1076 .replacingOccurrences(of: "--([^-])", with: "&#x2013;$1", options: .regularExpression) 1174 .replacingOccurrences(of: "--([^-])", with: "&#x2013;$1", options: .regularExpression)
1077 .replacingOccurrences(of: "...", with: "&#x2026;") 1175 .replacingOccurrences(of: "...", with: "&#x2026;")
1078 } 1176 }
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: " ")
1080 } 1180 }
1081 1181
1082 private func span(_ style: String, _ content: String) -> String { 1182 private func span(_ style: String, _ content: String) -> String {
@@ -1103,12 +1203,12 @@ final class ODTRenderer {
1103 if text.hasPrefix("<%%") { return plain(text) } 1203 if text.hasPrefix("<%%") { return plain(text) }
1104 return span(text.hasPrefix("<") ? "OrgActiveTimestamp" : "OrgInactiveTimestamp", plain(text)) 1204 return span(text.hasPrefix("<") ? "OrgActiveTimestamp" : "OrgInactiveTimestamp", plain(text))
1105 case .footnoteReference: 1205 case .footnoteReference:
1106 if tocEntry { return "" } 1206 if tocEntry || !withFootnotes { return "" }
1107 let comma = afterFootnote ? span("OrgSuperscript", ",") : "" 1207 let comma = afterFootnote ? span("OrgSuperscript", ",") : ""
1108 return comma + footnote(node.text) 1208 return comma + footnote(node)
1109 case .entity: 1209 case .entity:
1110 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "") 1210 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)
1112 case .radioTarget: 1212 case .radioTarget:
1113 let inner = plain(String(node.text.dropFirst(3).dropLast(3))) 1213 let inner = plain(String(node.text.dropFirst(3).dropLast(3)))
1114 if tocEntry { return inner } 1214 if tocEntry { return inner }
@@ -1166,35 +1266,91 @@ final class ODTRenderer {
1166 1266
1167 // MARK: - Footnotes 1267 // MARK: - Footnotes
1168 1268
1269 /// Numbers by footnote, a label or `@` and an anonymous reference's place, and the place
1270 /// of each one's first reference.
1169 private var footnoteNumbers: [String: Int] = [:] 1271 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 }
1171 1319
1172 private func footnote(_ text: String) -> String { 1320 private func footnote(_ node: SyntaxNode) -> String {
1321 let text = node.text
1173 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return plain(text) } 1322 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return plain(text) }
1174 var label = String(m.1) 1323 let key = base + node.range.lowerBound
1175 let inlineText = m.2.map(String.init) 1324 let label = m.1.isEmpty ? nil : String(m.1)
1176 if label.isEmpty { 1325 let id = label ?? "@\(key)"
1177 anonymous += 1 1326 let inline = m.2.map { (text: String($0), base: key + text.utf16.distance(from: text.startIndex, to: $0.startIndex)) }
1178 label = "anonymous-\(anonymous)" 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
1179 } 1343 }
1180 if let n = footnoteNumbers[label] { 1344 let n = footnoteNumbers[id]!
1345 if label != nil, firstReferences[id] != key {
1181 return span("OrgSuperscript", "<text:note-ref text:note-class=\"footnote\" text:reference-format=\"text\" text:ref-name=\"fn\(n)\">\(n)</text:note-ref>") 1346 return span("OrgSuperscript", "<text:note-ref text:note-class=\"footnote\" text:reference-format=\"text\" text:ref-name=\"fn\(n)\">\(n)</text:note-ref>")
1182 } 1347 }
1183 let n = footnoteNumbers.count + 1
1184 footnoteNumbers[label] = n
1185 let saved = (paragraphStyles, container, frames, afterFootnote) 1348 let saved = (paragraphStyles, container, frames, afterFootnote)
1186 paragraphStyles = ("Footnote", "OrgFootnoteCenter", "OrgFootnoteQuotations") 1349 paragraphStyles = ("Footnote", "OrgFootnoteCenter", "OrgFootnoteQuotations")
1187 container = nil 1350 container = nil
1188 frames = [] 1351 frames = []
1189 defer { (paragraphStyles, container, frames, afterFootnote) = saved } 1352 defer { (paragraphStyles, container, frames, afterFootnote) = saved }
1190 let definition: String 1353 guard let definition = definition(label: label, inline: inline) else { return fail("Definition not found for footnote \(m.1)") }
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 }
1198 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>" 1354 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>"
1199 } 1355 }
1200 1356
@@ -1236,7 +1392,7 @@ final class ODTRenderer {
1236 let descriptionNode = node.firstChild(.linkDescription) 1392 let descriptionNode = node.firstChild(.linkDescription)
1237 var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 } 1393 var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 }
1238 // `org-export-insert-image-links`: a description that is an image's path shows it. 1394 // `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)
1240 if let describedImage, !tocEntry { description = image(describedImage) } 1396 if let describedImage, !tocEntry { description = image(describedImage) }
1241 guard let path else { 1397 guard let path else {
1242 // A radio link refers to its target. 1398 // 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 {
55 55
56 """ 56 """
57 } 57 }
58 styles += """
59 <style:style style:name="Sect1" style:family="section">
60 <style:section-properties style:editable="false"/>
61 </style:style>
62
63 """
58 let sequences = ["Table", "Illustration", "Text", "Equation", "Listing"].map { 64 let sequences = ["Table", "Illustration", "Text", "Equation", "Listing"].map {
59 "<text:sequence-decl text:display-outline-level=\"2\" text:name=\"\($0)\"/>" 65 "<text:sequence-decl text:display-outline-level=\"2\" text:name=\"\($0)\"/>"
60 }.joined(separator: "\n") 66 }.joined(separator: "\n")
@@ -151,6 +157,8 @@ enum ODTTemplate {
151 styles += paragraph("OrgVerse", parent: "Text_20_body", "fo:margin-left=\"1cm\"") 157 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) 158 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\"") 159 styles += paragraph("OrgSrcBlockLastLine", parent: "OrgSrcBlock", "fo:margin-bottom=\"0.212cm\"")
160 styles += paragraph("OrgFixedWidthBlock", parent: "Standard", "fo:margin-top=\"0cm\" fo:margin-bottom=\"0cm\" fo:background-color=\"#f0f0f0\"", text: mono)
161 styles += paragraph("OrgFixedWidthBlockLastLine", parent: "OrgFixedWidthBlock", "fo:margin-bottom=\"0.212cm\"")
154 styles += paragraph("Footnote", parent: "Standard", "fo:margin-left=\"0.5cm\" fo:text-indent=\"-0.5cm\"", text: "fo:font-size=\"10pt\"") 162 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\"") 163 styles += paragraph("OrgFootnoteCenter", parent: "Footnote", "fo:text-align=\"center\"")
156 styles += paragraph("OrgFootnoteQuotations", parent: "Footnote", "fo:margin-left=\"1cm\" fo:margin-right=\"1cm\"") 164 styles += paragraph("OrgFootnoteQuotations", parent: "Footnote", "fo:margin-left=\"1cm\" fo:margin-right=\"1cm\"")
@@ -178,6 +186,7 @@ enum ODTTemplate {
178 styles += span("OrgTags", "fo:font-size=\"85%\"") 186 styles += span("OrgTags", "fo:font-size=\"85%\"")
179 styles += span("OrgTag", "fo:font-weight=\"bold\"") 187 styles += span("OrgTag", "fo:font-weight=\"bold\"")
180 styles += span("OrgPriority", "fo:font-weight=\"bold\"") 188 styles += span("OrgPriority", "fo:font-weight=\"bold\"")
189 for priority in ["A", "B", "C"] { styles += span("OrgPriority-\(priority)", "fo:font-weight=\"bold\"") }
181 styles += span("OrgActiveTimestamp", "fo:color=\"#555555\"") 190 styles += span("OrgActiveTimestamp", "fo:color=\"#555555\"")
182 styles += span("OrgInactiveTimestamp", "fo:color=\"#888888\"") 191 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\"") 192 styles += span("Internet_20_link", display: "Internet link", "fo:color=\"#000080\" style:text-underline-style=\"solid\" style:text-underline-width=\"auto\" style:text-underline-color=\"font-color\"")
Tests/OrgCoreTests/ODTExportTests.swift +149 −9
@@ -5,13 +5,14 @@ import Testing
5@testable import OrgCore 5@testable import OrgCore
6 6
7/// `content.xml` reduced to what ox-odt and the native export must agree on: headings with 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 8/// their outline level, paragraphs, lists, sections, spans, tables and their rows and cells,
9/// and images with their targets, notes and frames, and the text runs. Spaces written as 9/// links and images with their targets, notes and frames, the style names of these, and the
10/// elements count as spaces; references are numbered in order of appearance, since ox-odt's 10/// text runs. `text:s` counts as spaces; tabs and line breaks are tokens of their own;
11/// are random. 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.
12enum ODTSkeleton { 13enum ODTSkeleton {
13 static let kept: Set<String> = [ 14 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",
15 "table:table", "table:table-header-rows", "table:table-rows", "table:table-row", "table:table-cell", "table:covered-table-cell", 16 "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 "text:a", "draw:a", "draw:frame", "draw:image", "draw:text-box", "text:table-of-content", "text:index-body",
17 ] 18 ]
@@ -22,6 +23,7 @@ enum ODTSkeleton {
22 var lines: [String] = [] 23 var lines: [String] = []
23 var text = "" 24 var text = ""
24 var references: [String: Int] = [:] 25 var references: [String: Int] = [:]
26 var spans: [Bool] = []
25 func flush() { 27 func flush() {
26 let collapsed = Skeleton.decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ") 28 let collapsed = Skeleton.decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ")
27 if !collapsed.isEmpty { lines.append("\"" + collapsed + "\"") } 29 if !collapsed.isEmpty { lines.append("\"" + collapsed + "\"") }
@@ -45,18 +47,29 @@ enum ODTSkeleton {
45 text += String(repeating: " ", count: count) 47 text += String(repeating: " ", count: count)
46 continue 48 continue
47 case "text:tab", "text:line-break": 49 case "text:tab", "text:line-break":
48 text += " " 50 flush()
51 lines.append("<\(name)/>")
49 continue 52 continue
50 default: 53 default:
51 break 54 break
52 } 55 }
53 guard kept.contains(name) else { continue } 56 guard kept.contains(name) else { continue }
57 if name == "text:span", !tag.hasSuffix("/") {
58 if closing {
59 if spans.popLast() == false { continue }
60 } else {
61 let colored = tag.contains("text:style-name=\"OrgSrcFontLock")
62 spans.append(!colored)
63 if colored { continue }
64 }
65 }
54 flush() 66 flush()
55 if closing { 67 if closing {
56 lines.append("</\(name)>") 68 lines.append("</\(name)>")
57 continue 69 continue
58 } 70 }
59 var attributes = "" 71 var attributes = ""
72 if let style = tag.firstMatch(of: /(?:text|table):style-name="([^"]*)"/) { attributes += " style=\(style.1)" }
60 if let level = tag.firstMatch(of: /text:outline-level="([0-9]+)"/) { attributes += " level=\(level.1)" } 73 if let level = tag.firstMatch(of: /text:outline-level="([0-9]+)"/) { attributes += " level=\(level.1)" }
61 if let href = tag.firstMatch(of: /xlink:href="([^"]*)"/) { 74 if let href = tag.firstMatch(of: /xlink:href="([^"]*)"/) {
62 var value = String(href.1) 75 var value = String(href.1)
@@ -351,6 +364,101 @@ struct ODTExportTests {
351 Text -- here a_b and a_{b} and \\(x\\). 364 Text -- here a_b and a_{b} and \\(x\\).
352 * Second 365 * Second
353 """, 366 """,
367 "deep-headings": """
368 #+OPTIONS: toc:nil
369 * One
370 ** Two
371 *** Three
372 **** Four
373 See [[Four]].
374 **** Five
375 """,
376 "num-past-h": """
377 #+OPTIONS: toc:nil num:3 H:1
378 * A
379 ** B
380 *** C
381 **** D
382 """,
383 "nested-footnotes": """
384 #+OPTIONS: toc:nil
385 A[fn:1] B[fn:2] C[fn:4].
386
387 [fn:1] One[fn:3][fn:4].
388
389 [fn:2] Two.
390
391 [fn:3] Three.
392
393 [fn:4] Four.
394 """,
395 "inline-footnotes": """
396 #+OPTIONS: toc:nil
397 First[fn:x] then[fn:x: inline /def/] and an anonymous[fn:: one[fn:y]] note.
398
399 [fn:y] Nested in an anonymous one.
400 """,
401 "tocs": """
402 #+OPTIONS: toc:nil
403 * Top
404 #+TOC: headlines 1 local
405 ** Child A
406 ** DONE Child B
407 *** Grand
408 * Appendix
409 :PROPERTIES:
410 :UNNUMBERED: notoc
411 :END:
412 ** Inside appendix
413 *** Deeper
414 :PROPERTIES:
415 :UNNUMBERED: nil
416 :END:
417 * Last
418 #+TOC: headlines 5
419 """,
420 "cookie-header": """
421 #+OPTIONS: toc:nil
422 | <r> | <l> |
423 |-----+-----|
424 | a | b |
425 """,
426 "preserve-breaks": """
427 #+OPTIONS: toc:nil \\n:t
428 Line one
429 line two.
430
431 Ends with a break\\\\
432 next line\\\\
433 """,
434 "no-footnotes-tables-entities": """
435 #+OPTIONS: toc:nil f:nil |:nil e:nil
436 Text[fn:1] with \\alpha and \\beta{} here.
437
438 #+CAPTION: Dropped
439 | a | b |
440
441 - item
442 | c |
443
444 [fn:1] Note.
445 """,
446 "no-drawers": """
447 #+OPTIONS: toc:nil d:nil
448 * H
449 :NOTES:
450 Hidden.
451 :END:
452 Shown.
453 """,
454 "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 """,
354 ] 462 ]
355 463
356 /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the 464 /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the
@@ -491,13 +599,45 @@ struct ODTExportTests {
491 "Code src_python[:exports code]{1 + 1} here.\n", 599 "Code src_python[:exports code]{1 + 1} here.\n",
492 "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n", 600 "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n",
493 "- a quote\n #+begin_quote\n | q |\n #+end_quote\n", 601 "- 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",
494 ]) 616 ])
495 func refuses(_ text: String) { 617 func refuses(_ text: String) {
496 #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") } 618 #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") }
497 } 619 }
498 620
499 @Test func imageFiles() { 621 @Test func imageFiles() throws {
500 let files = ODTExport.imageFiles("[[file:a.png]] [[./b.jpg][desc]] [[https://x/c.png]] [[/abs/d.svg]]\n", path: "/doc/notes.org") 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")
501 #expect(files == ["/doc/a.png", "/abs/d.svg"]) 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 }
502 } 642 }
503} 643}
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
253Export to ODT writes an OpenDocument text file (=.odt=) for LibreOffice, Pages or Word. orgstar writes it itself, on the Mac and on iOS, the way Emacs's =ox-odt= does under =emacs -Q=: the same headings, paragraphs, lists, tables, links, notes and images, with ox-odt's style names, so a template that restyles ox-odt's output restyles this one too. 253Export to ODT writes an OpenDocument text file (=.odt=) for LibreOffice, Pages or Word. orgstar writes it itself, on the Mac and on iOS, the way Emacs's =ox-odt= does under =emacs -Q=: the same headings, paragraphs, lists, tables, links, notes and images, with ox-odt's style names, so a template that restyles ox-odt's output restyles this one too.
254 254
255- The title, subtitle (=#+SUBTITLE:=), author and date come first, then the table of contents and the text. On the Mac, without =#+AUTHOR:=, the author is your account's full name, as =user-full-name= is in Emacs. Without =#+TITLE:= there is no title. 255- The title, subtitle (=#+SUBTITLE:=), author and date come first, then the table of contents and the text. On the Mac, without =#+AUTHOR:=, the author is your account's full name, as =user-full-name= is in Emacs. Without =#+TITLE:= there is no title.
256- Headings are numbered by the word processor, to the depth =num= gives. Headings deeper than =H= become list items. =#+TOC: headlines= puts a table of contents where it is; =local= limits it to the section. 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. A note referred to again shows its number. 257- Footnotes are the word processor's own notes, numbered as ox-odt numbers them: those referred to in the text first, then those referred to only from other notes. A note referred to again shows its number.
258- Tables keep their header rows, alignment cookies, column groups and cell borders. A table inside a list item ends the list, sits indented below it, and the list carries on after it, as in ox-odt. 258- Tables keep their header rows, alignment cookies, column groups and cell borders. A table inside a list item ends the list, sits indented below it, and the list carries on after it, as in ox-odt.
259- Images from =file:= links (PNG, JPEG, GIF and SVG) are put inside the file. Their size is their pixels at 96 to the inch, or =#+ATTR_ODT: :width=, =:length= (the height) or =:scale=, and no more than 17 by 20 cm. A caption or =#+NAME:= numbers figures, tables and source blocks, and a link to the name shows the number. 259- Images from =file:= links (PNG, JPEG, GIF and SVG) are put inside the file. Their size is their pixels at 96 to the inch, or =#+ATTR_ODT: :width=, =:length= (the height) or =:scale=, and no more than 17 by 20 cm. A caption or =#+NAME:= numbers figures, tables and source blocks, and a link to the name shows the number.
260- LaTeX fragments and environments are kept as written, in code style, as ox-odt does without a MathML converter. Source blocks are not colored. 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.
261- =#+ODT:= lines, =#+BEGIN_EXPORT odt= blocks and =@@odt:...@@= snippets go in as they are. 262- =#+ODT:= lines, =#+BEGIN_EXPORT odt= blocks and =@@odt:...@@= snippets go in as they are.
262- The styles (=styles.xml=) are orgstar's own: A4 pages with 2 cm margins. =#+ODT_STYLES_FILE:= is not read. 263- The styles (=styles.xml=) are orgstar's own: A4 pages with 2 cm margins. =#+ODT_STYLES_FILE:= is not read.
263 264
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.
265 266
266* Markdown export 267* Markdown export
267 268