Commit 7f51ed1c5b

7f51ed1c5bb357b57908fb3c2ef9d8b99b71bc4d

parent: 42d79206fc

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 17:53 UTC

Match ox-latex on tags not in the TOC, number cells, post-blank, empty containers and left-out link targets

Layout: unified · split

Sources/OrgCore/Export/LaTeXExport.swift +120 −21
@@ -7,6 +7,7 @@ import Foundation
7public enum LaTeXExport { 7public enum LaTeXExport {
8 public struct Unsupported: Error, LocalizedError, Equatable, CustomStringConvertible { 8 public struct Unsupported: Error, LocalizedError, Equatable, CustomStringConvertible {
9 public let reason: String 9 public let reason: String
10 public init(reason: String) { self.reason = reason }
10 public var errorDescription: String? { reason } 11 public var errorDescription: String? { reason }
11 public var description: String { reason } 12 public var description: String { reason }
12 } 13 }
@@ -131,6 +132,7 @@ final class LaTeXRenderer {
131 (numbered, num) = try depth("num") 132 (numbered, num) = try depth("num")
132 (withTOC, toc) = try depth("toc") 133 (withTOC, toc) = try depth("toc")
133 timeStampFile = items["timestamp"] != "nil" 134 timeStampFile = items["timestamp"] != "nil"
135 if let tex = items["tex"], tex != "t", tex != "nil" { throw Unsupported(reason: "#+OPTIONS: tex:\(tex)") }
134 for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "LATEX_CLASS_PRE", "LATEX_FOOTNOTE_COMMAND", "CALL", "EXPORT_LATEX_CLASS"] where keywords[key] != nil { 136 for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "LATEX_CLASS_PRE", "LATEX_FOOTNOTE_COMMAND", "CALL", "EXPORT_LATEX_CLASS"] where keywords[key] != nil {
135 throw Unsupported(reason: "#+\(key)") 137 throw Unsupported(reason: "#+\(key)")
136 } 138 }
@@ -533,6 +535,8 @@ final class LaTeXRenderer {
533 full += "\\framebox{\\#\(letter)} " 535 full += "\\framebox{\\#\(letter)} "
534 } 536 }
535 full += text 537 full += text
538 // The title for the table of contents, without the tags unless `tags` is t.
539 let tocTitle = (options.items["tags"] ?? "t") == "t" ? nil : full
536 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text { 540 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
537 let shown = tags.split(separator: ":").map(String.init) 541 let shown = tags.split(separator: ":").map(String.init)
538 if !shown.isEmpty { full += "\\hfill{}\\textsc{\(shown.map(Self.protect).joined(separator: ":"))}" } 542 if !shown.isEmpty { full += "\\hfill{}\\textsc{\(shown.map(Self.protect).joined(separator: ":"))}" }
@@ -553,7 +557,14 @@ final class LaTeXRenderer {
553 } 557 }
554 return out 558 return out
555 } 559 }
556 let format = isNumbered ? sections[level - 1].0 : sections[level - 1].1 560 var format = isNumbered ? sections[level - 1].0 : sections[level - 1].1
561 // A numbered section's title in the table of contents, when it differs.
562 if isNumbered, let tocTitle, tocTitle != full, let brace = format.firstIndex(of: "{") {
563 // Emacs puts it in a `format` string, where `%` is a directive.
564 if tocTitle.contains("%") { throw Unsupported(reason: "% in a heading with tags not in the table of contents") }
565 let optional = tocTitle.replacingOccurrences(of: "[", with: "(").replacingOccurrences(of: "]", with: ")")
566 format.insert(contentsOf: "[\(optional)]", at: brace)
567 }
557 return format.replacingOccurrences(of: "%s", with: full) + "\n" + label + pre + (contents ?? "") 568 return format.replacingOccurrences(of: "%s", with: full) + "\n" + label + pre + (contents ?? "")
558 } 569 }
559 570
@@ -602,11 +613,13 @@ final class LaTeXRenderer {
602 return try keyword(node) 613 return try keyword(node)
603 case .drawer: 614 case .drawer:
604 if drawerName(node).uppercased() == "LOGBOOK" { return nil } 615 if drawerName(node).uppercased() == "LOGBOOK" { return nil }
605 let inner = node.children 616 // `org-latex-format-drawer-default-function` gives nil for no contents.
606 return try wrapLabel(affiliated, Self.normalize(try elements(inner, end: node.range.upperBound))) 617 guard hasContents(node.children) else { return nil }
618 return try wrapLabel(affiliated, Self.normalize(try elements(node.children, end: node.range.upperBound)))
607 case .dynamicBlock: 619 case .dynamicBlock:
608 let lines = node.text.components(separatedBy: "\n") 620 let lines = node.text.components(separatedBy: "\n")
609 return try wrapLabel(affiliated, Self.normalize(try blocks(lines.dropFirst().dropLast(2).joined(separator: "\n")))) 621 guard let contents = try blockContents(lines.dropFirst().dropLast(2).joined(separator: "\n")) else { return nil }
622 return try wrapLabel(affiliated, Self.normalize(contents))
610 case .planning, .propertyDrawer, .clock, .footnoteDefinition, .nodeProperty: 623 case .planning, .propertyDrawer, .clock, .footnoteDefinition, .nodeProperty:
611 return nil 624 return nil
612 default: 625 default:
@@ -634,6 +647,33 @@ final class LaTeXRenderer {
634 return try elements(nodes, end: (text as NSString).length) 647 return try elements(nodes, end: (text as NSString).length)
635 } 648 }
636 649
650 /// `blocks`, or nil when `text` has no element the export keeps, where Emacs passes nil
651 /// contents.
652 func blockContents(_ text: String) throws -> String? {
653 let tree = OrgParser.parse(text, defaults: settings)
654 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
655 let saved = exportSource
656 exportSource = ExportSource(tree: tree, text: text)
657 defer { exportSource = saved }
658 guard hasContents(nodes) else { return nil }
659 return try blocks(text)
660 }
661
662 /// Whether `nodes` hold an element the export keeps.
663 private func hasContents(_ nodes: [SyntaxNode]) -> Bool {
664 nodes.contains { node in
665 switch node.kind {
666 case .comment, .affiliatedKeyword: return false
667 case .block:
668 let type = blockType(node)
669 if type == "comment" { return false }
670 if type == "src", exportSource.exports(at: node.range.lowerBound) == "none" { return false }
671 return !isResults(node)
672 default: return !pruned(node)
673 }
674 }
675 }
676
637 /// The text blank lines are counted in, when it isn't the document's. 677 /// The text blank lines are counted in, when it isn't the document's.
638 private var currentSource: NSString? 678 private var currentSource: NSString?
639 679
@@ -762,7 +802,7 @@ final class LaTeXRenderer {
762 out += ordered ? "{\(checkbox) \(tag)} " : "[{\(checkbox) \(tag)}] " 802 out += ordered ? "{\(checkbox) \(tag)} " : "[{\(checkbox) \(tag)}] "
763 } else if let label = checkbox ?? tag { 803 } else if let label = checkbox ?? tag {
764 out += ordered ? "{\(label)} " : "[{\(label)}] " 804 out += ordered ? "{\(label)} " : "[{\(label)}] "
765 } else if contents.firstMatch(of: /^[ \t]*\[/) != nil { 805 } else if contents.firstMatch(of: /^[ \t]*\[/) != nil, !Self.startsWithLaTeXSnippet(children.first) {
766 out += "\\relax " 806 out += "\\relax "
767 } else { 807 } else {
768 out += " " 808 out += " "
@@ -770,10 +810,24 @@ final class LaTeXRenderer {
770 return out + Self.trim(contents) 810 return out + Self.trim(contents)
771 } 811 }
772 812
813 /// Whether `node` is a paragraph whose first object is a `@@latex:…@@` snippet.
814 static func startsWithLaTeXSnippet(_ node: SyntaxNode?) -> Bool {
815 guard let node, node.kind == .paragraph else { return false }
816 for element in node.elements {
817 switch element {
818 case .token(let token):
819 if token.text.contains(where: { !$0.isWhitespace }) { return false }
820 case .node(let n):
821 return n.kind == .exportSnippet && n.text.hasPrefix("@@latex:")
822 }
823 }
824 return false
825 }
826
773 // MARK: Tables 827 // MARK: Tables
774 828
775 /// `org-table-number-regexp`. 829 /// `org-table-number-regexp`.
776 static let numberPattern = try! NSRegularExpression(pattern: "^(?:[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$") 830 static let numberPattern = try! NSRegularExpression(pattern: "^(?:[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$", options: .caseInsensitive)
777 831
778 private func table(_ node: SyntaxNode, affiliated: Affiliated) throws -> String { 832 private func table(_ node: SyntaxNode, affiliated: Affiliated) throws -> String {
779 let rows = node.children.filter { $0.kind == .tableRow } 833 let rows = node.children.filter { $0.kind == .tableRow }
@@ -922,11 +976,13 @@ final class LaTeXRenderer {
922 guard text.contains(where: { !$0.isWhitespace }) else { return nil } 976 guard text.contains(where: { !$0.isWhitespace }) else { return nil }
923 let environment = affiliated.value("environment") ?? "verbatim" 977 let environment = affiliated.value("environment") ?? "verbatim"
924 return try wrapLabel(affiliated, "\\begin{\(environment)}\n\(try formatCode(lines))\\end{\(environment)}") 978 return try wrapLabel(affiliated, "\\begin{\(environment)}\n\(try formatCode(lines))\\end{\(environment)}")
925 case "quote": 979 case "quote", "center":
980 // Emacs formats nil contents as `nil`. Blank lines alone are a paragraph of one newline.
981 let contents = body.isEmpty ? nil : body.allSatisfy({ $0.allSatisfy(\.isWhitespace) }) ? "\n" : try blockContents(text)
982 let inner = contents.map(Self.normalize) ?? "nil"
983 if type == "center" { return try wrapLabel(affiliated, "\\begin{center}\n\(inner)\\end{center}") }
926 let environment = affiliated.value("environment") ?? "quote" 984 let environment = affiliated.value("environment") ?? "quote"
927 return try wrapLabel(affiliated, "\\begin{\(environment)}\(affiliated.value("options") ?? "")\n\(Self.normalize(try blocks(text)))\\end{\(environment)}") 985 return try wrapLabel(affiliated, "\\begin{\(environment)}\(affiliated.value("options") ?? "")\n\(inner)\\end{\(environment)}")
928 case "center":
929 return try wrapLabel(affiliated, "\\begin{center}\n\(Self.normalize(try blocks(text)))\\end{center}")
930 case "verse": 986 case "verse":
931 if !affiliated.attr.isEmpty { throw Unsupported(reason: "#+ATTR_LATEX on verse blocks") } 987 if !affiliated.attr.isEmpty { throw Unsupported(reason: "#+ATTR_LATEX on verse blocks") }
932 return try wrapLabel(affiliated, try verse(unescaped)) 988 return try wrapLabel(affiliated, try verse(unescaped))
@@ -968,9 +1024,31 @@ final class LaTeXRenderer {
968 }.joined(separator: "\n") + "\n" 1024 }.joined(separator: "\n") + "\n"
969 } 1025 }
970 1026
1027 /// The src and example blocks the export writes, in order, as their lines: none under a
1028 /// section left out, with `:exports none`, or a src block's results.
1029 private lazy var exportedBlocks: [[String]] = {
1030 let source = ExportSource(tree: tree, text: self.source as String)
1031 return tree.root.descendants().filter { $0.kind == .block }.compactMap { node in
1032 var lines = node.text.components(separatedBy: "\n")
1033 if lines.last == "" { lines.removeLast() }
1034 guard Coderef.block(lines) != nil, !Self.excluded(node, by: self), !isResults(node) else { return nil }
1035 if blockType(node) == "src", source.exports(at: node.range.lowerBound) == "none" { return nil }
1036 return lines
1037 }
1038 }()
1039
1040 /// Whether `node` is the results of the src block before it, which the export removes.
1041 private func isResults(_ node: SyntaxNode) -> Bool {
1042 guard let siblings = node.parent?.children, let index = siblings.firstIndex(where: { $0.range == node.range }) else { return false }
1043 let keywords = siblings[..<index].reversed().prefix { $0.kind == .affiliatedKeyword }
1044 guard keywords.contains(where: { $0.text.firstMatch(of: /^[ \t]*#\+(?i:results)[\[:]/) != nil }) else { return false }
1045 let before = index - keywords.count - 1
1046 return before >= 0 && siblings[before].kind == .block && blockType(siblings[before]) == "src"
1047 }
1048
971 /// Each src and example block's `org-export-get-loc`, by the block's text, in order. 1049 /// Each src and example block's `org-export-get-loc`, by the block's text, in order.
972 private lazy var blockLocs: [String: [Int?]] = { 1050 private lazy var blockLocs: [String: [Int?]] = {
973 let blocks = Coderef.blocks(tree) 1051 let blocks = exportedBlocks
974 var locs: [String: [Int?]] = [:] 1052 var locs: [String: [Int?]] = [:]
975 for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) { 1053 for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) {
976 locs[lines.joined(separator: "\n"), default: []].append(loc) 1054 locs[lines.joined(separator: "\n"), default: []].append(loc)
@@ -1197,16 +1275,25 @@ final class LaTeXRenderer {
1197 var out = "" 1275 var out = ""
1198 var index = 0 1276 var index = 0
1199 var dropBlanks = false 1277 var dropBlanks = false
1278 // An object's post-blank, which Emacs writes as spaces.
1279 var afterObject = false
1200 while index < items.count { 1280 while index < items.count {
1201 let item = items[index] 1281 let item = items[index]
1202 switch item { 1282 switch item {
1203 case .text(var t): 1283 case .text(var t):
1204 if dropBlanks { t = String(t.drop { $0 == " " || $0 == "\t" }) } 1284 if dropBlanks {
1285 t = String(t.drop { $0 == " " || $0 == "\t" })
1286 } else if afterObject {
1287 let blanks = t.prefix { $0 == " " || $0 == "\t" }
1288 t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count)
1289 }
1205 dropBlanks = false 1290 dropBlanks = false
1291 afterObject = false
1206 out += plainText(t) 1292 out += plainText(t)
1207 index += 1 1293 index += 1
1208 case .object(let node, let children): 1294 case .object(let node, let children):
1209 dropBlanks = false 1295 dropBlanks = false
1296 afterObject = true
1210 if let math = mathValue(node) { 1297 if let math = mathValue(node) {
1211 var values = [math] 1298 var values = [math]
1212 var next = index + 1 1299 var next = index + 1
@@ -1222,7 +1309,7 @@ final class LaTeXRenderer {
1222 if var result = try object(node, children) { 1309 if var result = try object(node, children) {
1223 // `org-timestamp-translate` keeps the blanks after the timestamp. 1310 // `org-timestamp-translate` keeps the blanks after the timestamp.
1224 if node.kind == .timestamp, index + 1 < items.count, case .text(let t) = items[index + 1] { 1311 if node.kind == .timestamp, index + 1 < items.count, case .text(let t) = items[index + 1] {
1225 result = result.dropLast() + String(t.prefix { $0 == " " || $0 == "\t" }) + "}" 1312 result = result.dropLast() + String(repeating: " ", count: t.prefix { $0 == " " || $0 == "\t" }.count) + "}"
1226 } 1313 }
1227 out += result 1314 out += result
1228 } else { 1315 } else {
@@ -1486,7 +1573,7 @@ final class LaTeXRenderer {
1486 } 1573 }
1487 return "\\hyperref[\(label)]{\(description ?? title ?? "")}" 1574 return "\\hyperref[\(label)]{\(description ?? title ?? "")}"
1488 case "coderef": 1575 case "coderef":
1489 guard let resolved = Coderef.resolve(path, in: tree) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") } 1576 guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
1490 // `org-export-get-coderef-format` on the transcoded description, then `format`. 1577 // `org-export-get-coderef-format` on the transcoded description, then `format`.
1491 var format = description ?? "%s" 1578 var format = description ?? "%s"
1492 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") } 1579 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
@@ -1512,14 +1599,14 @@ final class LaTeXRenderer {
1512 /// The `<<target>>` a fuzzy link names. 1599 /// The `<<target>>` a fuzzy link names.
1513 private func target(_ path: String) -> String? { 1600 private func target(_ path: String) -> String? {
1514 let search = Self.words(path) 1601 let search = Self.words(path)
1515 return tree.root.descendants().first { $0.kind == .target && Self.words(String($0.text.dropFirst(2).dropLast(2))) == search } 1602 return tree.root.descendants().first { $0.kind == .target && Self.words(String($0.text.dropFirst(2).dropLast(2))) == search && !Self.excluded($0, by: self) }
1516 .map { String($0.text.dropFirst(2).dropLast(2)) } 1603 .map { String($0.text.dropFirst(2).dropLast(2)) }
1517 } 1604 }
1518 1605
1519 /// The label of the element whose `#+NAME` a fuzzy link names, as the element writes it. 1606 /// The label of the element whose `#+NAME` a fuzzy link names, as the element writes it.
1520 private func namedElement(_ path: String) -> String? { 1607 private func namedElement(_ path: String) -> String? {
1521 let search = path.split(whereSeparator: \.isWhitespace).map(String.init) 1608 let search = path.split(whereSeparator: \.isWhitespace).map(String.init)
1522 for node in tree.root.descendants() where node.kind == .affiliatedKeyword { 1609 for node in tree.root.descendants() where node.kind == .affiliatedKeyword && !Self.excluded(node, by: self) {
1523 guard let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { continue } 1610 guard let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { continue }
1524 let name = String(m.1) 1611 let name = String(m.1)
1525 let words = name.split(whereSeparator: \.isWhitespace).map(String.init) 1612 let words = name.split(whereSeparator: \.isWhitespace).map(String.init)
@@ -1541,16 +1628,26 @@ final class LaTeXRenderer {
1541 return nil 1628 return nil
1542 } 1629 }
1543 1630
1544 /// The heading a link goes to: by `CUSTOM_ID`, `ID` or title. 1631 /// The headings the export writes.
1632 private lazy var exportedHeadings: [HeadingInfo] = {
1633 let starts = Set(tree.root.descendants().filter { node in
1634 node.kind == .heading && HTMLRenderer.sectionExport(node, options: options, selected: selected) != .nothing
1635 && !(node.parent?.parent.map { Self.excluded($0, by: self) } ?? false)
1636 }.map(\.range.lowerBound))
1637 return model.headings.filter { starts.contains($0.headingRange.lowerBound) }
1638 }()
1639
1640 /// The exported heading a link goes to: by `CUSTOM_ID`, `ID` or title.
1545 private func resolveHeading(type: String, path: String) throws -> HeadingInfo? { 1641 private func resolveHeading(type: String, path: String) throws -> HeadingInfo? {
1642 let headings = exportedHeadings
1546 switch type { 1643 switch type {
1547 case "custom-id": 1644 case "custom-id":
1548 return model.headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } } 1645 return headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } }
1549 case "id": 1646 case "id":
1550 return model.headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } } 1647 return headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } }
1551 default: 1648 default:
1552 let search = Self.words(path.hasPrefix("*") ? String(path.dropFirst()) : path) 1649 let search = Self.words(path.hasPrefix("*") ? String(path.dropFirst()) : path)
1553 return model.headings.first { heading in 1650 return headings.first { heading in
1554 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound } 1651 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1555 let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ") 1652 let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ")
1556 return Self.words(raw) == search 1653 return Self.words(raw) == search
@@ -1711,7 +1808,8 @@ final class LaTeXRenderer {
1711 return try blocks(text) 1808 return try blocks(text)
1712 } 1809 }
1713 1810
1714 /// The object or text before `node` in its parent. 1811 /// The object before `node` in its parent, nil after text. Spaces and tabs after an object
1812 /// are its post-blank, not text.
1715 private func previousSibling(_ node: SyntaxNode) -> SyntaxNode? { 1813 private func previousSibling(_ node: SyntaxNode) -> SyntaxNode? {
1716 guard let parent = node.parent else { return nil } 1814 guard let parent = node.parent else { return nil }
1717 var previous: SyntaxNode.Element? 1815 var previous: SyntaxNode.Element?
@@ -1720,6 +1818,7 @@ final class LaTeXRenderer {
1720 if case .node(let p)? = previous { return p } 1818 if case .node(let p)? = previous { return p }
1721 return nil 1819 return nil
1722 } 1820 }
1821 if case .token(let t) = element, !t.text.isEmpty, t.text.allSatisfy({ $0 == " " || $0 == "\t" }), case .node? = previous { continue }
1723 previous = element 1822 previous = element
1724 } 1823 }
1725 return nil 1824 return nil
Sources/OrgCore/Links/Coderef.swift +6 −1
@@ -96,7 +96,12 @@ public enum Coderef {
96 /// `org-export-resolve-coderef`: the label, or its line's number for blocks that number 96 /// `org-export-resolve-coderef`: the label, or its line's number for blocks that number
97 /// lines instead; nil when no block has it. 97 /// lines instead; nil when no block has it.
98 public static func resolve(_ ref: String, in tree: OrgTree) -> String? { 98 public static func resolve(_ ref: String, in tree: OrgTree) -> String? {
99 let parsed = blocks(tree).compactMap(block) 99 resolve(ref, blocks: blocks(tree))
100 }
101
102 /// `resolve` among `blocks`, as their lines.
103 static func resolve(_ ref: String, blocks: [[String]]) -> String? {
104 let parsed = blocks.compactMap(block)
100 let locs = locs(parsed) 105 let locs = locs(parsed)
101 for (block, loc) in zip(parsed, locs) { 106 for (block, loc) in zip(parsed, locs) {
102 let lines = trimmedLines(block.body) 107 let lines = trimmedLines(block.body)
Tests/OrgCoreTests/LaTeXExportTests.swift +97
@@ -156,6 +156,28 @@ struct LaTeXExportTests {
156 "Plain LaTeX's own words and TeXbook.\n", 156 "Plain LaTeX's own words and TeXbook.\n",
157 "#+begin_example\nplain\n#+end_example\n\n#+begin_src sh -n\none\ntwo\n#+end_src\n\n#+begin_example\nplain\n#+end_example\n\n#+begin_src sh +n\nthree\n#+end_src\n", 157 "#+begin_example\nplain\n#+end_example\n\n#+begin_src sh -n\none\ntwo\n#+end_src\n\n#+begin_example\nplain\n#+end_example\n\n#+begin_src sh +n\nthree\n#+end_src\n",
158 "* Deep lists\n** two\n*** three\n**** four a\n**** COMMENT skipped\n**** four b :noexport:\n**** four c\n", 158 "* Deep lists\n** two\n*** three\n**** four a\n**** COMMENT skipped\n**** four b :noexport:\n**** four c\n",
159 "| NaN | a |\n| INF | b |\n| 2X | c |\n| -inf | d |\n",
160 "#+OPTIONS: tags:not-in-toc\n* TODO [#A] One [x] :a:b:\n* Two\n* Three :c:\n** Four :d:\n*** Five :e:\n**** Six :f:\n",
161 "#+OPTIONS: tags:not-in-toc num:nil pri:t\n* [#B] One :a:\n",
162 "* A :noexport:\n#+begin_src sh -n\na\nb\n#+end_src\n* B\n#+begin_src sh +n\nc\n#+end_src\n",
163 "#+begin_src sh -n :exports none\na\nb\n#+end_src\n\n#+begin_src sh +n\nc\n#+end_src\n",
164 "#+begin_src sh -n :exports code\na\n#+end_src\n\n#+RESULTS:\n#+begin_example\nr\ns\n#+end_example\n\n#+begin_src sh +n\nc\n#+end_src\n",
165 "* COMMENT A\n#+begin_src sh -n\na (ref:x)\n#+end_src\n* B\n#+begin_src sh -n -r\nb\nc (ref:x)\n#+end_src\nSee [[(x)]].\n",
166 "A[fn:1] [fn:2] b[fn:1]\t[fn:2] c[fn:1]\n [fn:2] d.\n\n[fn:1] One.\n\n[fn:2] Two.\n",
167 "- @@latex:[x]@@ foo\n- @@LaTeX:[x]@@ foo\n- @@tex:[x]@@ foo\n- @@latex:[x]@@ foo\n- x\n\n [a] b\n",
168 "#+begin_foo\n#+end_foo\n\n:DR:\n:END:\n\nb\n",
169 "a\n\n:DR:\n# c\n:END:\n\nb\n",
170 "a\n\n:DR:\n\n:END:\n\nb\n",
171 "a\n\n#+BEGIN: x\n#+END:\n\nb\n",
172 "a\n\n#+begin_quote\n#+end_quote\n\nb\n",
173 "a\n\n#+begin_quote\n\n#+end_quote\n\nb\n",
174 "a\n\n#+begin_quote\n# c\n#+end_quote\n\nb\n",
175 "a\n\n#+begin_center\n#+end_center\n\nb\n",
176 "#+NAME: n\n#+begin_quote\n#+end_quote\n",
177 "#+begin_center\n# c\n\n#+end_center\n\n#+begin_quote\n#+begin_src sh :exports none\nx\n#+end_src\n#+end_quote\n\n#+begin_quote\n#+FOO: t\n#+end_quote\n\n:DR:\n#+begin_comment\nc\n#+end_comment\n:END:\n\n:DR:\n#+begin_src sh\n#+end_src\n:END:\n\nend\n",
178 "a\n:DR:\n:END:\n\nb\n\na\n#+begin_src sh\n#+end_src\n\nb\n\na\n:DR:\n:END:\nb\n\na\n#+BEGIN: x\n#+END:\n\nb\n",
179 "*b*\tx =v=\t\ty \\alpha\tz [[https://a.b]]\tw x^2\tq $m$\tr <2024-01-15 Mon>\tt *b*\t\n",
180 "a @@html:x@@\tb a@@html:x@@\tb [fn::n]\t[fn::m] c\n",
159 ] 181 ]
160 182
161 @Test(.enabled(if: oracle)) 183 @Test(.enabled(if: oracle))
@@ -181,6 +203,77 @@ struct LaTeXExportTests {
181 try compare(cases, names: ["body", "blocks body", "subtree", "subtree from body", "subtree body"]) 203 try compare(cases, names: ["body", "blocks body", "subtree", "subtree from body", "subtree body"])
182 } 204 }
183 205
206 /// A subtree's `EXPORT_*` properties replace the file's keywords.
207 @Test(.enabled(if: oracle))
208 func subtreePropertiesMatchEmacs() throws {
209 let doc = """
210 #+TITLE: Doc
211 #+SUBTITLE: File sub
212 #+LATEX_CLASS: book
213 #+LATEX_CLASS_OPTIONS: [a4paper]
214 #+LATEX_HEADER: \\usepackage{tikz}
215 #+LATEX_HEADER_EXTRA: \\usepackage{amsthm}
216 #+LATEX_COMPILER: xelatex
217 #+KEYWORDS: k1
218 #+DESCRIPTION: d1
219 #+LANGUAGE: fr
220 #+EXCLUDE_TAGS: drop
221 * Top
222 :PROPERTIES:
223 :EXPORT_LATEX_CLASS: report
224 :EXPORT_LATEX_CLASS_OPTIONS: [12pt]
225 :EXPORT_LATEX_HEADER: \\usepackage{xcolor}
226 :EXPORT_LATEX_HEADER_EXTRA: \\usepackage{listings}
227 :EXPORT_LATEX_COMPILER: lualatex
228 :EXPORT_SUBTITLE: Sub
229 :EXPORT_KEYWORDS: k2
230 :EXPORT_DESCRIPTION: d2
231 :EXPORT_LANGUAGE: de
232 :EXPORT_EXCLUDE_TAGS: gone
233 :END:
234 Body.
235 ** Child
236 x
237 ** Dropped :gone:
238 z
239 ** Kept :drop:
240 w
241 * Other
242 :PROPERTIES:
243 :EXPORT_SUBTITLE: Only sub
244 :END:
245 y
246
247 """
248 let top = (doc as NSString).range(of: "Body.").location
249 let other = (doc as NSString).range(of: "\ny").location + 1
250 let cases = [
251 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(top, in: doc)),
252 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(other, in: doc)),
253 ]
254 try compare(cases, names: ["subtree properties", "subtree subtitle"])
255 }
256
257 /// Links to what the export leaves out stop both exports.
258 @Test(.enabled(if: oracle))
259 func abortsWhereEmacsAborts() throws {
260 let docs = [
261 "* A :noexport:\n* B\nSee [[*A]].\n",
262 "* A :noexport:\n:PROPERTIES:\n:CUSTOM_ID: a\n:END:\n* B\nSee [[#a]].\n",
263 "* COMMENT A\n* B\nSee [[*A]].\n",
264 "* A :noexport:\n** Inner\n* B\nSee [[*Inner]].\n",
265 "* A :noexport:\nA <<here>> target.\n* B\nSee [[here]].\n",
266 "* A :noexport:\n#+NAME: tbl\n| x |\n* B\nSee [[tbl]].\n",
267 "* A :noexport:\n#+begin_src sh -r\nx (ref:y)\n#+end_src\n* B\nSee [[(y)]].\n",
268 ]
269 let emacs = try LaTeXOracle.export(docs.map { LaTeXOracle.Case(text: $0) })
270 for (doc, theirs) in zip(docs, emacs) {
271 let ours = LaTeXOracle.native(LaTeXOracle.Case(text: doc))
272 #expect(theirs.hasPrefix("ERROR: "), "\(doc)\n--- emacs\n\(theirs)")
273 #expect(ours.hasPrefix("ERROR: Unable to resolve"), "\(doc)\n--- ours\n\(ours)")
274 }
275 }
276
184 private func compare(_ cases: [LaTeXOracle.Case], names: [String]) throws { 277 private func compare(_ cases: [LaTeXOracle.Case], names: [String]) throws {
185 let emacs = try LaTeXOracle.export(cases) 278 let emacs = try LaTeXOracle.export(cases)
186 for (index, c) in cases.enumerated() { 279 for (index, c) in cases.enumerated() {
@@ -221,6 +314,10 @@ struct LaTeXExportTests {
221 #expect(reason("#+LATEX_HEADER: \\usepackage[AUTO]{babel}\nx\n") != nil) 314 #expect(reason("#+LATEX_HEADER: \\usepackage[AUTO]{babel}\nx\n") != nil)
222 #expect(reason("#+begin_src sh :exports results\necho\n#+end_src\n") == ":exports results") 315 #expect(reason("#+begin_src sh :exports results\necho\n#+end_src\n") == ":exports results")
223 #expect(reason("[cite:@key]\n") == "Citations") 316 #expect(reason("[cite:@key]\n") == "Citations")
317 #expect(reason("#+OPTIONS: tex:verbatim\nMath \\(a_1\\).\n") == "#+OPTIONS: tex:verbatim")
318 let pre = "* Top\n:PROPERTIES:\n:EXPORT_LATEX_CLASS_PRE: \\x\n:END:\nBody.\n"
319 #expect(ExportScope.subtree(pre, at: 0).flatMap(reason) == "#+LATEX_CLASS_PRE")
320 #expect(reason("#+OPTIONS: tags:not-in-toc\n* 100% done :a:\n")?.hasPrefix("% in a heading") == true)
224 } 321 }
225 322
226 @Test func labelsStayTheSame() throws { 323 @Test func labelsStayTheSame() throws {