| @@ -27,12 +27,19 @@ public enum ODTExport { |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | 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 | 31 | public static func imageFiles(_ text: String, settings: OrgSettings = .default, path: String) -> [String] { |
| 31 | 32 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() |
| 33 | let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, setup: settings.setupKeywords) |
| 32 | 34 | 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 } |
| 36 | 43 | } |
| 37 | 44 | } |
| 38 | 45 | |
| @@ -46,6 +53,7 @@ public enum ODTExport { |
| 46 | 53 | let meta = HTMLExport.metadata(text, settings: settings) |
| 47 | 54 | let keywords = Self.keywords(text, settings: settings) |
| 48 | 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 | 57 | renderer.language = meta.language ?? language |
| 50 | 58 | |
| 51 | 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 | 97 | var parts: [(name: String, data: Data)] = [("mimetype", Data(ODTTemplate.mimetype.utf8))] |
| 90 | 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 | 100 | parts.append(("meta.xml", Data(metaXML.utf8))) |
| 93 | 101 | parts += renderer.images.map { ($0.name, $0.data) } |
| 94 | 102 | parts.append(("META-INF/manifest.xml", Data(ODTTemplate.manifest(images: renderer.images.map(\.name)).utf8))) |
| 95 | 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 | 142 | /// `#+SUBTITLE`, `#+KEYWORDS` and `#+DESCRIPTION`: lines of the same keyword joined. |
| 99 | 143 | static func keywords(_ text: String, settings: OrgSettings) -> [String: String] { |
| 100 | 144 | let tree = OrgParser.parse(text, defaults: settings) |
| @@ -132,6 +176,16 @@ final class ODTRenderer { |
| 132 | 176 | private(set) var failure: ODTExport.Failure? |
| 133 | 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 | 189 | init(settings: OrgSettings, options: ExportOptions, directory: URL) { |
| 136 | 190 | self.settings = settings |
| 137 | 191 | self.options = options |
| @@ -176,7 +230,8 @@ final class ODTRenderer { |
| 176 | 230 | private var selected: Set<Int>? |
| 177 | 231 | private var documentTree: OrgTree? |
| 178 | 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 | 236 | /// Where the tree being read starts in the document, so elements read from a block's or a |
| 182 | 237 | /// footnote's contents keep their place; how deep in such contents it is. |
| @@ -204,11 +259,8 @@ final class ODTRenderer { |
| 204 | 259 | heading.relative = heading.level - top + 1 |
| 205 | 260 | heading.lowLevel = heading.relative > options.headlineLevels |
| 206 | 261 | 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 { |
| 212 | 264 | let index = heading.relative - 1 |
| 213 | 265 | if counters.count <= index { counters += Array(repeating: 0, count: index + 1 - counters.count) } |
| 214 | 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 | 294 | private func collect(_ node: SyntaxNode, ancestors: [Int], infos: [Int: HeadingInfo]) { |
| 233 | 295 | var affiliated: [String: String] = [:] |
| 234 | 296 | for child in node.children { |
| @@ -260,6 +322,7 @@ final class ODTRenderer { |
| 260 | 322 | let inner = child.kind == .target ? child.text.dropFirst(2).dropLast(2) : child.text.dropFirst(3).dropLast(3) |
| 261 | 323 | targets.append((Self.words(inner.uppercased()), key, newReference())) |
| 262 | 324 | case .table: |
| 325 | guard withTables else { continue } |
| 263 | 326 | if captioned { enumerables.append((key, "Table", ancestors)) } |
| 264 | 327 | collect(child, ancestors: ancestors, infos: infos) |
| 265 | 328 | case .paragraph: |
| @@ -271,7 +334,7 @@ final class ODTRenderer { |
| 271 | 334 | if ["src", "example", "export", "comment", "verse"].contains(type) { continue } |
| 272 | 335 | within(body.text, base: key + body.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) } |
| 273 | 336 | case .drawer, .dynamicBlock: |
| 274 | | guard let inner = Self.inner(child) else { continue } |
| 337 | guard let inner = inner(child) else { continue } |
| 275 | 338 | within(inner.text, base: key + inner.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) } |
| 276 | 339 | default: |
| 277 | 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 |
| 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)? { |
| 285 | 348 | var lines = node.text.components(separatedBy: "\n") |
| 286 | 349 | if lines.last == "" { lines.removeLast() } |
| 287 | 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 | 352 | return (lines.dropFirst().dropLast().joined(separator: "\n"), first.utf16.count + 1) |
| 290 | 353 | } |
| 291 | 354 | |
| @@ -333,10 +396,11 @@ final class ODTRenderer { |
| 333 | 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 | 401 | selected = HTMLRenderer.selection(tree, tags: options.selectTags) |
| 339 | 402 | collect(tree) |
| 403 | if footnotePass == nil, withFootnotes { numberFootnotes(text) } |
| 340 | 404 | return rendering(tree, text) { tree.root.children.map(element).joined() } |
| 341 | 405 | } |
| 342 | 406 | |
| @@ -357,14 +421,19 @@ final class ODTRenderer { |
| 357 | 421 | /// `org-odt-toc` for the whole document: headings to `toc`, or nothing. |
| 358 | 422 | func tableOfContents() -> String { |
| 359 | 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 | 433 | let keys = headingOrder.filter { key in |
| 365 | 434 | 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) |
| 368 | 437 | } |
| 369 | 438 | guard !keys.isEmpty else { return "" } |
| 370 | 439 | let title = scope == nil ? ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8) : nil |
| @@ -392,7 +461,7 @@ final class ODTRenderer { |
| 392 | 461 | let heading = headings[key]! |
| 393 | 462 | var entry = heading.number.map { $0.map(String.init).joined(separator: ".") + ". " } ?? "" |
| 394 | 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 | 465 | if let priority = parts.priority { entry += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " } |
| 397 | 466 | entry += parts.title |
| 398 | 467 | if options.tagsInTOC, !parts.tags.isEmpty { entry += " " + tagsSpan(parts.tags) } |
| @@ -446,13 +515,13 @@ final class ODTRenderer { |
| 446 | 515 | case .plainList: |
| 447 | 516 | return list(node) |
| 448 | 517 | case .table: |
| 449 | | return table(node) |
| 518 | return withTables ? table(node) : "" |
| 450 | 519 | case .block: |
| 451 | 520 | return block(node) |
| 452 | 521 | case .horizontalRule: |
| 453 | 522 | return "\n<text:p text:style-name=\"Horizontal_20_Line\"></text:p>" |
| 454 | 523 | case .drawer, .dynamicBlock: |
| 455 | | guard let inner = Self.inner(node) else { return "" } |
| 524 | guard let inner = inner(node) else { return "" } |
| 456 | 525 | return blocks(inner.text, base: base + node.range.lowerBound + inner.offset) |
| 457 | 526 | case .inlineTask: |
| 458 | 527 | // `emacs -Q` doesn't load org-inlinetask, so ox-odt reads them as headings. |
| @@ -469,7 +538,7 @@ final class ODTRenderer { |
| 469 | 538 | return code(lines) |
| 470 | 539 | case .tableEl: |
| 471 | 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 | 542 | default: |
| 474 | 543 | // Comments, property drawers, planning, clocks, footnote definitions, formulas. |
| 475 | 544 | return "" |
| @@ -555,7 +624,13 @@ final class ODTRenderer { |
| 555 | 624 | imageCaption = affiliated["CAPTION"] |
| 556 | 625 | imageAttributes = affiliated["ATTR_ODT"] |
| 557 | 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 | 636 | /// The link of a paragraph that is only an image link. |
| @@ -695,6 +770,7 @@ final class ODTRenderer { |
| 695 | 770 | // MARK: - Tables |
| 696 | 771 | |
| 697 | 772 | private var tableStyles: [(name: String, width: String)] = [] |
| 773 | private var tableCount = 0 |
| 698 | 774 | |
| 699 | 775 | private func table(_ node: SyntaxNode) -> String { |
| 700 | 776 | let attributeLine = affiliated["ATTR_ODT"] |
| @@ -756,10 +832,11 @@ final class ODTRenderer { |
| 756 | 832 | if kinds[r] == .rule, seen { current += 1; seen = false } |
| 757 | 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 | 837 | let hasHeader = firstData.map { start in |
| 761 | 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 | 840 | } ?? false |
| 764 | 841 | let headerColumns = attributes["header-columns"].map { Int($0) ?? 1 } ?? 0 |
| 765 | 842 | var body = "" |
| @@ -784,9 +861,11 @@ final class ODTRenderer { |
| 784 | 861 | body += "\n<table:table-row>\n\(row)\n</table:table-row>" |
| 785 | 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 | 866 | var style = "OrgTable" |
| 788 | 867 | if attributeLine != nil { |
| 789 | | style = "OrgTable\(tableStyles.count + 1)" |
| 868 | style = "OrgTable\(tableCount)" |
| 790 | 869 | tableStyles.append((style, attributes["rel-width"] ?? "96")) |
| 791 | 870 | } |
| 792 | 871 | let firstRow = data.first.map { cells[$0] } ?? [] |
| @@ -831,7 +910,8 @@ final class ODTRenderer { |
| 831 | 910 | case "src": |
| 832 | 911 | let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? "" |
| 833 | 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 | 915 | if let textbox = attributes["textbox"], textbox != "nil" { |
| 836 | 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 | 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 | 958 | let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil) |
| 879 | 959 | let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat) |
| 880 | 960 | let key = block.joined(separator: "\n") |
| 881 | 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. |
| 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 { |
| 887 | 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 | 974 | let out = lines.enumerated().map { index, line -> String in |
| 889 | 975 | var text = line |
| 890 | 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 | 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 | 982 | return loc == nil ? paragraph : "\n<text:list-item>\(paragraph)\n</text:list-item>" |
| 895 | 983 | }.joined() |
| 896 | 984 | guard let loc else { return out } |
| @@ -944,6 +1032,11 @@ final class ODTRenderer { |
| 944 | 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 | 1040 | static func isImage(_ file: String) -> Bool { |
| 948 | 1041 | file.range(of: "\\.(jpeg|jpg|png|gif|svg)", options: [.regularExpression, .caseInsensitive]) != nil |
| 949 | 1042 | } |
| @@ -1003,6 +1096,8 @@ final class ODTRenderer { |
| 1003 | 1096 | afterFootnote = false |
| 1004 | 1097 | var out = "" |
| 1005 | 1098 | var text = "" |
| 1099 | // A line break object takes the newline after it, as Org's does. |
| 1100 | var afterBreak = false |
| 1006 | 1101 | for element in node.elements { |
| 1007 | 1102 | switch element { |
| 1008 | 1103 | case .token(let token): |
| @@ -1010,13 +1105,15 @@ final class ODTRenderer { |
| 1010 | 1105 | case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter: |
| 1011 | 1106 | continue |
| 1012 | 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 | 1111 | case .node(let child): |
| 1016 | 1112 | if !text.isEmpty { afterFootnote = false } |
| 1017 | 1113 | out += plainText(text) |
| 1018 | 1114 | text = "" |
| 1019 | 1115 | out += object(child) |
| 1116 | afterBreak = child.kind == .lineBreak |
| 1020 | 1117 | } |
| 1021 | 1118 | } |
| 1022 | 1119 | if !text.isEmpty { afterFootnote = false } |
| @@ -1051,7 +1148,7 @@ final class ODTRenderer { |
| 1051 | 1148 | if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil { |
| 1052 | 1149 | if options.tex { out += "<text:span text:style-name=\"OrgCode\">\(Self.escape(whole))</text:span>" } |
| 1053 | 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 | 1152 | } else if let marker = group(7), let body = group(8) { |
| 1056 | 1153 | let braced = body.hasPrefix("{") |
| 1057 | 1154 | if options.scripts == .off || (options.scripts == .braces && !braced) { |
| @@ -1067,7 +1164,8 @@ final class ODTRenderer { |
| 1067 | 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 | 1169 | private func plain(_ text: String) -> String { |
| 1072 | 1170 | var out = Self.escape(text) |
| 1073 | 1171 | if options.specialStrings { |
| @@ -1076,7 +1174,9 @@ final class ODTRenderer { |
| 1076 | 1174 | .replacingOccurrences(of: "--([^-])", with: "–$1", options: .regularExpression) |
| 1077 | 1175 | .replacingOccurrences(of: "...", with: "…") |
| 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 | 1182 | private func span(_ style: String, _ content: String) -> String { |
| @@ -1103,12 +1203,12 @@ final class ODTRenderer { |
| 1103 | 1203 | if text.hasPrefix("<%%") { return plain(text) } |
| 1104 | 1204 | return span(text.hasPrefix("<") ? "OrgActiveTimestamp" : "OrgInactiveTimestamp", plain(text)) |
| 1105 | 1205 | case .footnoteReference: |
| 1106 | | if tocEntry { return "" } |
| 1206 | if tocEntry || !withFootnotes { return "" } |
| 1107 | 1207 | let comma = afterFootnote ? span("OrgSuperscript", ",") : "" |
| 1108 | | return comma + footnote(node.text) |
| 1208 | return comma + footnote(node) |
| 1109 | 1209 | case .entity: |
| 1110 | 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 | 1212 | case .radioTarget: |
| 1113 | 1213 | let inner = plain(String(node.text.dropFirst(3).dropLast(3))) |
| 1114 | 1214 | if tocEntry { return inner } |
| @@ -1166,35 +1266,91 @@ final class ODTRenderer { |
| 1166 | 1266 | |
| 1167 | 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 | 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 | 1322 | 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 |
| 1179 | 1343 | } |
| 1180 | | if let n = footnoteNumbers[label] { |
| 1344 | let n = footnoteNumbers[id]! |
| 1345 | if label != nil, firstReferences[id] != key { |
| 1181 | 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 | 1348 | let saved = (paragraphStyles, container, frames, afterFootnote) |
| 1186 | 1349 | paragraphStyles = ("Footnote", "OrgFootnoteCenter", "OrgFootnoteQuotations") |
| 1187 | 1350 | container = nil |
| 1188 | 1351 | frames = [] |
| 1189 | 1352 | 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)") } |
| 1198 | 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 | 1392 | let descriptionNode = node.firstChild(.linkDescription) |
| 1237 | 1393 | var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 } |
| 1238 | 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 | 1396 | if let describedImage, !tocEntry { description = image(describedImage) } |
| 1241 | 1397 | guard let path else { |
| 1242 | 1398 | // A radio link refers to its target. |