Tests/OrgCoreTests/ODTExportTests.swift

7b8e9c5338e64edcb9d405f5449784741a5bdfa2
orgstar/Tests/OrgCoreTests/ODTExportTests.swift

730 lines · 28766 bytes

  1import Foundation
  2import AppKit
  3import ImageIO
  4import Testing
  5@testable import OrgCore
  6
  7/// `content.xml` reduced to what ox-odt and the native export must agree on: headings with
  8/// their outline level, paragraphs, lists, sections, spans, tables and their rows and cells,
  9/// links and images with their targets, notes and frames, the style names of these, and the
 10/// text runs. `text:s` counts as spaces; tabs and line breaks are tokens of their own;
 11/// references are numbered in order of appearance, since ox-odt's are random. The spans
 12/// ox-odt colors source code with are left out: the export doesn't fontify.
 13enum ODTSkeleton {
 14    static let kept: Set<String> = [
 15        "text:h", "text:p", "text:span", "text:list", "text:list-item", "text:list-header", "text:section", "text:note",
 16        "table:table", "table:table-header-rows", "table:table-rows", "table:table-row", "table:table-cell", "table:covered-table-cell",
 17        "text:a", "draw:a", "draw:frame", "draw:image", "draw:text-box", "text:table-of-content", "text:index-body",
 18    ]
 19
 20    static func reduce(_ xml: String) -> String {
 21        guard let start = xml.range(of: "<office:text>"), let end = xml.range(of: "</office:text>") else { return xml }
 22        let body = xml[start.upperBound..<end.lowerBound]
 23        var lines: [String] = []
 24        var text = ""
 25        var references: [String: Int] = [:]
 26        var spans: [Bool] = []
 27        func flush() {
 28            let collapsed = Skeleton.decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ")
 29            if !collapsed.isEmpty { lines.append("\"" + collapsed + "\"") }
 30            text = ""
 31        }
 32        var i = body.startIndex
 33        while i < body.endIndex {
 34            guard body[i] == "<", let close = body[i...].firstIndex(of: ">") else {
 35                text.append(body[i])
 36                i = body.index(after: i)
 37                continue
 38            }
 39            let tag = String(body[body.index(after: i)..<close])
 40            i = body.index(after: close)
 41            if tag.hasPrefix("!") || tag.hasPrefix("?") { continue }
 42            let closing = tag.hasPrefix("/")
 43            let name = String(tag.dropFirst(closing ? 1 : 0).prefix { !$0.isWhitespace && $0 != "/" })
 44            switch name {
 45            case "text:s":
 46                let count = tag.firstMatch(of: /text:c="([0-9]+)"/).flatMap { Int($0.1) } ?? 1
 47                text += String(repeating: " ", count: count)
 48                continue
 49            case "text:tab", "text:line-break":
 50                flush()
 51                lines.append("<\(name)/>")
 52                continue
 53            default:
 54                break
 55            }
 56            guard kept.contains(name) else { continue }
 57            if name == "text:span", !tag.hasSuffix("/") {
 58                if closing {
 59                    if spans.popLast() == false { continue }
 60                } else {
 61                    let colored = tag.contains("text:style-name=\"OrgSrcFontLock")
 62                    spans.append(!colored)
 63                    if colored { continue }
 64                }
 65            }
 66            flush()
 67            if closing {
 68                lines.append("</\(name)>")
 69                continue
 70            }
 71            var attributes = ""
 72            if let style = tag.firstMatch(of: /(?:text|table):style-name="([^"]*)"/) { attributes += " style=\(style.1)" }
 73            if let level = tag.firstMatch(of: /text:outline-level="([0-9]+)"/) { attributes += " level=\(level.1)" }
 74            if let href = tag.firstMatch(of: /xlink:href="([^"]*)"/) {
 75                var value = String(href.1)
 76                if value.hasPrefix("#") {
 77                    let n = references[value] ?? references.count + 1
 78                    references[value] = n
 79                    value = "#ref\(n)"
 80                }
 81                attributes += " href=\"\(value)\""
 82            }
 83            if let span = tag.firstMatch(of: /table:number-columns-spanned="([0-9]+)"/) { attributes += " span=\(span.1)" }
 84            lines.append("<\(name)\(attributes)>")
 85            if tag.hasSuffix("/") { lines.append("</\(name)>") }
 86        }
 87        flush()
 88        return lines.joined(separator: "\n") + "\n"
 89    }
 90}
 91
 92/// Reads a zip's entries, stored or deflated, through `unzip` for the latter.
 93enum ZipReader {
 94    struct Entry {
 95        var name: String
 96        var method: UInt16
 97        var extraLength: UInt16
 98        var data: Data
 99    }
100
101    /// The local entries in order.
102    static func entries(_ data: Data) -> [Entry] {
103        var out: [Entry] = []
104        var at = 0
105        let bytes = [UInt8](data)
106        func u16(_ i: Int) -> UInt16 { UInt16(bytes[i]) | UInt16(bytes[i + 1]) << 8 }
107        func u32(_ i: Int) -> UInt32 { UInt32(u16(i)) | UInt32(u16(i + 2)) << 16 }
108        while at + 30 <= bytes.count, u32(at) == 0x04034b50 {
109            let method = u16(at + 8)
110            let size = Int(u32(at + 18))
111            let nameLength = Int(u16(at + 26))
112            let extra = u16(at + 28)
113            let name = String(decoding: bytes[(at + 30)..<(at + 30 + nameLength)], as: UTF8.self)
114            let start = at + 30 + nameLength + Int(extra)
115            out.append(Entry(name: name, method: method, extraLength: extra, data: Data(bytes[start..<(start + size)])))
116            at = start + size
117        }
118        return out
119    }
120
121    /// The names the central directory lists.
122    static func directory(_ data: Data) -> [String] {
123        let bytes = [UInt8](data)
124        var names: [String] = []
125        var i = 0
126        while i + 46 <= bytes.count {
127            if bytes[i] == 0x50, bytes[i + 1] == 0x4b, bytes[i + 2] == 0x01, bytes[i + 3] == 0x02 {
128                let length = Int(bytes[i + 28]) | Int(bytes[i + 29]) << 8
129                names.append(String(decoding: bytes[(i + 46)..<(i + 46 + length)], as: UTF8.self))
130                i += 46 + length
131            } else {
132                i += 1
133            }
134        }
135        return names
136    }
137}
138
139struct ODTExportTests {
140    static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable
141
142    /// A PNG of `width` by `height` pixels.
143    static func png(width: Int, height: Int) -> Data {
144        let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
145                                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
146        context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
147        context.fill(CGRect(x: 0, y: 0, width: width, height: height))
148        let data = NSMutableData()
149        let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)!
150        CGImageDestinationAddImage(destination, context.makeImage()!, nil)
151        CGImageDestinationFinalize(destination)
152        return data as Data
153    }
154
155    static let corpus = ["minimal", "core", "headings", "listblocks", "lists", "table", "blocks", "timestamps", "footnote", "tblfm"]
156
157    /// Documents for what the corpus doesn't cover. `PIC` is replaced by an image's path.
158    static let snippets: [String: String] = [
159        "images": """
160            #+TITLE: Images
161
162            [[file:PIC]]
163
164            #+CAPTION: A captioned picture
165            #+NAME: fig:one
166            [[file:PIC]]
167
168            Inline [[file:PIC]] in text and a [[file:PIC][described]] link.
169
170            #+ATTR_ODT: :width 3
171            [[file:PIC]]
172
173            See [[fig:one]] and [[fig:one][the figure]].
174
175            [[https://example.com][file:PIC]]
176            """,
177        "tables": """
178            #+TITLE: Tables
179            #+OPTIONS: toc:nil
180
181            * One
182            #+CAPTION: Scores
183            #+NAME: tbl:scores
184            | Name  | <r>   |
185            | Name  | Score |
186            |-------+-------|
187            | alpha | 10    |
188            |-------+-------|
189            | beta  | x     |
190            | gamma |       |
191
192            Refer to [[tbl:scores]].
193
194            | / | <> |   |
195            | # | a  | b |
196            | ! | x  | y |
197            | # | 1  | 2 |
198
199            | <5> | b |
200            | 1   | 2 |
201
202            #+ATTR_ODT: :rel-width 50
203            | c | d |
204            """,
205        "list-tables": """
206            #+OPTIONS: toc:nil
207
208            1. first
209               - nested
210                 | a | b |
211                 | 1 | 2 |
212                 after the table
213               - next nested
214            2. second
215               | x |
216               | y |
217               then text
218               | z |
219
220            - term :: definition
221              | t |
222            """,
223        "footnotes": """
224            #+OPTIONS: toc:nil
225
226            One[fn:a][fn:b] and again[fn:a], anonymous[fn:: inline /note/].
227
228            [fn:a] First note.
229
230              With a second paragraph.
231            [fn:b] Second note.
232            """,
233        "low-levels": """
234            #+OPTIONS: H:2
235
236            * Top
237            ** Second
238            *** Third
239            Text under third.
240            **** Fourth
241            | cell |
242            *** Third again
243            * Other
244            """,
245        "links": """
246            #+TITLE: Links
247
248            * Alpha
249            :PROPERTIES:
250            :CUSTOM_ID: alpha-id
251            :ID: 1234-abcd
252            :END:
253            Go to [[*Beta]], [[Beta][the beta]], [[#alpha-id][custom]], [[#alpha-id]], [[id:1234-abcd]] and <<here>>.
254            * Beta
255            A <<<radio word>>> and later the radio word again. [[here][back]].
256            Mail [[mailto:a@b.c][me]], a file [[file:notes.txt]], ./rel.txt and [[./dir/x.org][rel]].
257            #+begin_src emacs-lisp -n -r
258            (setq x 1) (ref:one)
259            (setq y 2)
260            #+end_src
261            Line [[(one)]] and [[(one)][line %s]].
262            * Gamma :noexport:
263            Excluded.
264            * COMMENT Delta
265            Commented.
266            """,
267        "inline": """
268            #+TITLE: Inline /markup/
269            #+SUBTITLE: The subtitle
270            #+AUTHOR: Someone
271            #+DATE: <2024-03-01 Fri>
272            #+OPTIONS: num:nil pri:t
273
274            * TODO [#B] Heading with =code= :tag:
275            Text with *bold*, /italic/, _under_, +strike+, ~code   spaced~, =verb=.
276            Math \\(a+b\\) and $x$ and \\alpha and H_2O and x^{2} and e^x.
277            Dashes -- and --- and ... and a\\-b.
278            Line one\\\\
279            line two.
280            @@odt:<text:span>raw</text:span>@@ and @@html:<b>no</b>@@ and [2/3] cookie.
281            #+ODT: <text:p>raw paragraph</text:p>
282
283            -----
284
285            \\begin{equation}
286            E = mc^2
287            \\end{equation}
288
289            :NOTES:
290            Drawer contents.
291            :END:
292
293            #+begin_verse
294              Indented first
295            second   line
296            #+end_verse
297
298            #+begin_example -n
299            one
300            two
301            #+end_example
302
303            #+CAPTION: A listing
304            #+begin_src python
305            print("x")
306            #+end_src
307
308            : fixed width
309            : lines
310
311            #+begin_center
312            Centered *text*.
313            #+end_center
314
315            #+TOC: headlines 1
316            """,
317        "more": """
318            #+OPTIONS: toc:nil
319
320            * Heading
321            #+begin_src python
322
323            x = 1
324
325            y = 2
326
327            #+end_src
328
329            #+begin_example
330            ex
331
332
333            #+end_example
334
335            3. [@3] third
336            4. fourth
337               - [X] term :: def
338               - [ ] other :: more
339
340            #+begin_quote
341            - a quoted item
342            #+end_quote
343
344            [2024-01-01 Mon]--[2024-01-02 Tue] and <2024-01-01 Mon 10:00>
345
346            #+TOC: headlines local
347
348            ** Sub
349            Text \\alpha{} \\beta and \\nbsp{}.
350
351            #+begin_textbox
352            Boxed.
353            #+end_textbox
354
355            #+begin_annotation
356            Noted.
357            #+end_annotation
358            """,
359        "options": """
360            #+OPTIONS: toc:1 num:1 todo:nil tags:nil author:nil date:nil title:nil -:nil ^:{} tex:nil
361
362            * DONE First :x:
363            ** Sub
364            Text -- here a_b and a_{b} and \\(x\\).
365            * Second
366            """,
367        "deep-headings": """
368            #+OPTIONS: toc:nil
369            * One
370            ** Two
371            *** Three
372            **** Four
373            See [[Four]].
374            **** Five
375            """,
376        "num-past-h": """
377            #+OPTIONS: toc:nil num:3 H:1
378            * A
379            ** B
380            *** C
381            **** D
382            """,
383        "nested-footnotes": """
384            #+OPTIONS: toc:nil
385            A[fn:1] B[fn:2] C[fn:4].
386
387            [fn:1] One[fn:3][fn:4].
388
389            [fn:2] Two.
390
391            [fn:3] Three.
392
393            [fn:4] Four.
394            """,
395        "inline-footnotes": """
396            #+OPTIONS: toc:nil
397            First[fn:x] then[fn:x: inline /def/] and an anonymous[fn:: one[fn:y]] note.
398
399            [fn:y] Nested in an anonymous one.
400            """,
401        "tocs": """
402            #+OPTIONS: toc:nil
403            * Top
404            #+TOC: headlines 1 local
405            ** Child A
406            ** DONE Child B
407            *** Grand
408            * Appendix
409            :PROPERTIES:
410            :UNNUMBERED: notoc
411            :END:
412            ** Inside appendix
413            *** Deeper
414            :PROPERTIES:
415            :UNNUMBERED: nil
416            :END:
417            * Last
418            #+TOC: headlines 5
419            """,
420        "cookie-header": """
421            #+OPTIONS: toc:nil
422            | <r> | <l> |
423            |-----+-----|
424            | a   | b   |
425            """,
426        "preserve-breaks": """
427            #+OPTIONS: toc:nil \\n:t
428            Line one
429            line two.
430
431            Ends with a break\\\\
432            next line\\\\
433            """,
434        "no-footnotes-tables-entities": """
435            #+OPTIONS: toc:nil f:nil |:nil e:nil
436            Text[fn:1] with \\alpha and \\beta{} here.
437
438            #+CAPTION: Dropped
439            | a | b |
440
441            - item
442              | c |
443
444            [fn:1] Note.
445            """,
446        "no-drawers": """
447            #+OPTIONS: toc:nil d:nil
448            * H
449            :NOTES:
450            Hidden.
451            :END:
452            Shown.
453            """,
454        "include-subdirectory": """
455            #+OPTIONS: toc:nil
456            #+INCLUDE: "sub/part.inc"
457            """,
458        "src-blank-lines": """
459            #+OPTIONS: toc:nil
460            #+begin_src python
461            a
462            \u{20}\u{20}
463            #+end_src
464
465            #+begin_src python
466            a
467            \u{20}\u{20}
468
469            #+end_src
470
471            #+begin_src python -i
472            a
473            \u{20}\u{20}
474            #+end_src
475
476            #+begin_example
477            a
478            \u{20}\u{20}
479            #+end_example
480
481            #+begin_src foo
482            \u{20}\u{20}a
483            \u{20}\u{20}
484            #+end_src
485            """,
486        "toc-local-before-headings": """
487            #+OPTIONS: toc:nil
488            #+TOC: headlines 1 local
489            * A
490            ** B
491            """,
492        "babel-languages": """
493            #+OPTIONS: toc:nil
494            before
495            #+begin_src dot
496            a
497            #+end_src
498            after
499            #+begin_src latex
500            b
501            #+end_src
502            #+begin_src plantuml
503            c
504            #+end_src
505            #+begin_src ditaa
506            d
507            #+end_src
508            #+begin_src gnuplot
509            e
510            #+end_src
511            #+begin_src lilypond
512            f
513            #+end_src
514            """,
515        "all-drawers": """
516            #+OPTIONS: toc:nil d:t
517            * H
518            :LOGBOOK:
519            - Note taken on [2024-01-01 Mon 10:00]
520            :END:
521            Shown.
522            """,
523    ]
524
525    /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the
526    /// message.
527    static func emacs(_ files: [URL]) throws -> [String] {
528        let folder = files[0].deletingLastPathComponent()
529        let output = folder.appendingPathComponent("out.json")
530        let script = folder.appendingPathComponent("odt.el")
531        try """
532            ;;; -*- lexical-binding: t -*-
533            (require 'ox-odt)
534            (require 'json)
535            (setq user-full-name "Tester")
536            (let (results)
537              (dolist (file (split-string (getenv "ODT_FILES") "\\n" t))
538                (push (condition-case err
539                          (with-current-buffer (find-file-noselect file)
540                            (let ((odt (org-odt-export-to-odt)))
541                              (with-temp-buffer
542                                (let ((coding-system-for-read 'utf-8))
543                                  (call-process "unzip" nil t nil "-p" odt "content.xml"))
544                                (buffer-string))))
545                        (error (concat "ERROR: " (error-message-string err))))
546                      results))
547              (let ((coding-system-for-write 'utf-8))
548                (with-temp-file (getenv "ODT_OUTPUT")
549                  (insert (json-encode (vconcat (nreverse results)))))))
550            """.write(to: script, atomically: true, encoding: .utf8)
551        try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: [
552            "ODT_FILES": files.map(\.path).joined(separator: "\n"), "ODT_OUTPUT": output.path, "TZ": "UTC",
553        ])
554        return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
555    }
556
557    static func content(_ text: String, path: String) throws -> String {
558        let parts = try ODTExport.parts(text, path: path, author: "Tester")
559        return String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
560    }
561
562    @Test(.enabled(if: oracle))
563    func matchesOxODT() throws {
564        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
565        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
566        defer { try? FileManager.default.removeItem(at: folder) }
567        let picture = folder.appendingPathComponent("pic.png")
568        try Self.png(width: 64, height: 48).write(to: picture)
569        // Links in a file included from another folder are relative to that folder.
570        let sub = folder.appendingPathComponent("sub")
571        try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
572        try Self.png(width: 20, height: 10).write(to: sub.appendingPathComponent("pic.png"))
573        try """
574            [[file:pic.png]]
575
576            file:pic.png and <file:pic.png> and [[https://x.org][file:pic.png]] and [[file:../sub/pic.png][pic]]
577
578            See file:notes.txt and <file:notes.txt>.
579
580            #+begin_example
581            [[file:nothere.png]]
582            #+end_example
583            """.write(to: sub.appendingPathComponent("part.inc"), atomically: true, encoding: .utf8)
584        var documents: [(name: String, text: String)] = []
585        for name in Self.corpus {
586            documents.append((name, try String(contentsOf: ExportTests.folder.appendingPathComponent("\(name).org"), encoding: .utf8)))
587        }
588        for (name, text) in Self.snippets.sorted(by: { $0.key < $1.key }) {
589            documents.append((name, text.replacingOccurrences(of: "PIC", with: picture.path) + "\n"))
590        }
591        let files = documents.map { folder.appendingPathComponent($0.name + ".org") }
592        for (document, file) in zip(documents, files) { try document.text.write(to: file, atomically: true, encoding: .utf8) }
593        let expected = try Self.emacs(files)
594        for (index, document) in documents.enumerated() {
595            let theirs = ODTSkeleton.reduce(expected[index])
596            let ours = ODTSkeleton.reduce(try Self.content(document.text, path: files[index].path))
597            #expect(ours == theirs, "\(document.name)\n--- ours\n\(ours)\n--- ox-odt\n\(theirs)")
598        }
599    }
600
601    /// Where ox-odt stops, the export stops with its message.
602    @Test(.enabled(if: oracle))
603    func failsLikeOxODT() throws {
604        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
605        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
606        defer { try? FileManager.default.removeItem(at: folder) }
607        // `[[./pic.png]]` included from `sub` is written back as `[[sub/pic.png]]`, a fuzzy link.
608        let sub = folder.appendingPathComponent("sub")
609        try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
610        try Self.png(width: 10, height: 10).write(to: sub.appendingPathComponent("pic.png"))
611        try "[[./pic.png]]\n".write(to: sub.appendingPathComponent("dot.inc"), atomically: true, encoding: .utf8)
612        let documents = [
613            "broken": "See [[nowhere]].\n",
614            "included-dot-link": "#+INCLUDE: \"sub/dot.inc\"\n",
615            "missing": "[[file:missing.png]]\n",
616            "elements": try String(contentsOf: ExportTests.folder.appendingPathComponent("elements.org"), encoding: .utf8),
617        ].sorted { $0.key < $1.key }
618        let files = documents.map { folder.appendingPathComponent($0.key + ".org") }
619        for (document, file) in zip(documents, files) { try document.value.write(to: file, atomically: true, encoding: .utf8) }
620        let expected = try Self.emacs(files)
621        for (index, document) in documents.enumerated() {
622            #expect(expected[index].hasPrefix("ERROR: "), "\(document.key)")
623            #expect(throws: ODTExport.Failure.self) { try Self.content(document.value, path: files[index].path) }
624            do {
625                _ = try Self.content(document.value, path: files[index].path)
626            } catch let failure as ODTExport.Failure {
627                #expect(expected[index].contains(failure.message), "\(document.key): \(failure.message) / \(expected[index])")
628            }
629        }
630    }
631
632    /// `mimetype` first and stored, with no extra field; the manifest lists every part; each
633    /// XML part parses.
634    @Test func package() throws {
635        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
636        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
637        defer { try? FileManager.default.removeItem(at: folder) }
638        try Self.png(width: 10, height: 10).write(to: folder.appendingPathComponent("a.png"))
639        let path = folder.appendingPathComponent("doc.org").path
640        let data = try ODTExport.document("#+TITLE: T & U\n\n* Heading\n[[./a.png]]\n\n| x | y |\n", path: path)
641        let entries = ZipReader.entries(data)
642        #expect(entries.first?.name == "mimetype")
643        #expect(entries.first?.method == 0)
644        #expect(entries.first?.extraLength == 0)
645        #expect(entries.first.map { String(decoding: $0.data, as: UTF8.self) } == "application/vnd.oasis.opendocument.text")
646        #expect(ZipReader.directory(data) == entries.map(\.name))
647        #expect(entries.map(\.name) == ["mimetype", "content.xml", "styles.xml", "meta.xml", "Images/0001.png", "META-INF/manifest.xml"])
648        let manifest = try XMLDocument(data: entries.last!.data)
649        let listed = try manifest.nodes(forXPath: "//*[local-name()='file-entry']/@*[local-name()='full-path']").compactMap(\.stringValue)
650        for entry in entries where !["mimetype", "META-INF/manifest.xml"].contains(entry.name) {
651            #expect(listed.contains(entry.name), "\(entry.name)")
652        }
653        #expect(listed.contains("/"))
654        for entry in entries where entry.name.hasSuffix(".xml") {
655            #expect(throws: Never.self) { try XMLDocument(data: entry.data) }
656        }
657        let content = try XMLDocument(data: entries[1].data)
658        #expect(try content.nodes(forXPath: "//*[local-name()='h']").count == 1)
659        #expect(try content.nodes(forXPath: "//*[local-name()='image']/@*[local-name()='href']").compactMap(\.stringValue) == ["Images/0001.png"])
660        #expect(try content.nodes(forXPath: "//*[local-name()='table-cell']").count == 2)
661        let meta = try XMLDocument(data: entries[3].data)
662        #expect(try meta.nodes(forXPath: "//*[local-name()='title']").first?.stringValue == "T & U")
663    }
664
665    /// The text system reads the file: headings, list items, table cells and notes.
666    @Test func opensInTextKit() throws {
667        let text = "#+TITLE: Opened\n\n* Heading\n- item one\n- item two\n\n| a | b |\n|---+---|\n| 1 | 2 |\n\nA note.[fn:1]\n\n[fn:1] Noted.\n"
668        let data = try ODTExport.document(text, path: "/tmp/doc.org")
669        let string = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.openDocument], documentAttributes: nil).string
670        for word in ["Opened", "Heading", "item one", "item two", "a", "2", "A note."] {
671            #expect(string.contains(word), "\(word) in \(string)")
672        }
673    }
674
675    /// What the native export can't write the way ox-odt does stops the export instead.
676    @Test(arguments: [
677        "*************** Task\nBody.\n*************** END\n",
678        "Here <<there>> and [[there]].\n",
679        "#+begin_src emacs-lisp\n(x) (ref:a)\n#+end_src\n[[(a)]]\n",
680        "#+ATTR_ODT: :style TableWithHeaderRowAndColumn\n| a |\n",
681        "Code src_python[:exports code]{1 + 1} here.\n",
682        "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n",
683        "- a quote\n  #+begin_quote\n  | q |\n  #+end_quote\n",
684        "#+OPTIONS: p:t\n* H\nSCHEDULED: <2024-01-01 Mon>\n",
685        "#+OPTIONS: broken-links:t\nSee [[nowhere]].\n",
686        "#+OPTIONS: c:t\n* H\nCLOCK: [2024-01-01 Mon 10:00]--[2024-01-01 Mon 11:00] =>  1:00\n",
687        "#+OPTIONS: prop:t\n* H\n:PROPERTIES:\n:A: 1\n:END:\n",
688        "#+OPTIONS: ::nil\n: fixed\n",
689        "#+OPTIONS: *:nil\n*bold*\n",
690        "#+OPTIONS: stat:nil\n* H [1/2]\n",
691        "#+OPTIONS: tasks:nil\n* TODO H\n",
692        "#+OPTIONS: <:nil\n<2024-01-01 Mon>\n",
693        "#+OPTIONS: arch:nil\n* H :ARCHIVE:\nBody.\n",
694        "#+OPTIONS: email:t\n#+EMAIL: a@b.c\nText.\n",
695        "#+OPTIONS: ':t\n\"quoted\"\n",
696        "#+OPTIONS: tex:verbatim\n\\(x\\)\n",
697        "#+OPTIONS: d:(\"NOTES\")\n:NOTES:\nx\n:END:\n",
698    ])
699    func refuses(_ text: String) {
700        #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") }
701    }
702
703    @Test func imageFiles() throws {
704        let files = ODTExport.imageFiles("[[file:a.png]] [[./b.jpg][desc]] [[https://x/c.png]] [[/abs/d.svg]] [[https://x][file:e.png]]\n", path: "/doc/notes.org")
705        #expect(files == ["/doc/a.png", "/abs/d.svg", "/doc/e.png"])
706        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
707        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
708        defer { try? FileManager.default.removeItem(at: folder) }
709        try "[[file:/elsewhere/f.png]]\n".write(to: folder.appendingPathComponent("part.org"), atomically: true, encoding: .utf8)
710        #expect(ODTExport.imageFiles("#+INCLUDE: \"part.org\"\n", path: folder.appendingPathComponent("doc.org").path) == ["/elsewhere/f.png"])
711        let sub = folder.appendingPathComponent("sub")
712        try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
713        try "[[file:g.png]] [[https://x][file:../h.png]]\n".write(to: sub.appendingPathComponent("part.inc"), atomically: true, encoding: .utf8)
714        #expect(ODTExport.imageFiles("#+INCLUDE: \"sub/part.inc\"\n", path: folder.appendingPathComponent("doc.org").path)
715            == [sub.appendingPathComponent("g.png").path, folder.appendingPathComponent("h.png").path])
716    }
717
718    /// Every style `content.xml` names is in `styles.xml` or its automatic styles.
719    @Test func stylesDefined() throws {
720        let text = "#+OPTIONS: pri:t\n* TODO [#A] One\n* [#B] Two\n* DONE [#C] Three\n"
721        let parts = try ODTExport.parts(text, path: "/tmp/doc.org")
722        let content = String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
723        let styles = String(decoding: parts.first { $0.name == "styles.xml" }!.data, as: UTF8.self)
724        let used = Set(content.matches(of: /text:style-name="([^"]+)"/).map { String($0.1) })
725        #expect(used.isSuperset(of: ["OrgPriority-A", "OrgPriority-B", "OrgPriority-C"]))
726        for name in used {
727            #expect(styles.contains("style:name=\"\(name)\"") || content.contains("style:name=\"\(name)\""), "\(name)")
728        }
729    }
730}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form