| @@ -7,6 +7,7 @@ import Foundation |
| 7 | 7 | public enum LaTeXExport { |
| 8 | 8 | public struct Unsupported: Error, LocalizedError, Equatable, CustomStringConvertible { |
| 9 | 9 | public let reason: String |
| 10 | public init(reason: String) { self.reason = reason } |
| 10 | 11 | public var errorDescription: String? { reason } |
| 11 | 12 | public var description: String { reason } |
| 12 | 13 | } |
| @@ -131,6 +132,7 @@ final class LaTeXRenderer { |
| 131 | 132 | (numbered, num) = try depth("num") |
| 132 | 133 | (withTOC, toc) = try depth("toc") |
| 133 | 134 | timeStampFile = items["timestamp"] != "nil" |
| 135 | if let tex = items["tex"], tex != "t", tex != "nil" { throw Unsupported(reason: "#+OPTIONS: tex:\(tex)") } |
| 134 | 136 | for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "LATEX_CLASS_PRE", "LATEX_FOOTNOTE_COMMAND", "CALL", "EXPORT_LATEX_CLASS"] where keywords[key] != nil { |
| 135 | 137 | throw Unsupported(reason: "#+\(key)") |
| 136 | 138 | } |
| @@ -533,6 +535,8 @@ final class LaTeXRenderer { |
| 533 | 535 | full += "\\framebox{\\#\(letter)} " |
| 534 | 536 | } |
| 535 | 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 | 540 | if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text { |
| 537 | 541 | let shown = tags.split(separator: ":").map(String.init) |
| 538 | 542 | if !shown.isEmpty { full += "\\hfill{}\\textsc{\(shown.map(Self.protect).joined(separator: ":"))}" } |
| @@ -553,7 +557,14 @@ final class LaTeXRenderer { |
| 553 | 557 | } |
| 554 | 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 | 568 | return format.replacingOccurrences(of: "%s", with: full) + "\n" + label + pre + (contents ?? "") |
| 558 | 569 | } |
| 559 | 570 | |
| @@ -602,11 +613,13 @@ final class LaTeXRenderer { |
| 602 | 613 | return try keyword(node) |
| 603 | 614 | case .drawer: |
| 604 | 615 | if drawerName(node).uppercased() == "LOGBOOK" { return nil } |
| 605 | | let inner = node.children |
| 606 | | return try wrapLabel(affiliated, Self.normalize(try elements(inner, end: node.range.upperBound))) |
| 616 | // `org-latex-format-drawer-default-function` gives nil for no contents. |
| 617 | guard hasContents(node.children) else { return nil } |
| 618 | return try wrapLabel(affiliated, Self.normalize(try elements(node.children, end: node.range.upperBound))) |
| 607 | 619 | case .dynamicBlock: |
| 608 | 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 | 623 | case .planning, .propertyDrawer, .clock, .footnoteDefinition, .nodeProperty: |
| 611 | 624 | return nil |
| 612 | 625 | default: |
| @@ -634,6 +647,33 @@ final class LaTeXRenderer { |
| 634 | 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 | 677 | /// The text blank lines are counted in, when it isn't the document's. |
| 638 | 678 | private var currentSource: NSString? |
| 639 | 679 | |
| @@ -762,7 +802,7 @@ final class LaTeXRenderer { |
| 762 | 802 | out += ordered ? "{\(checkbox) \(tag)} " : "[{\(checkbox) \(tag)}] " |
| 763 | 803 | } else if let label = checkbox ?? tag { |
| 764 | 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 | 806 | out += "\\relax " |
| 767 | 807 | } else { |
| 768 | 808 | out += " " |
| @@ -770,10 +810,24 @@ final class LaTeXRenderer { |
| 770 | 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 | 827 | // MARK: Tables |
| 774 | 828 | |
| 775 | 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 | 832 | private func table(_ node: SyntaxNode, affiliated: Affiliated) throws -> String { |
| 779 | 833 | let rows = node.children.filter { $0.kind == .tableRow } |
| @@ -922,11 +976,13 @@ final class LaTeXRenderer { |
| 922 | 976 | guard text.contains(where: { !$0.isWhitespace }) else { return nil } |
| 923 | 977 | let environment = affiliated.value("environment") ?? "verbatim" |
| 924 | 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 | 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)}") |
| 928 | | case "center": |
| 929 | | return try wrapLabel(affiliated, "\\begin{center}\n\(Self.normalize(try blocks(text)))\\end{center}") |
| 985 | return try wrapLabel(affiliated, "\\begin{\(environment)}\(affiliated.value("options") ?? "")\n\(inner)\\end{\(environment)}") |
| 930 | 986 | case "verse": |
| 931 | 987 | if !affiliated.attr.isEmpty { throw Unsupported(reason: "#+ATTR_LATEX on verse blocks") } |
| 932 | 988 | return try wrapLabel(affiliated, try verse(unescaped)) |
| @@ -968,9 +1024,31 @@ final class LaTeXRenderer { |
| 968 | 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 | 1049 | /// Each src and example block's `org-export-get-loc`, by the block's text, in order. |
| 972 | 1050 | private lazy var blockLocs: [String: [Int?]] = { |
| 973 | | let blocks = Coderef.blocks(tree) |
| 1051 | let blocks = exportedBlocks |
| 974 | 1052 | var locs: [String: [Int?]] = [:] |
| 975 | 1053 | for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) { |
| 976 | 1054 | locs[lines.joined(separator: "\n"), default: []].append(loc) |
| @@ -1197,16 +1275,25 @@ final class LaTeXRenderer { |
| 1197 | 1275 | var out = "" |
| 1198 | 1276 | var index = 0 |
| 1199 | 1277 | var dropBlanks = false |
| 1278 | // An object's post-blank, which Emacs writes as spaces. |
| 1279 | var afterObject = false |
| 1200 | 1280 | while index < items.count { |
| 1201 | 1281 | let item = items[index] |
| 1202 | 1282 | switch item { |
| 1203 | 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 | 1290 | dropBlanks = false |
| 1291 | afterObject = false |
| 1206 | 1292 | out += plainText(t) |
| 1207 | 1293 | index += 1 |
| 1208 | 1294 | case .object(let node, let children): |
| 1209 | 1295 | dropBlanks = false |
| 1296 | afterObject = true |
| 1210 | 1297 | if let math = mathValue(node) { |
| 1211 | 1298 | var values = [math] |
| 1212 | 1299 | var next = index + 1 |
| @@ -1222,7 +1309,7 @@ final class LaTeXRenderer { |
| 1222 | 1309 | if var result = try object(node, children) { |
| 1223 | 1310 | // `org-timestamp-translate` keeps the blanks after the timestamp. |
| 1224 | 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 | 1314 | out += result |
| 1228 | 1315 | } else { |
| @@ -1486,7 +1573,7 @@ final class LaTeXRenderer { |
| 1486 | 1573 | } |
| 1487 | 1574 | return "\\hyperref[\(label)]{\(description ?? title ?? "")}" |
| 1488 | 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 | 1577 | // `org-export-get-coderef-format` on the transcoded description, then `format`. |
| 1491 | 1578 | var format = description ?? "%s" |
| 1492 | 1579 | if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") } |
| @@ -1512,14 +1599,14 @@ final class LaTeXRenderer { |
| 1512 | 1599 | /// The `<<target>>` a fuzzy link names. |
| 1513 | 1600 | private func target(_ path: String) -> String? { |
| 1514 | 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 | 1603 | .map { String($0.text.dropFirst(2).dropLast(2)) } |
| 1517 | 1604 | } |
| 1518 | 1605 | |
| 1519 | 1606 | /// The label of the element whose `#+NAME` a fuzzy link names, as the element writes it. |
| 1520 | 1607 | private func namedElement(_ path: String) -> String? { |
| 1521 | 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 | 1610 | guard let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { continue } |
| 1524 | 1611 | let name = String(m.1) |
| 1525 | 1612 | let words = name.split(whereSeparator: \.isWhitespace).map(String.init) |
| @@ -1541,16 +1628,26 @@ final class LaTeXRenderer { |
| 1541 | 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 | 1641 | private func resolveHeading(type: String, path: String) throws -> HeadingInfo? { |
| 1642 | let headings = exportedHeadings |
| 1546 | 1643 | switch type { |
| 1547 | 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 | 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 | 1648 | default: |
| 1552 | 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 | 1651 | let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound } |
| 1555 | 1652 | let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ") |
| 1556 | 1653 | return Self.words(raw) == search |
| @@ -1711,7 +1808,8 @@ final class LaTeXRenderer { |
| 1711 | 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 | 1813 | private func previousSibling(_ node: SyntaxNode) -> SyntaxNode? { |
| 1716 | 1814 | guard let parent = node.parent else { return nil } |
| 1717 | 1815 | var previous: SyntaxNode.Element? |
| @@ -1720,6 +1818,7 @@ final class LaTeXRenderer { |
| 1720 | 1818 | if case .node(let p)? = previous { return p } |
| 1721 | 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 | 1822 | previous = element |
| 1724 | 1823 | } |
| 1725 | 1824 | return nil |