Commit f4b1fe8a56

f4b1fe8a56c6fef7f34d16e7b2e43844be3d2af2

parent: 170754362d

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 18:26 UTC

Match ox-odt on included links, blank src lines, local TOCs and Babel defaults

Rewrite relative file links in files included from another folder, as
org-export--update-included-link does, for export and for imageFiles.
Inline plain and angle file: image links. Empty whitespace-only lines in
src blocks without -i. Leave the title out of every local TOC. In ODT,
export the code of dot, latex, plantuml, ditaa, gnuplot and lilypond
blocks without :exports, as emacs -Q does.

Layout: unified · split

Sources/OrgCore/Compute/Babel.swift +4 −3
@@ -252,10 +252,11 @@ public enum Babel {
252 /// What export shows of the src block, `#+CALL:` line, inline call or inline src block 252 /// What export shows of the src block, `#+CALL:` line, inline call or inline src block
253 /// starting at `offset` (`org-babel-exp-process-buffer`): `code`, `results`, `both` or 253 /// starting at `offset` (`org-babel-exp-process-buffer`): `code`, `results`, `both` or
254 /// `none`, from the header arguments as evaluation resolves them. Calls never show code. 254 /// `none`, from the header arguments as evaluation resolves them. Calls never show code.
255 /// Nil when nothing there runs. 255 /// Nil when nothing there runs. Without `languages`, as in `emacs -Q`, no language's
256 public static func exports(at offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) -> String? { 256 /// `ob-` library is loaded to give its own default.
257 public static func exports(at offset: Int, tree: OrgTree, model: DocumentModel, text: NSString, languages: Bool = true) -> String? {
257 func value(_ params: Params?, language: String?) -> String { 258 func value(_ params: Params?, language: String?) -> String {
258 (params?.single[":exports"] ?? language.flatMap { languageExports[$0] } ?? "code").lowercased() 259 (params?.single[":exports"] ?? language.flatMap { languages ? languageExports[$0] : nil } ?? "code").lowercased()
259 } 260 }
260 if let block = model.srcBlocks.first(where: { $0.range.lowerBound == offset }) { 261 if let block = model.srcBlocks.first(where: { $0.range.lowerBound == offset }) {
261 return value(try? Params(block: block, model: model, text: text), language: block.language) 262 return value(try? Params(block: block, model: model, text: text), language: block.language)
Sources/OrgCore/Export/ExportOptions.swift +74 −2
@@ -118,7 +118,9 @@ public struct ExportOptions: Sendable, Equatable {
118public enum ExportPreprocess { 118public enum ExportPreprocess {
119 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with 119 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with
120 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`. 120 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`.
121 public static func includes(_ text: String, directory: URL?, depth: Int = 0) -> String { 121 /// `includer` is the exported file's directory, `directory` at the top.
122 public static func includes(_ text: String, directory: URL?, depth: Int = 0, includer: URL? = nil) -> String {
123 let includer = depth == 0 ? directory : includer
122 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text } 124 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text }
123 var lines: [String] = [] 125 var lines: [String] = []
124 for line in text.components(separatedBy: "\n") { 126 for line in text.components(separatedBy: "\n") {
@@ -159,10 +161,11 @@ public enum ExportPreprocess {
159 lines.append("#+END_\(kind)") 161 lines.append("#+END_\(kind)")
160 continue 162 continue
161 } 163 }
164 if let includer { included = rebasingLinks(included, from: url.deletingLastPathComponent(), to: includer) }
162 if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) { 165 if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) {
163 included = shift(included, to: minLevel) 166 included = shift(included, to: minLevel)
164 } 167 }
165 let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1) 168 let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1, includer: includer)
166 lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded) 169 lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded)
167 } 170 }
168 return lines.joined(separator: "\n") 171 return lines.joined(separator: "\n")
@@ -187,6 +190,75 @@ public enum ExportPreprocess {
187 return unreadable 190 return unreadable
188 } 191 }
189 192
193 /// `org-export--update-included-link`: the relative `file` links of a file in `directory`,
194 /// relative to `includer` instead. Links in descriptions too; `plain` for those, which
195 /// can only be plain or angle links.
196 static func rebasingLinks(_ text: String, from directory: URL, to includer: URL, plain: Bool = false) -> String {
197 guard plain || directory.resolvingSymlinksInPath().path != includer.resolvingSymlinksInPath().path else { return text }
198 let ns = text as NSString
199 var edits: [(range: Range<Int>, text: String)] = []
200 for node in OrgParser.parse(text).root.descendants() where node.kind == .link {
201 let whole = node.text
202 if whole.hasPrefix("[[") {
203 guard !plain else { continue }
204 if let description = node.firstChild(.linkDescription) {
205 let rebased = rebasingLinks(description.text, from: directory, to: includer, plain: true)
206 if rebased != description.text { edits.append((description.range, rebased)) }
207 }
208 if let path = node.tokens.first(where: { $0.kind == .linkPath }), let rebased = rebasedPath(path.text, from: directory, to: includer, bracket: true) {
209 edits.append((path.range, rebased))
210 }
211 } else if whole.hasPrefix("<"), whole.hasSuffix(">") {
212 if let rebased = rebasedPath(String(whole.dropFirst().dropLast()), from: directory, to: includer, bracket: false) {
213 edits.append((node.range, "<" + rebased + ">"))
214 }
215 } else if let rebased = rebasedPath(whole, from: directory, to: includer, bracket: false) {
216 edits.append((node.range, rebased))
217 }
218 }
219 guard !edits.isEmpty else { return text }
220 let out = NSMutableString(string: ns)
221 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
222 out.replaceCharacters(in: NSRange(location: edit.range.lowerBound, length: edit.range.count), with: edit.text)
223 }
224 return out as String
225 }
226
227 /// A link's path rewritten as `org-element-link-interpreter` writes it back: the type only
228 /// when it was written. Nil when it isn't a relative file link.
229 static func rebasedPath(_ raw: String, from directory: URL, to includer: URL, bracket: Bool) -> String? {
230 var type = ""
231 var rest = raw
232 if let m = raw.firstMatch(of: /^(file(?:\+[^:]+)?|[^:\/]+\+file):/) {
233 type = String(m.0)
234 rest = String(raw[m.0.endIndex...])
235 } else if !(bracket && ["/", "./", "../", "~"].contains(where: raw.hasPrefix)) {
236 return nil
237 }
238 var path = rest
239 var search = ""
240 if let r = rest.range(of: "::") {
241 path = String(rest[..<r.lowerBound])
242 search = String(rest[r.lowerBound...])
243 }
244 guard !path.hasPrefix("/"), !path.hasPrefix("~") else { return nil }
245 // `file-relative-name` of `expand-file-name`.
246 func components(_ path: String) -> [String] {
247 var out: [String] = []
248 for part in path.split(separator: "/", omittingEmptySubsequences: true) {
249 if part == "." { continue }
250 if part == ".." { if !out.isEmpty { out.removeLast() } } else { out.append(String(part)) }
251 }
252 return out
253 }
254 let target = components(directory.path + "/" + path)
255 let base = components(includer.path)
256 var common = 0
257 while common < min(target.count, base.count), target[common] == base[common] { common += 1 }
258 let relative = (Array(repeating: "..", count: base.count - common) + target[common...]).joined(separator: "/")
259 return type + (relative.isEmpty ? "." : relative) + search
260 }
261
190 /// An include's file, relative to `directory`. 262 /// An include's file, relative to `directory`.
191 static func includeURL(_ file: String, directory: URL?) -> URL { 263 static func includeURL(_ file: String, directory: URL?) -> URL {
192 (file as NSString).isAbsolutePath || directory == nil 264 (file as NSString).isAbsolutePath || directory == nil
Sources/OrgCore/Export/HTMLExport.swift +5 −2
@@ -112,14 +112,17 @@ final class ExportSource {
112 /// Whether the last inline src block or call lets the `{{{results(…)}}}` after it show; 112 /// Whether the last inline src block or call lets the `{{{results(…)}}}` after it show;
113 /// nil when nothing asks. 113 /// nil when nothing asks.
114 var inlineResults: Bool? 114 var inlineResults: Bool?
115 /// Whether the languages' own `:exports` defaults apply.
116 let languages: Bool
115 117
116 init(tree: OrgTree, text: String) { 118 init(tree: OrgTree, text: String, languages: Bool = true) {
117 self.tree = tree 119 self.tree = tree
118 self.text = text as NSString 120 self.text = text as NSString
121 self.languages = languages
119 } 122 }
120 123
121 func exports(at offset: Int) -> String? { 124 func exports(at offset: Int) -> String? {
122 Babel.exports(at: offset, tree: tree, model: model, text: text) 125 Babel.exports(at: offset, tree: tree, model: model, text: text, languages: languages)
123 } 126 }
124 127
125 /// `{{{results(…)}}}`, Org's `$1` macro, as the inline block or call before it allows: 128 /// `{{{results(…)}}}`, Org's `$1` macro, as the inline block or call before it allows:
Sources/OrgCore/Export/ODTExport.swift +23 −9
@@ -37,7 +37,7 @@ public enum ODTExport {
37 if let description = node.firstChild(.linkDescription) { 37 if let description = node.firstChild(.linkDescription) {
38 file = ODTRenderer.describedImage(description) 38 file = ODTRenderer.describedImage(description)
39 } else { 39 } else {
40 file = ODTRenderer.filePath(node.tokens.first { $0.kind == .linkPath }?.text ?? "").flatMap { ODTRenderer.isImage($0) ? $0 : nil } 40 file = ODTRenderer.linkPath(node).flatMap(ODTRenderer.filePath).flatMap { ODTRenderer.isImage($0) ? $0 : nil }
41 } 41 }
42 return file.map { ODTRenderer.expand($0, directory: directory).path } 42 return file.map { ODTRenderer.expand($0, directory: directory).path }
43 } 43 }
@@ -365,10 +365,11 @@ final class ODTRenderer {
365 365
366 private var source: ExportSource? 366 private var source: ExportSource?
367 367
368 /// `body` with `tree` as the source of `:exports`. 368 /// `body` with `tree` as the source of `:exports`. As in `emacs -Q`, which loads no `ob-`
369 /// library for dot, LaTeX and the like, their blocks export their code.
369 private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T { 370 private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
370 let saved = source 371 let saved = source
371 source = ExportSource(tree: tree, text: text) 372 source = ExportSource(tree: tree, text: text, languages: false)
372 defer { source = saved } 373 defer { source = saved }
373 return body() 374 return body()
374 } 375 }
@@ -428,7 +429,8 @@ final class ODTRenderer {
428 /// headings `org-export-excluded-from-toc-p` leaves out. 429 /// 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 /// 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 /// it's empty: every keyword is a TODO one.
431 private func toc(depth: Int, scope: Int?, template: Bool = false) -> String { 432 /// A `local` one has no title, even outside any heading.
433 private func toc(depth: Int, scope: Int?, local: Bool = false, template: Bool = false) -> String {
432 let limit = min(scope.flatMap { headings[$0].map { $0.relative + depth } } ?? depth, options.headlineLevels) 434 let limit = min(scope.flatMap { headings[$0].map { $0.relative + depth } } ?? depth, options.headlineLevels)
433 let keys = headingOrder.filter { key in 435 let keys = headingOrder.filter { key in
434 let heading = headings[key]! 436 let heading = headings[key]!
@@ -436,7 +438,7 @@ final class ODTRenderer {
436 return heading.relative <= limit && !excluded && (scope.map { heading.ancestors.contains($0) } ?? true) 438 return heading.relative <= limit && !excluded && (scope.map { heading.ancestors.contains($0) } ?? true)
437 } 439 }
438 guard !keys.isEmpty else { return "" } 440 guard !keys.isEmpty else { return "" }
439 let title = scope == nil ? ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8) : nil 441 let title = local ? nil : ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8)
440 var out = "\n<text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">\n" 442 var out = "\n<text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">\n"
441 out += " <text:table-of-content-source text:outline-level=\"\(depth)\">" 443 out += " <text:table-of-content-source text:outline-level=\"\(depth)\">"
442 if let title { out += "\n <text:index-title-template text:style-name=\"Contents_20_Heading\">\(Self.escape(title))</text:index-title-template>\n" } 444 if let title { out += "\n <text:index-title-template text:style-name=\"Contents_20_Heading\">\(Self.escape(title))</text:index-title-template>\n" }
@@ -639,7 +641,7 @@ final class ODTRenderer {
639 guard links.count == 1, node.children.count == 1, 641 guard links.count == 1, node.children.count == 1,
640 node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }), 642 node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }),
641 links[0].firstChild(.linkDescription) == nil, 643 links[0].firstChild(.linkDescription) == nil,
642 let file = Self.filePath(links[0].tokens.first { $0.kind == .linkPath }?.text ?? ""), Self.isImage(file) else { return nil } 644 let file = Self.linkPath(links[0]).flatMap(Self.filePath), Self.isImage(file) else { return nil }
643 return links[0] 645 return links[0]
644 } 646 }
645 647
@@ -654,7 +656,7 @@ final class ODTRenderer {
654 let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) } ?? options.headlineLevels 656 let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) } ?? options.headlineLevels
655 if value.range(of: ":target", options: .caseInsensitive) != nil { return fail("ODT export doesn't support #+TOC with :target") } 657 if value.range(of: ":target", options: .caseInsensitive) != nil { return fail("ODT export doesn't support #+TOC with :target") }
656 let local = value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil 658 let local = value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil
657 return toc(depth: depth, scope: local ? currentHeading() : nil) 659 return toc(depth: depth, scope: local ? currentHeading() : nil, local: local)
658 case "PRINT_BIBLIOGRAPHY": 660 case "PRINT_BIBLIOGRAPHY":
659 guard let citations else { return "" } 661 guard let citations else { return "" }
660 return citations.bibliography.map { "\n<text:p text:style-name=\"Text_20_body\">" + render($0) + "</text:p>" }.joined() 662 return citations.bibliography.map { "\n<text:p text:style-name=\"Text_20_body\">" + render($0) + "</text:p>" }.joined()
@@ -911,7 +913,11 @@ final class ODTRenderer {
911 let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? "" 913 let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? ""
912 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:] 914 let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
913 let language = parameters.split(whereSeparator: \.isWhitespace).first.map(String.init).flatMap { $0.hasPrefix("-") || $0.hasPrefix(":") ? nil : $0 } 915 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) 916 // Babel rewrites the block, which empties lines of only blanks unless `-i` keeps
917 // the indentation.
918 let preserve = Coderef.block(lines)?.switches.preserveIndent ?? false
919 let kept = preserve ? unescaped : unescaped.map { $0.allSatisfy { $0 == " " || $0 == "\t" } ? "" : $0 }
920 let formatted = numbered(lines, Self.dedent(kept), fontified: language.map(ODTSourceModes.fontified) ?? true)
915 if let textbox = attributes["textbox"], textbox != "nil" { 921 if let textbox = attributes["textbox"], textbox != "nil" {
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>" 922 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>"
917 } 923 }
@@ -1018,6 +1024,14 @@ final class ODTRenderer {
1018 private var imageCaption: String? 1024 private var imageCaption: String?
1019 private var imageAttributes: String? 1025 private var imageAttributes: String?
1020 1026
1027 /// A bracket link's path, or a plain or angle `file:` link's.
1028 static func linkPath(_ node: SyntaxNode) -> String? {
1029 if let token = node.tokens.first(where: { $0.kind == .linkPath }) { return token.text }
1030 var text = node.text
1031 if text.hasPrefix("<"), text.hasSuffix(">") { text = String(text.dropFirst().dropLast()) }
1032 return text.hasPrefix("file:") ? text : nil
1033 }
1034
1021 /// A link's file, for `file:` links and paths Org reads as files. 1035 /// A link's file, for `file:` links and paths Org reads as files.
1022 static func filePath(_ path: String) -> String? { 1036 static func filePath(_ path: String) -> String? {
1023 var file: String 1037 var file: String
@@ -1388,7 +1402,7 @@ final class ODTRenderer {
1388 } 1402 }
1389 1403
1390 private func link(_ node: SyntaxNode) -> String { 1404 private func link(_ node: SyntaxNode) -> String {
1391 let path = node.tokens.first { $0.kind == .linkPath }?.text 1405 let path = Self.linkPath(node)
1392 let descriptionNode = node.firstChild(.linkDescription) 1406 let descriptionNode = node.firstChild(.linkDescription)
1393 var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 } 1407 var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 }
1394 // `org-export-insert-image-links`: a description that is an image's path shows it. 1408 // `org-export-insert-image-links`: a description that is an image's path shows it.
Sources/OrgCore/Links/Coderef.swift +4
@@ -14,10 +14,13 @@ public enum Coderef {
14 public var retainLabels = true 14 public var retainLabels = true
15 public var useLabels = true 15 public var useLabels = true
16 public var labelFormat = Coderef.defaultFormat 16 public var labelFormat = Coderef.defaultFormat
17 /// `-i`.
18 public var preserveIndent = false
17 19
18 public static func == (a: Switches, b: Switches) -> Bool { 20 public static func == (a: Switches, b: Switches) -> Bool {
19 a.numberLines?.continued == b.numberLines?.continued && a.numberLines?.before == b.numberLines?.before 21 a.numberLines?.continued == b.numberLines?.continued && a.numberLines?.before == b.numberLines?.before
20 && a.retainLabels == b.retainLabels && a.useLabels == b.useLabels && a.labelFormat == b.labelFormat 22 && a.retainLabels == b.retainLabels && a.useLabels == b.useLabels && a.labelFormat == b.labelFormat
23 && a.preserveIndent == b.preserveIndent
21 } 24 }
22 25
23 public init(_ switches: String?) { 26 public init(_ switches: String?) {
@@ -30,6 +33,7 @@ public enum Coderef {
30 retainLabels = !r || (numberLines != nil && k) 33 retainLabels = !r || (numberLines != nil && k)
31 useLabels = retainLabels && !k 34 useLabels = retainLabels && !k
32 if let m = switches.firstMatch(of: /-l +"([^"\n]+)"/) { labelFormat = String(m.1) } 35 if let m = switches.firstMatch(of: /-l +"([^"\n]+)"/) { labelFormat = String(m.1) }
36 preserveIndent = switches.contains(/-i\b/)
33 } 37 }
34 } 38 }
35 39
Tests/OrgCoreTests/ODTExportTests.swift +87
@@ -451,6 +451,67 @@ struct ODTExportTests {
451 :END: 451 :END:
452 Shown. 452 Shown.
453 """, 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 """,
454 "all-drawers": """ 515 "all-drawers": """
455 #+OPTIONS: toc:nil d:t 516 #+OPTIONS: toc:nil d:t
456 * H 517 * H
@@ -505,6 +566,21 @@ struct ODTExportTests {
505 defer { try? FileManager.default.removeItem(at: folder) } 566 defer { try? FileManager.default.removeItem(at: folder) }
506 let picture = folder.appendingPathComponent("pic.png") 567 let picture = folder.appendingPathComponent("pic.png")
507 try Self.png(width: 64, height: 48).write(to: picture) 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)
508 var documents: [(name: String, text: String)] = [] 584 var documents: [(name: String, text: String)] = []
509 for name in Self.corpus { 585 for name in Self.corpus {
510 documents.append((name, try String(contentsOf: ExportTests.folder.appendingPathComponent("\(name).org"), encoding: .utf8))) 586 documents.append((name, try String(contentsOf: ExportTests.folder.appendingPathComponent("\(name).org"), encoding: .utf8)))
@@ -528,8 +604,14 @@ struct ODTExportTests {
528 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)") 604 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
529 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 605 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
530 defer { try? FileManager.default.removeItem(at: folder) } 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)
531 let documents = [ 612 let documents = [
532 "broken": "See [[nowhere]].\n", 613 "broken": "See [[nowhere]].\n",
614 "included-dot-link": "#+INCLUDE: \"sub/dot.inc\"\n",
533 "missing": "[[file:missing.png]]\n", 615 "missing": "[[file:missing.png]]\n",
534 "elements": try String(contentsOf: ExportTests.folder.appendingPathComponent("elements.org"), encoding: .utf8), 616 "elements": try String(contentsOf: ExportTests.folder.appendingPathComponent("elements.org"), encoding: .utf8),
535 ].sorted { $0.key < $1.key } 617 ].sorted { $0.key < $1.key }
@@ -626,6 +708,11 @@ struct ODTExportTests {
626 defer { try? FileManager.default.removeItem(at: folder) } 708 defer { try? FileManager.default.removeItem(at: folder) }
627 try "[[file:/elsewhere/f.png]]\n".write(to: folder.appendingPathComponent("part.org"), atomically: true, encoding: .utf8) 709 try "[[file:/elsewhere/f.png]]\n".write(to: folder.appendingPathComponent("part.org"), atomically: true, encoding: .utf8)
628 #expect(ODTExport.imageFiles("#+INCLUDE: \"part.org\"\n", path: folder.appendingPathComponent("doc.org").path) == ["/elsewhere/f.png"]) 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])
629 } 716 }
630 717
631 /// Every style `content.xml` names is in `styles.xml` or its automatic styles. 718 /// Every style `content.xml` names is in `styles.xml` or its automatic styles.
docs/manual/guide/12-export.org +3 −2
@@ -126,7 +126,7 @@ LaTeX fragments (=\(…\)=, =\[…\]=, =$…$=, =$$…$$=) and LaTeX environment
126| =:lines "5-10"= | Only those lines; either end may be left out. | 126| =:lines "5-10"= | Only those lines; either end may be left out. |
127| =:minlevel 2= | Shift the included headings so the shallowest is at that level. | 127| =:minlevel 2= | Shift the included headings so the shallowest is at that level. |
128 128
129A file that cannot be read is replaced by an empty line. 129A file that cannot be read is replaced by an empty line. In a file included as Org from another folder, relative =file:= links are rewritten relative to the Org file, as Org does: =[[file:pic.png]]= in =sub/part.org= becomes =[[file:sub/pic.png]]=. A link written without =file:=, such as =[[./pic.png]]=, comes back as =[[sub/pic.png]]=, which Org then reads as a link to a heading.
130 130
131** Macros 131** Macros
132 132
@@ -253,11 +253,12 @@ For Org's own ASCII layout, with underlined headings and drawn tables, use Expor
253Export to ODT writes an OpenDocument text file (=.odt=) for LibreOffice, Pages or Word. orgstar writes it itself, on the Mac and on iOS, the way Emacs's =ox-odt= does under =emacs -Q=: the same headings, paragraphs, lists, tables, links, notes and images, with ox-odt's style names, so a template that restyles ox-odt's output restyles this one too. 253Export to ODT writes an OpenDocument text file (=.odt=) for LibreOffice, Pages or Word. orgstar writes it itself, on the Mac and on iOS, the way Emacs's =ox-odt= does under =emacs -Q=: the same headings, paragraphs, lists, tables, links, notes and images, with ox-odt's style names, so a template that restyles ox-odt's output restyles this one too.
254 254
255- The title, subtitle (=#+SUBTITLE:=), author and date come first, then the table of contents and the text. On the Mac, without =#+AUTHOR:=, the author is your account's full name, as =user-full-name= is in Emacs. Without =#+TITLE:= there is no title. 255- The title, subtitle (=#+SUBTITLE:=), author and date come first, then the table of contents and the text. On the Mac, without =#+AUTHOR:=, the author is your account's full name, as =user-full-name= is in Emacs. Without =#+TITLE:= there is no title.
256- Headings are numbered by the word processor, to the depth =num= gives (=num:t= numbers every level). Headings deeper than =H= become list items. =#+TOC: headlines= puts a table of contents where it is; =local= limits it to the section and counts the depth from there. 256- Headings are numbered by the word processor, to the depth =num= gives (=num:t= numbers every level). Headings deeper than =H= become list items. =#+TOC: headlines= puts a table of contents where it is; =local= limits it to the section, counts the depth from there and leaves out the title.
257- Footnotes are the word processor's own notes, numbered as ox-odt numbers them: those referred to in the text first, then those referred to only from other notes. A note referred to again shows its number. 257- Footnotes are the word processor's own notes, numbered as ox-odt numbers them: those referred to in the text first, then those referred to only from other notes. A note referred to again shows its number.
258- Tables keep their header rows, alignment cookies, column groups and cell borders. A table inside a list item ends the list, sits indented below it, and the list carries on after it, as in ox-odt. 258- Tables keep their header rows, alignment cookies, column groups and cell borders. A table inside a list item ends the list, sits indented below it, and the list carries on after it, as in ox-odt.
259- Images from =file:= links (PNG, JPEG, GIF and SVG) are put inside the file. Their size is their pixels at 96 to the inch, or =#+ATTR_ODT: :width=, =:length= (the height) or =:scale=, and no more than 17 by 20 cm. A caption or =#+NAME:= numbers figures, tables and source blocks, and a link to the name shows the number. 259- Images from =file:= links (PNG, JPEG, GIF and SVG) are put inside the file. Their size is their pixels at 96 to the inch, or =#+ATTR_ODT: :width=, =:length= (the height) or =:scale=, and no more than 17 by 20 cm. A caption or =#+NAME:= numbers figures, tables and source blocks, and a link to the name shows the number.
260- LaTeX fragments and environments are kept as written, in code style, as ox-odt does without a MathML converter. Source blocks are not colored; a language Emacs has no mode for gets ox-odt's plain code style. 260- LaTeX fragments and environments are kept as written, in code style, as ox-odt does without a MathML converter. Source blocks are not colored; a language Emacs has no mode for gets ox-odt's plain code style.
261- Without =:exports=, every source block exports its code, =dot=, =plantuml=, =ditaa=, =gnuplot=, =latex= and =lilypond= included: =emacs -Q= loads no Babel library to give them =results=. A line of only spaces in a source block is exported empty, unless =-i= keeps the indentation.
261- Of the =#+OPTIONS=, =\n=, =f=, =|=, =e= and =d= (=t= or =nil=) are read, along with those every export reads. 262- Of the =#+OPTIONS=, =\n=, =f=, =|=, =e= and =d= (=t= or =nil=) are read, along with those every export reads.
262- =#+ODT:= lines, =#+BEGIN_EXPORT odt= blocks and =@@odt:...@@= snippets go in as they are. 263- =#+ODT:= lines, =#+BEGIN_EXPORT odt= blocks and =@@odt:...@@= snippets go in as they are.
263- The styles (=styles.xml=) are orgstar's own: A4 pages with 2 cm margins. =#+ODT_STYLES_FILE:= is not read. 264- The styles (=styles.xml=) are orgstar's own: A4 pages with 2 cm margins. =#+ODT_STYLES_FILE:= is not read.