Tests/OrgCoreTests/ODTExportTests.swift

design-themes-widgets
orgstar/Tests/OrgCoreTests/ODTExportTests.swift history · blame · raw

827 lines · 30675 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-results": """
493            #+OPTIONS: toc:nil
494            #+begin_src dot
495            a
496            #+end_src
497
498            #+RESULTS:
499            : resdot
500
501            #+begin_src dot :file graph.png
502            digraph { b }
503            #+end_src
504
505            #+RESULTS:
506            [[file:graph.png]]
507
508            #+begin_src latex
509            c
510            #+end_src
511
512            #+RESULTS:
513            #+begin_export latex
514            c
515            #+end_export
516
517            #+begin_src processing
518            d
519            #+end_src
520
521            #+RESULTS:
522            : resprocessing
523
524            #+begin_src org
525            e
526            #+end_src
527
528            #+RESULTS:
529            : resorg
530
531            #+begin_src gnuplot :file plot.png
532            f
533            #+end_src
534
535            #+RESULTS:
536            [[file:plot.png]]
537
538            after
539            """,
540        "babel-languages-exports": """
541            #+OPTIONS: toc:nil
542            #+begin_src dot :exports results
543            a
544            #+end_src
545
546            #+RESULTS:
547            : resdot
548
549            #+begin_src dot :file pic.png :exports both
550            digraph { b }
551            #+end_src
552
553            #+RESULTS:
554            [[file:pic.png]]
555
556            #+begin_src latex :exports results
557            c
558            #+end_src
559
560            #+RESULTS:
561            #+begin_export latex
562            c
563            #+end_export
564
565            #+begin_src processing :exports both
566            d
567            #+end_src
568
569            #+RESULTS:
570            : resprocessing
571
572            #+begin_src dot :exports none
573            g
574            #+end_src
575
576            #+RESULTS:
577            : resnone
578
579            #+begin_src dot :file none.png :exports results
580            h
581            #+end_src
582
583            #+begin_src latex :exports both
584            i
585            #+end_src
586
587            after
588            """,
589        "babel-languages": """
590            #+OPTIONS: toc:nil
591            before
592            #+begin_src dot
593            a
594            #+end_src
595            after
596            #+begin_src latex
597            b
598            #+end_src
599            #+begin_src plantuml
600            c
601            #+end_src
602            #+begin_src ditaa
603            d
604            #+end_src
605            #+begin_src gnuplot
606            e
607            #+end_src
608            #+begin_src lilypond
609            f
610            #+end_src
611            """,
612        "all-drawers": """
613            #+OPTIONS: toc:nil d:t
614            * H
615            :LOGBOOK:
616            - Note taken on [2024-01-01 Mon 10:00]
617            :END:
618            Shown.
619            """,
620    ]
621
622    /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the
623    /// message.
624    static func emacs(_ files: [URL]) throws -> [String] {
625        let folder = files[0].deletingLastPathComponent()
626        let output = folder.appendingPathComponent("out.json")
627        let script = folder.appendingPathComponent("odt.el")
628        try """
629            ;;; -*- lexical-binding: t -*-
630            (require 'ox-odt)
631            (require 'json)
632            (setq user-full-name "Tester")
633            (let (results)
634              (dolist (file (split-string (getenv "ODT_FILES") "\\n" t))
635                (push (condition-case err
636                          (with-current-buffer (find-file-noselect file)
637                            (let ((odt (org-odt-export-to-odt)))
638                              (with-temp-buffer
639                                (let ((coding-system-for-read 'utf-8))
640                                  (call-process "unzip" nil t nil "-p" odt "content.xml"))
641                                (buffer-string))))
642                        (error (concat "ERROR: " (error-message-string err))))
643                      results))
644              (let ((coding-system-for-write 'utf-8))
645                (with-temp-file (getenv "ODT_OUTPUT")
646                  (insert (json-encode (vconcat (nreverse results)))))))
647            """.write(to: script, atomically: true, encoding: .utf8)
648        try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: [
649            "ODT_FILES": files.map(\.path).joined(separator: "\n"), "ODT_OUTPUT": output.path, "TZ": "UTC",
650        ])
651        return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
652    }
653
654    static func content(_ text: String, path: String) throws -> String {
655        let parts = try ODTExport.parts(text, path: path, author: "Tester")
656        return String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
657    }
658
659    @Test(.enabled(if: oracle))
660    func matchesOxODT() throws {
661        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
662        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
663        defer { try? FileManager.default.removeItem(at: folder) }
664        let picture = folder.appendingPathComponent("pic.png")
665        try Self.png(width: 64, height: 48).write(to: picture)
666        // Links in a file included from another folder are relative to that folder.
667        let sub = folder.appendingPathComponent("sub")
668        try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
669        try Self.png(width: 20, height: 10).write(to: sub.appendingPathComponent("pic.png"))
670        try """
671            [[file:pic.png]]
672
673            file:pic.png and <file:pic.png> and [[https://x.org][file:pic.png]] and [[file:../sub/pic.png][pic]]
674
675            See file:notes.txt and <file:notes.txt>.
676
677            #+begin_example
678            [[file:nothere.png]]
679            #+end_example
680            """.write(to: sub.appendingPathComponent("part.inc"), atomically: true, encoding: .utf8)
681        var documents: [(name: String, text: String)] = []
682        for name in Self.corpus {
683            documents.append((name, try String(contentsOf: ExportTests.folder.appendingPathComponent("\(name).org"), encoding: .utf8)))
684        }
685        for (name, text) in Self.snippets.sorted(by: { $0.key < $1.key }) {
686            documents.append((name, text.replacingOccurrences(of: "PIC", with: picture.path) + "\n"))
687        }
688        let files = documents.map { folder.appendingPathComponent($0.name + ".org") }
689        for (document, file) in zip(documents, files) { try document.text.write(to: file, atomically: true, encoding: .utf8) }
690        let expected = try Self.emacs(files)
691        for (index, document) in documents.enumerated() {
692            let theirs = ODTSkeleton.reduce(expected[index])
693            let ours = ODTSkeleton.reduce(try Self.content(document.text, path: files[index].path))
694            #expect(ours == theirs, "\(document.name)\n--- ours\n\(ours)\n--- ox-odt\n\(theirs)")
695        }
696    }
697
698    /// Where ox-odt stops, the export stops with its message.
699    @Test(.enabled(if: oracle))
700    func failsLikeOxODT() throws {
701        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
702        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
703        defer { try? FileManager.default.removeItem(at: folder) }
704        // `[[./pic.png]]` included from `sub` is written back as `[[sub/pic.png]]`, a fuzzy link.
705        let sub = folder.appendingPathComponent("sub")
706        try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
707        try Self.png(width: 10, height: 10).write(to: sub.appendingPathComponent("pic.png"))
708        try "[[./pic.png]]\n".write(to: sub.appendingPathComponent("dot.inc"), atomically: true, encoding: .utf8)
709        let documents = [
710            "broken": "See [[nowhere]].\n",
711            "included-dot-link": "#+INCLUDE: \"sub/dot.inc\"\n",
712            "missing": "[[file:missing.png]]\n",
713            "elements": try String(contentsOf: ExportTests.folder.appendingPathComponent("elements.org"), encoding: .utf8),
714        ].sorted { $0.key < $1.key }
715        let files = documents.map { folder.appendingPathComponent($0.key + ".org") }
716        for (document, file) in zip(documents, files) { try document.value.write(to: file, atomically: true, encoding: .utf8) }
717        let expected = try Self.emacs(files)
718        for (index, document) in documents.enumerated() {
719            #expect(expected[index].hasPrefix("ERROR: "), "\(document.key)")
720            #expect(throws: ODTExport.Failure.self) { try Self.content(document.value, path: files[index].path) }
721            do {
722                _ = try Self.content(document.value, path: files[index].path)
723            } catch let failure as ODTExport.Failure {
724                #expect(expected[index].contains(failure.message), "\(document.key): \(failure.message) / \(expected[index])")
725            }
726        }
727    }
728
729    /// `mimetype` first and stored, with no extra field; the manifest lists every part; each
730    /// XML part parses.
731    @Test func package() throws {
732        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
733        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
734        defer { try? FileManager.default.removeItem(at: folder) }
735        try Self.png(width: 10, height: 10).write(to: folder.appendingPathComponent("a.png"))
736        let path = folder.appendingPathComponent("doc.org").path
737        let data = try ODTExport.document("#+TITLE: T & U\n\n* Heading\n[[./a.png]]\n\n| x | y |\n", path: path)
738        let entries = ZipReader.entries(data)
739        #expect(entries.first?.name == "mimetype")
740        #expect(entries.first?.method == 0)
741        #expect(entries.first?.extraLength == 0)
742        #expect(entries.first.map { String(decoding: $0.data, as: UTF8.self) } == "application/vnd.oasis.opendocument.text")
743        #expect(ZipReader.directory(data) == entries.map(\.name))
744        #expect(entries.map(\.name) == ["mimetype", "content.xml", "styles.xml", "meta.xml", "Images/0001.png", "META-INF/manifest.xml"])
745        let manifest = try XMLDocument(data: entries.last!.data)
746        let listed = try manifest.nodes(forXPath: "//*[local-name()='file-entry']/@*[local-name()='full-path']").compactMap(\.stringValue)
747        for entry in entries where !["mimetype", "META-INF/manifest.xml"].contains(entry.name) {
748            #expect(listed.contains(entry.name), "\(entry.name)")
749        }
750        #expect(listed.contains("/"))
751        for entry in entries where entry.name.hasSuffix(".xml") {
752            #expect(throws: Never.self) { try XMLDocument(data: entry.data) }
753        }
754        let content = try XMLDocument(data: entries[1].data)
755        #expect(try content.nodes(forXPath: "//*[local-name()='h']").count == 1)
756        #expect(try content.nodes(forXPath: "//*[local-name()='image']/@*[local-name()='href']").compactMap(\.stringValue) == ["Images/0001.png"])
757        #expect(try content.nodes(forXPath: "//*[local-name()='table-cell']").count == 2)
758        let meta = try XMLDocument(data: entries[3].data)
759        #expect(try meta.nodes(forXPath: "//*[local-name()='title']").first?.stringValue == "T & U")
760    }
761
762    /// The text system reads the file: headings, list items, table cells and notes.
763    @Test func opensInTextKit() throws {
764        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"
765        let data = try ODTExport.document(text, path: "/tmp/doc.org")
766        let string = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.openDocument], documentAttributes: nil).string
767        for word in ["Opened", "Heading", "item one", "item two", "a", "2", "A note."] {
768            #expect(string.contains(word), "\(word) in \(string)")
769        }
770    }
771
772    /// What the native export can't write the way ox-odt does stops the export instead.
773    @Test(arguments: [
774        "*************** Task\nBody.\n*************** END\n",
775        "Here <<there>> and [[there]].\n",
776        "#+begin_src emacs-lisp\n(x) (ref:a)\n#+end_src\n[[(a)]]\n",
777        "#+ATTR_ODT: :style TableWithHeaderRowAndColumn\n| a |\n",
778        "Code src_python[:exports code]{1 + 1} here.\n",
779        "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n",
780        "- a quote\n  #+begin_quote\n  | q |\n  #+end_quote\n",
781        "#+OPTIONS: p:t\n* H\nSCHEDULED: <2024-01-01 Mon>\n",
782        "#+OPTIONS: broken-links:t\nSee [[nowhere]].\n",
783        "#+OPTIONS: c:t\n* H\nCLOCK: [2024-01-01 Mon 10:00]--[2024-01-01 Mon 11:00] =>  1:00\n",
784        "#+OPTIONS: prop:t\n* H\n:PROPERTIES:\n:A: 1\n:END:\n",
785        "#+OPTIONS: ::nil\n: fixed\n",
786        "#+OPTIONS: *:nil\n*bold*\n",
787        "#+OPTIONS: stat:nil\n* H [1/2]\n",
788        "#+OPTIONS: tasks:nil\n* TODO H\n",
789        "#+OPTIONS: <:nil\n<2024-01-01 Mon>\n",
790        "#+OPTIONS: arch:nil\n* H :ARCHIVE:\nBody.\n",
791        "#+OPTIONS: email:t\n#+EMAIL: a@b.c\nText.\n",
792        "#+OPTIONS: ':t\n\"quoted\"\n",
793        "#+OPTIONS: tex:verbatim\n\\(x\\)\n",
794        "#+OPTIONS: d:(\"NOTES\")\n:NOTES:\nx\n:END:\n",
795    ])
796    func refuses(_ text: String) {
797        #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") }
798    }
799
800    @Test func imageFiles() throws {
801        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")
802        #expect(files == ["/doc/a.png", "/abs/d.svg", "/doc/e.png"])
803        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
804        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
805        defer { try? FileManager.default.removeItem(at: folder) }
806        try "[[file:/elsewhere/f.png]]\n".write(to: folder.appendingPathComponent("part.org"), atomically: true, encoding: .utf8)
807        #expect(ODTExport.imageFiles("#+INCLUDE: \"part.org\"\n", path: folder.appendingPathComponent("doc.org").path) == ["/elsewhere/f.png"])
808        let sub = folder.appendingPathComponent("sub")
809        try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true)
810        try "[[file:g.png]] [[https://x][file:../h.png]]\n".write(to: sub.appendingPathComponent("part.inc"), atomically: true, encoding: .utf8)
811        #expect(ODTExport.imageFiles("#+INCLUDE: \"sub/part.inc\"\n", path: folder.appendingPathComponent("doc.org").path)
812            == [sub.appendingPathComponent("g.png").path, folder.appendingPathComponent("h.png").path])
813    }
814
815    /// Every style `content.xml` names is in `styles.xml` or its automatic styles.
816    @Test func stylesDefined() throws {
817        let text = "#+OPTIONS: pri:t\n* TODO [#A] One\n* [#B] Two\n* DONE [#C] Three\n"
818        let parts = try ODTExport.parts(text, path: "/tmp/doc.org")
819        let content = String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
820        let styles = String(decoding: parts.first { $0.name == "styles.xml" }!.data, as: UTF8.self)
821        let used = Set(content.matches(of: /text:style-name="([^"]+)"/).map { String($0.1) })
822        #expect(used.isSuperset(of: ["OrgPriority-A", "OrgPriority-B", "OrgPriority-C"]))
823        for name in used {
824            #expect(styles.contains("style:name=\"\(name)\"") || content.contains("style:name=\"\(name)\""), "\(name)")
825        }
826    }
827}