Commit ebb9b1cc59

ebb9b1cc597c90a66e0e4c2795b9e185281f1161

parent: f5aa93a763

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 16:33 UTC

Native LaTeX export matching ox-latex

Layout: unified · split

Sources/OrgCore/Export/ExportOptions.swift +21 −3
@@ -33,6 +33,18 @@ public struct ExportOptions: Sendable, Equatable {
33 public var selectTags = ["export"] 33 public var selectTags = ["export"]
34 /// `#+HTML_HEAD` and `#+HTML_HEAD_EXTRA` lines, in order. 34 /// `#+HTML_HEAD` and `#+HTML_HEAD_EXTRA` lines, in order.
35 public var htmlHead: [String] = [] 35 public var htmlHead: [String] = []
36 /// `#+LATEX_CLASS`, the last one.
37 public var latexClass: String?
38 /// `#+LATEX_CLASS_OPTIONS`, the last one.
39 public var latexClassOptions: String?
40 /// `#+LATEX_HEADER` lines, in order.
41 public var latexHeader: [String] = []
42 /// `#+LATEX_HEADER_EXTRA` lines, in order.
43 public var latexHeaderExtra: [String] = []
44 /// `#+LATEX_COMPILER`, the first one.
45 public var latexCompiler: String?
46 /// Every `#+OPTIONS` item as written, the last value of each.
47 public var items: [String: String] = [:]
36 48
37 /// `org-export-with-*` defaults. 49 /// `org-export-with-*` defaults.
38 public static let org = ExportOptions(toc: 3, num: 3) 50 public static let org = ExportOptions(toc: 3, num: 3)
@@ -45,22 +57,28 @@ public struct ExportOptions: Sendable, Equatable {
45 return options 57 return options
46 }() 58 }()
47 59
48 /// `defaults` with the document's `#+OPTIONS`, `#+EXCLUDE_TAGS`, `#+SELECT_TAGS` and 60 /// `defaults` with the document's `#+OPTIONS`, `#+EXCLUDE_TAGS`, `#+SELECT_TAGS`,
49 /// `#+HTML_HEAD` applied. 61 /// `#+HTML_HEAD` and `#+LATEX_*` applied.
50 public static func parse(_ text: String, defaults: ExportOptions = .org) -> ExportOptions { 62 public static func parse(_ text: String, defaults: ExportOptions = .org) -> ExportOptions {
51 var options = defaults 63 var options = defaults
52 var tocSet: String? 64 var tocSet: String?
53 var numSet: String? 65 var numSet: String?
54 for m in text.matches(of: #/(?mi)^[ \t]*#\+(OPTIONS|EXCLUDE_TAGS|SELECT_TAGS|HTML_HEAD|HTML_HEAD_EXTRA):[ \t]*(.*?)[ \t]*$/#) { 66 for m in text.matches(of: #/(?mi)^[ \t]*#\+(OPTIONS|EXCLUDE_TAGS|SELECT_TAGS|HTML_HEAD|HTML_HEAD_EXTRA|LATEX_CLASS|LATEX_CLASS_OPTIONS|LATEX_HEADER|LATEX_HEADER_EXTRA|LATEX_COMPILER):[ \t]*(.*?)[ \t]*$/#) {
55 let value = String(m.2) 67 let value = String(m.2)
56 switch m.1.uppercased() { 68 switch m.1.uppercased() {
57 case "EXCLUDE_TAGS": options.excludeTags = value.split(whereSeparator: \.isWhitespace).map(String.init) 69 case "EXCLUDE_TAGS": options.excludeTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
58 case "SELECT_TAGS": options.selectTags = value.split(whereSeparator: \.isWhitespace).map(String.init) 70 case "SELECT_TAGS": options.selectTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
59 case "HTML_HEAD", "HTML_HEAD_EXTRA": options.htmlHead.append(value) 71 case "HTML_HEAD", "HTML_HEAD_EXTRA": options.htmlHead.append(value)
72 case "LATEX_CLASS": options.latexClass = value
73 case "LATEX_CLASS_OPTIONS": options.latexClassOptions = value
74 case "LATEX_HEADER": options.latexHeader.append(value)
75 case "LATEX_HEADER_EXTRA": options.latexHeaderExtra.append(value)
76 case "LATEX_COMPILER": if options.latexCompiler == nil { options.latexCompiler = value }
60 default: 77 default:
61 for item in value.matches(of: /(\S+?):(\S+)/) { 78 for item in value.matches(of: /(\S+?):(\S+)/) {
62 let key = String(item.1) 79 let key = String(item.1)
63 let v = String(item.2) 80 let v = String(item.2)
81 options.items[key] = v
64 let on = v != "nil" 82 let on = v != "nil"
65 switch key { 83 switch key {
66 case "toc": tocSet = v 84 case "toc": tocSet = v
Sources/OrgCore/Export/ExportScope.swift +7 −1
@@ -28,8 +28,14 @@ public enum ExportScope {
28 body = body.replacing(#/^(?:[ \t]*(?:SCHEDULED|DEADLINE|CLOSED):[^\n]*\n)?(?:[ \t]*:PROPERTIES:[ \t]*\n(?:[^\n]*\n)*?[ \t]*:END:[ \t]*(?:\n|$))?/#, with: "", maxReplacements: 1) 28 body = body.replacing(#/^(?:[ \t]*(?:SCHEDULED|DEADLINE|CLOSED):[^\n]*\n)?(?:[ \t]*:PROPERTIES:[ \t]*\n(?:[^\n]*\n)*?[ \t]*:END:[ \t]*(?:\n|$))?/#, with: "", maxReplacements: 1)
29 body = ExportPreprocess.shift(body, to: 1) 29 body = ExportPreprocess.shift(body, to: 1)
30 30
31 var lines = preamble(tree)
32 let property = { (key: String) in heading.properties.last { $0.key.uppercased() == key }?.value } 31 let property = { (key: String) in heading.properties.last { $0.key.uppercased() == key }?.value }
32 // The title, author and date the subtree sets replace the file's, which Org would
33 // otherwise join.
34 let replaced = Set(overrides.prefix(4).filter { $0.property == "EXPORT_TITLE" || property($0.property) != nil }.map(\.keyword))
35 var lines = preamble(tree).filter { line in
36 guard let m = line.firstMatch(of: #/^#\+([^:\s]+):/#) else { return true }
37 return !replaced.contains(m.1.uppercased())
38 }
33 lines.append("#+TITLE: " + (property("EXPORT_TITLE") ?? Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces))) 39 lines.append("#+TITLE: " + (property("EXPORT_TITLE") ?? Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces)))
34 for (key, keyword) in overrides where key != "EXPORT_TITLE" { 40 for (key, keyword) in overrides where key != "EXPORT_TITLE" {
35 if let value = property(key) { lines.append("#+\(keyword): \(value)") } 41 if let value = property(key) { lines.append("#+\(keyword): \(value)") }
Sources/OrgCore/Export/LaTeXExport.swift added +1733
@@ -0,0 +1,1733 @@
1import Foundation
2
3/// LaTeX export as ox-latex (Org 9.8.7) writes it under `emacs -Q`: the default packages,
4/// `article`, `report` or `book` sectioning, `verbatim` source blocks, `tabular` tables. What it
5/// can't write as Emacs would throws `Unsupported`, naming the construct, instead of writing
6/// something else. Labels are made from the document, where Emacs picks them at random.
7public enum LaTeXExport {
8 public struct Unsupported: Error, LocalizedError, Equatable {
9 public let reason: String
10 public var errorDescription: String? { reason }
11 }
12
13 /// `org-latex-classes`: each class's header and its sectioning, numbered and not.
14 static let classes: [String: (header: String, sections: [(String, String)])] = {
15 let part = ("\\part{%s}", "\\part*{%s}")
16 let chapter = ("\\chapter{%s}", "\\chapter*{%s}")
17 let section = ("\\section{%s}", "\\section*{%s}")
18 let subsection = ("\\subsection{%s}", "\\subsection*{%s}")
19 let subsubsection = ("\\subsubsection{%s}", "\\subsubsection*{%s}")
20 return [
21 "article": ("\\documentclass[11pt]{article}", [section, subsection, subsubsection, ("\\paragraph{%s}", "\\paragraph*{%s}"), ("\\subparagraph{%s}", "\\subparagraph*{%s}")]),
22 "report": ("\\documentclass[11pt]{report}", [part, chapter, section, subsection, subsubsection]),
23 "book": ("\\documentclass[11pt]{book}", [part, chapter, section, subsection, subsubsection]),
24 ]
25 }()
26
27 /// `org-latex-default-packages-alist`: options, package and the compilers it is for.
28 static let packages: [(String, String, [String])] = [
29 ("", "amsmath", ["lualatex", "xelatex"]), ("", "fontspec", ["lualatex", "xelatex"]),
30 ("utf8", "inputenc", ["pdflatex"]), ("T1", "fontenc", ["pdflatex"]),
31 ("", "graphicx", []), ("", "longtable", []), ("", "wrapfig", []), ("", "rotating", []), ("normalem", "ulem", []),
32 ("", "amsmath", ["pdflatex"]), ("", "amssymb", ["pdflatex"]), ("", "capt-of", []), ("", "hyperref", []),
33 ]
34
35 static let compilers = ["pdflatex", "xelatex", "lualatex"]
36
37 /// A `.tex` document, or with `bodyOnly` what goes between `\begin{document}` and
38 /// `\end{document}` without the title and contents. `author` stands for `user-full-name`,
39 /// `language` for `org-export-default-language`, `now` for the `% Created` line.
40 public static func document(
41 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
42 author: String = "", language: String = "en", timeZone: TimeZone = .current
43 ) throws -> String {
44 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
45 let included = ExportPreprocess.includes(text, directory: directory)
46 // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays.
47 let marker = "\u{E000}"
48 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") }
49 var literal = included
50 if included.contains("{{{") {
51 let ns = included as NSString
52 let kept = OrgParser.parse(included, defaults: settings).root.descendants()
53 .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range)
54 var out = ""
55 var at = 0
56 for range in kept.sorted(by: { $0.lowerBound < $1.lowerBound }) where range.lowerBound >= at {
57 out += ns.substring(with: NSRange(location: at, length: range.lowerBound - at))
58 out += ns.substring(with: NSRange(location: range.lowerBound, length: range.count)).replacingOccurrences(of: "{{{", with: marker + "{{")
59 at = range.upperBound
60 }
61 literal = out + ns.substring(from: at)
62 }
63 let text = ExportPreprocess.macros(literal, path: path, now: now, setup: settings.setupKeywords).replacingOccurrences(of: marker, with: "{")
64 let tree = OrgParser.parse(text, defaults: settings)
65 let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
66 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
67 let renderer = try LaTeXRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language)
68 let body = try renderer.body()
69 if bodyOnly { return body }
70 return try renderer.template(body, author: author, now: now, timeZone: timeZone)
71 }
72}
73
74final class LaTeXRenderer {
75 typealias Unsupported = LaTeXExport.Unsupported
76
77 let tree: OrgTree
78 let source: NSString
79 let settings: OrgSettings
80 let options: ExportOptions
81 /// Keyword values by name, in order.
82 let keywords: [String: [String]]
83 let language: String
84 let className: String
85 /// `num` and `toc` as written: nil for t.
86 let num: Int?
87 let numbered: Bool
88 let toc: Int?
89 let withTOC: Bool
90 let timeStampFile: Bool
91 private var selected: Set<Int>?
92 /// Added to heading levels.
93 private var levelOffset = 0
94 private var exportSource: ExportSource
95 private let model: DocumentModel
96
97 init(tree: OrgTree, text: String, settings: OrgSettings, keywords lines: [String], language: String) throws {
98 self.tree = tree
99 source = text as NSString
100 self.settings = settings
101 exportSource = ExportSource(tree: tree, text: text)
102 model = DocumentModel(tree: tree)
103 var keywords: [String: [String]] = [:]
104 for line in lines {
105 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { continue }
106 keywords[m.1.uppercased(), default: []].append(m.2.map(String.init) ?? "")
107 }
108 self.keywords = keywords
109 options = ExportOptions.parse(lines.joined(separator: "\n"))
110 self.language = keywords["LANGUAGE"]?.last ?? language
111 className = options.latexClass ?? "article"
112 guard LaTeXExport.classes[className] != nil else { throw Unsupported(reason: "Unknown LaTeX class `\(className)'") }
113
114 // `#+OPTIONS` this export follows; any other item only at its default.
115 let defaults = ["\\n": "nil", ":": "t", "*": "t", "e": "t", "f": "t", "|": "t", "p": "nil", "c": "nil", "prop": "nil",
116 "stat": "t", "tasks": "t", "inline": "t", "arch": "headline", "email": "nil", "creator": "nil",
117 "broken-links": "nil", "'": "nil", "<": "t", "d": "(not \"LOGBOOK\")", "latex-use-sans": "nil", "expand-links": "t"]
118 for (key, value) in options.items {
119 if let standard = defaults[key], standard != value { throw Unsupported(reason: "#+OPTIONS: \(key):\(value)") }
120 }
121 let items = options.items
122 func depth(_ key: String) throws -> (Bool, Int?) {
123 guard let v = items[key] else { return (true, nil) }
124 if v == "nil" { return (false, nil) }
125 if v == "t" { return (true, nil) }
126 guard let n = Int(v) else { throw Unsupported(reason: "#+OPTIONS: \(key):\(v)") }
127 return (true, n)
128 }
129 (numbered, num) = try depth("num")
130 (withTOC, toc) = try depth("toc")
131 timeStampFile = items["timestamp"] != "nil"
132 for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "LATEX_CLASS_PRE", "LATEX_FOOTNOTE_COMMAND", "CALL", "EXPORT_LATEX_CLASS"] where keywords[key] != nil {
133 throw Unsupported(reason: "#+\(key)")
134 }
135 for line in options.latexHeader + options.latexHeaderExtra + (options.latexClassOptions.map { [$0] } ?? [])
136 where line.contains("{babel}") || line.contains("{polyglossia}") || line.contains("\\babelprovide") || line.contains("[AUTO]") {
137 throw Unsupported(reason: "Babel or Polyglossia in the LaTeX header")
138 }
139 // Radio links: links that are only words.
140 if tree.root.descendants().contains(where: { $0.kind == .link && !$0.tokens.contains { $0.kind == .linkPath } && !$0.text.hasPrefix("<") && !$0.text.contains(":") }) {
141 throw Unsupported(reason: "Radio targets")
142 }
143 let kinds = Set(tree.root.descendants().map(\.kind))
144 for (kind, name) in [(SyntaxKind.radioTarget, "Radio targets"), (.citation, "Citations"), (.inlineTask, "Inline tasks"),
145 (.inlineSourceBlock, "Inline source blocks"), (.inlineBabelCall, "Inline calls"), (.tableEl, "table.el tables"),
146 (.diarySexp, "Diary sexps")] where kinds.contains(kind) {
147 throw Unsupported(reason: name)
148 }
149 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
150 // `:headline-offset`: the shallowest exported heading is level 1.
151 let options = options
152 let selected = selected
153 let top = tree.root.children.compactMap { $0.kind == .section ? $0.firstChild(.heading) : nil }
154 .filter { HTMLRenderer.sectionExport($0, options: options, selected: selected) != .nothing }
155 levelOffset = 1 - (top.compactMap { $0.tokens.first { $0.kind == .stars }?.text.count }.min() ?? 1)
156 try countFootnotes()
157 }
158
159 // MARK: - Template
160
161 /// `org-latex-template`.
162 func template(_ body: String, author: String, now: Date, timeZone: TimeZone) throws -> String {
163 var out = ""
164 if timeStampFile {
165 let formatter = DateFormatter()
166 formatter.locale = Locale(identifier: "en_US_POSIX")
167 formatter.timeZone = timeZone
168 formatter.dateFormat = "yyyy-MM-dd EEE HH:mm"
169 out += "% Created \(formatter.string(from: now))\n"
170 }
171 let compiler = options.latexCompiler ?? "pdflatex"
172 if LaTeXExport.compilers.contains(compiler) { out += "% Intended LaTeX compiler: \(compiler)\n" }
173 out += preamble(compiler: compiler)
174 if numbered, let num { out += "\\setcounter{secnumdepth}{\(num)}\n" }
175 var authorText: String? = try keywords["AUTHOR"].map { try parsed($0) } ?? (author.isEmpty ? nil : try inlineString(author))
176 if authorText?.isEmpty == true { authorText = nil }
177 if options.author, let authorText { out += "\\author{\(authorText)}\n" }
178 // The default, `\today`, is a LaTeX fragment, which `tex:nil` takes out.
179 let date = try keywords["DATE"].map { try parsed($0) } ?? (options.tex ? "\\today" : "")
180 out += "\\date{\(options.date ? date : "")}\n"
181 let title = try keywords["TITLE"].map { try parsed($0) } ?? ""
182 let subtitle = try keywords["SUBTITLE"].map { "\\\\\\medskip\n\\large " + (try parsed($0)) } ?? ""
183 out += "\\title{\(title)\(subtitle)}\n"
184 let lang = Self.languageNames[self.language] ?? self.language
185 out += "\\hypersetup{\n pdfauthor={\(options.author ? authorText ?? "" : "")},\n pdftitle={\(options.title ? title : "")},\n"
186 out += " pdfkeywords={\(try keywords["KEYWORDS"].map { try parsed($0) } ?? "")},\n"
187 out += " pdfsubject={\(try keywords["DESCRIPTION"].map { try parsed($0) } ?? "")},\n pdfcreator={},\n pdflang={\(Self.capitalize(lang))}}\n"
188 out += "\\begin{document}\n\n"
189 if options.title, !title.isEmpty { out += "\\maketitle\n" }
190 if withTOC {
191 if let toc { out += "\\setcounter{tocdepth}{\(toc)}\n" }
192 out += "\\tableofcontents\n\n"
193 }
194 return out + body + "\\end{document}"
195 }
196
197 /// A keyword parsed as Org text, its lines joined with spaces.
198 private func parsed(_ values: [String]) throws -> String {
199 try inlineString(values.joined(separator: " "))
200 }
201
202 /// `org-latex-make-preamble` with the class, its options and the header lines.
203 private func preamble(compiler: String) -> String {
204 var header = LaTeXExport.classes[className]!.header
205 if let classOptions = options.latexClassOptions {
206 header = header.replacingOccurrences(of: "[11pt]", with: classOptions)
207 }
208 let known = LaTeXExport.compilers.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame }
209 let packages = LaTeXExport.packages.filter { !known || $0.2.isEmpty || $0.2.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame } }
210 .map { $0.0.isEmpty ? "\\usepackage{\($0.1)}" : "\\usepackage[\($0.0)]{\($0.1)}" }
211 var out = header + "\n\n" + packages.joined(separator: "\n")
212 let extra = [options.latexHeader, options.latexHeaderExtra].filter { !$0.isEmpty }.map { Self.normalize($0.joined(separator: "\n")) }.joined()
213 if extra.contains(where: { !$0.isWhitespace }) { out += "\n" + extra }
214 return Self.normalize(out)
215 }
216
217 /// `:lang-name` in `org-latex-language-alist`.
218 static let languageNames: [String: String] = [
219 "af": "Afrikaans", "am": "Amharic", "ar": "Arabic", "ast": "Asturian", "bg": "Bulgarian", "bn": "Bengali", "bo": "Tibetan",
220 "br": "Breton", "ca": "Catalan", "cop": "Coptic", "cs": "Czech", "cy": "Welsh", "da": "Danish", "de": "German", "de-de": "German",
221 "de-at": "German", "dsb": "Lower Sorbian", "dv": "Dhivehi", "el": "Greek", "el-polyton": "Polytonic Greek", "grc": "Ancient Greek",
222 "en": "English", "en-au": "English", "en-ca": "English", "en-gb": "English", "en-nz": "English", "en-us": "English",
223 "eo": "Esperanto", "es": "Spanish", "es-mx": "Spanish", "et": "Estonian", "eu": "Basque", "fa": "Persian", "fi": "Finnish",
224 "fr": "French", "fr-ca": "French", "fur": "Friulian", "ga": "Irish Gaelic", "gd": "Scottish Gaelic", "gl": "Galician",
225 "he": "Hebrew", "hi": "Hindi", "hr": "Croatian", "hsb": "Upper Sorbian", "hu": "Magyar", "hy": "Armenian", "ia": "Interlingua",
226 "id": "Indonesian", "is": "Icelandic", "it": "Italian", "kn": "Kannada", "la": "Latin", "la-classic": "Classic Latin",
227 "la-medieval": "Medieval Latin", "la-ecclesiastic": "Ecclesiastic Latin", "lo": "Lao", "lt": "Lithuanian", "lv": "Latvian",
228 "ml": "Malayalam", "mr": "Marathi", "ms": "Malay", "nb": "Norwegian Bokmål", "nl": "Dutch", "nn": "Norwegian Nynorsk",
229 "no": "Norwegian", "oc": "Occitan", "pl": "Polish", "pms": "Piedmontese", "pt": "Portuges", "pt-br": "Portuges", "rm": "Romansh",
230 "ro": "Romanian", "ru": "Russian", "sa": "Sanskrit", "sk": "Slovak", "sl": "Slovene", "sq": "Albanian", "sr": "Serbian",
231 "sr-cyrl": "Serbian", "sr-latn": "Serbian", "sv": "Swedish", "syr": "Syriac", "ta": "Tamil", "te": "Telugu", "th": "Thai",
232 "tk": "Turkmen", "tr": "Turkish", "uk": "Ukrainian", "ur": "Urdu", "vi": "Vietnamese", "zh": "Chinese Simplified",
233 "zh-cn": "Chinese Simplified", "zh-tw": "Chinese Traditional",
234 ]
235
236 /// Emacs's `capitalize`: each word's first letter up, the rest down.
237 static func capitalize(_ s: String) -> String {
238 var out = ""
239 var inWord = false
240 for c in s {
241 let word = c.isLetter || c.isNumber
242 out += word ? (inWord ? c.lowercased() : c.uppercased()) : String(c)
243 inWord = word
244 }
245 return out
246 }
247
248 // MARK: - Strings
249
250 /// `org-element-normalize-string`: one final newline, none for the empty string.
251 static func normalize(_ s: String) -> String {
252 guard !s.isEmpty else { return "" }
253 var end = s.endIndex
254 var cut = s.endIndex
255 while end > s.startIndex {
256 let before = s.index(before: end)
257 if s[before] == " " || s[before] == "\t" {
258 end = before
259 } else if s[before] == "\n" {
260 end = before
261 cut = before
262 } else {
263 break
264 }
265 }
266 return String(s[..<cut]) + "\n"
267 }
268
269 /// `org-trim`.
270 static func trim(_ s: String) -> String { s.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r\u{0C}\u{0B}")) }
271
272 /// `org-latex--protect-text`.
273 static func protect(_ s: String) -> String {
274 var out = ""
275 for c in s {
276 if "\\{}$%&_#~^".contains(c) { out += "\\" }
277 out.append(c)
278 }
279 return out
280 }
281
282 /// `org-latex--protect-texttt`.
283 static func texttt(_ s: String) -> String {
284 var out = ""
285 var i = s.startIndex
286 while i < s.endIndex {
287 let rest = s[i...]
288 if rest.hasPrefix("--") || rest.hasPrefix("<<") || rest.hasPrefix(">>") {
289 out += "\(s[i]){}\(s[i]){}"
290 i = s.index(i, offsetBy: 2)
291 continue
292 }
293 switch s[i] {
294 case "\\": out += "\\textbackslash{}"
295 case "~": out += "\\textasciitilde{}"
296 case "^": out += "\\textasciicircum{}"
297 case "{", "}", "$", "%", "&", "_", "#": out += "\\\(s[i])"
298 default: out.append(s[i])
299 }
300 i = s.index(after: i)
301 }
302 return "\\texttt{\(out)}"
303 }
304
305 /// `org-remove-indentation`: the common indentation of the non-blank lines removed.
306 static func removeIndentation(_ s: String) throws -> String {
307 let lines = s.components(separatedBy: "\n")
308 let indents = lines.filter { $0.contains { $0 != " " && $0 != "\t" } }.map { $0.prefix { $0 == " " || $0 == "\t" } }
309 guard let common = indents.map(\.count).min(), common > 0 else { return s }
310 if indents.contains(where: { $0.contains("\t") }) { throw Unsupported(reason: "Tabs in indented code") }
311 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }.joined(separator: "\n")
312 }
313
314 // MARK: - Labels
315
316 private var references: [String: String] = [:]
317 private var usedReferences: Set<String> = []
318
319 /// `org-export-get-reference`: a label for `key`, made from it so it stays the same between
320 /// exports of the same document.
321 func reference(_ key: String) -> String {
322 if let existing = references[key] { return existing }
323 var hash: UInt32 = 2_166_136_261
324 for byte in key.utf8 { hash = (hash ^ UInt32(byte)) &* 16_777_619 }
325 var value = hash & 0xFFFFFFF
326 var label = String(format: "org%07x", value)
327 while usedReferences.contains(label) {
328 value = (value &+ 1) & 0xFFFFFFF
329 label = String(format: "org%07x", value)
330 }
331 usedReferences.insert(label)
332 references[key] = label
333 return label
334 }
335
336 // MARK: - Document
337
338 /// The transcoded document, `org-element-normalize-string`'d.
339 func body() throws -> String {
340 var nodes = tree.root.children
341 // With a select tag, the text before the first heading isn't exported.
342 if selected != nil { nodes.removeAll { $0.kind == .zerothSection } }
343 var out = ""
344 for node in nodes {
345 if node.kind == .zerothSection {
346 out += Self.normalize(try elements(node.children, end: node.range.upperBound))
347 } else if node.kind == .section {
348 out += try section(node) ?? ""
349 }
350 }
351 return Self.normalize(out)
352 }
353
354 /// Blank lines at the end of `source[from..<to]`.
355 func blankLines(from: Int, to: Int) -> Int {
356 guard to > from else { return 0 }
357 let source = currentSource ?? self.source
358 let lines = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)).components(separatedBy: "\n").dropLast()
359 return lines.reversed().prefix { $0.allSatisfy { $0 == " " || $0 == "\t" } }.count
360 }
361
362 /// Affiliated keywords of the element being transcoded.
363 struct Affiliated {
364 var caption: [String] = []
365 var name: String?
366 var attr: [String] = []
367 /// `#+RESULTS`' value, when it has the keyword.
368 var results: String?
369
370 /// `org-export-read-attribute :attr_latex`: values by key, nil for `nil` or nothing.
371 func attribute(_ key: String) -> String?? {
372 guard !attr.isEmpty else { return .none }
373 var s = attr.joined(separator: " ")
374 var pairs: [(String, String?)] = []
375 var pending: String?
376 let re = #/(?:^|[ \t]+)(:[-a-zA-Z0-9_]+)(?:[ \t]+|$)/#
377 while let m = s.firstMatch(of: re) {
378 if let pending { pairs.append((pending, Self.value(String(s[..<m.range.lowerBound])))) }
379 pending = String(m.1)
380 s = String(s[m.range.upperBound...])
381 }
382 if let pending { pairs.append((pending, Self.value(s))) }
383 guard let pair = pairs.first(where: { $0.0 == ":" + key }) else { return .none }
384 return .some(pair.1)
385 }
386
387 static func value(_ s: String) -> String? {
388 if s.isEmpty || s == "nil" { return nil }
389 if let m = s.wholeMatch(of: /"("+)?"/) { return m.1.map(String.init) ?? "" }
390 return s
391 }
392
393 /// The attribute's value, nil when absent or nil.
394 func value(_ key: String) -> String? { attribute(key) ?? nil }
395 func has(_ key: String) -> Bool { attribute(key) != nil }
396 }
397
398 /// `elements`, each `org-element-normalize-string`'d and followed by its blank lines, as
399 /// `org-export-data` joins a greater element's contents.
400 func elements(_ nodes: [SyntaxNode], end: Int) throws -> String {
401 var out = ""
402 var affiliated = Affiliated()
403 // The element before and its blank lines, which a comment after it may add to; they
404 // show only when it wrote something.
405 var pendingBlank = 0
406 var previous: SyntaxNode?
407 var previousWrote = false
408 var afterSrc = false
409 for (index, node) in nodes.enumerated() {
410 let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
411 if node.kind == .affiliatedKeyword {
412 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
413 guard let m = line.firstMatch(of: /^#\+([A-Za-z_]+)(\[[^\]]*\])?:[ \t]*(.*)$/) else { continue }
414 let key = m.1.uppercased()
415 if m.2 != nil, key != "CAPTION", key != "RESULTS" { throw Unsupported(reason: "#+\(key)[…]") }
416 switch key {
417 case "CAPTION":
418 if m.2 != nil { throw Unsupported(reason: "Short captions") }
419 affiliated.caption.append(String(m.3))
420 case "NAME": affiliated.name = String(m.3)
421 case "ATTR_LATEX": affiliated.attr.append(String(m.3))
422 case "RESULTS": affiliated.results = String(m.3)
423 default: break
424 }
425 continue
426 }
427 defer { affiliated = Affiliated() }
428 // `org-babel-exp-process-buffer`: a src block's results go, and with `:exports none`
429 // the block too, as if they had never been there.
430 if node.kind == .block, blockType(node) == "src" {
431 let exports = exportSource.exports(at: node.range.lowerBound) ?? "code"
432 if exports != "code", exports != "none" { throw Unsupported(reason: ":exports \(exports)") }
433 afterSrc = true
434 if exports == "none" { continue }
435 } else if let results = affiliated.results {
436 if afterSrc {
437 afterSrc = false
438 continue
439 }
440 if results.isEmpty { throw Unsupported(reason: "#+RESULTS without a source block") }
441 if affiliated.name == nil { affiliated.name = results }
442 } else {
443 afterSrc = false
444 }
445 if node.kind == .comment || (node.kind == .block && blockType(node) == "comment") {
446 // `org-export--skip-p`: the element before keeps at least one blank line.
447 if previous != nil {
448 let blank = max(pendingBlank, blankLines(from: node.range.lowerBound, to: next), 1)
449 if previousWrote { out += String(repeating: "\n", count: blank - pendingBlank) }
450 pendingBlank = blank
451 }
452 continue
453 }
454 guard let result = try element(node, affiliated: affiliated, previous: previous, previousBlank: pendingBlank) else {
455 if !pruned(node) {
456 previous = node
457 previousWrote = false
458 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
459 }
460 continue
461 }
462 previous = node
463 previousWrote = true
464 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
465 var text = Self.normalize(result) + String(repeating: "\n", count: pendingBlank)
466 if node.kind == .paragraph { text = Self.cleanLineBreaks(text) }
467 out += text
468 }
469 return out
470 }
471
472 /// Elements `org-export--prune-tree` takes out of the tree.
473 private func pruned(_ node: SyntaxNode) -> Bool {
474 switch node.kind {
475 case .planning, .propertyDrawer, .clock, .footnoteDefinition: return true
476 case .drawer: return drawerName(node).uppercased() == "LOGBOOK"
477 case .latexEnvironment: return !options.tex
478 default: return false
479 }
480 }
481
482 private func drawerName(_ node: SyntaxNode) -> String {
483 node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1) } ?? ""
484 }
485
486 /// `org-latex-clean-invalid-line-breaks`.
487 static func cleanLineBreaks(_ s: String) -> String {
488 s.replacing(#/(?m)(\\end\{[A-Za-z0-9*]+\}|^)[ \t]*\\\\[ \t]*$/#) { String($0.1) }
489 }
490
491 // MARK: - Headlines
492
493 /// A section's heading and contents, nil when not exported.
494 private func section(_ node: SyntaxNode) throws -> String? {
495 guard let heading = node.firstChild(.heading) else { return nil }
496 // `org-footnote-section`'s heading isn't exported.
497 if heading.firstChild(.title)?.text == "Footnotes" { return nil }
498 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
499 if export == .nothing { return nil }
500 let children = node.children.filter { $0.kind != .heading }
501 let body = children.filter { $0.kind != .section }
502 let subsections = children.filter { $0.kind == .section }
503 var contents: String?
504 if export == .all {
505 var out = Self.normalize(try elements(body, end: subsections.first?.range.lowerBound ?? node.range.upperBound))
506 let exported = try subsections.compactMap { try section($0) }
507 for (index, sub) in exported.enumerated() {
508 out += sub
509 _ = index
510 }
511 contents = Self.normalize(out)
512 }
513 let first = children.first?.range.lowerBound ?? node.range.upperBound
514 let preBlank = children.isEmpty ? 0 : blankLines(from: heading.range.lowerBound, to: first)
515 return Self.normalize(try headline(heading, section: node, contents: contents, preBlank: preBlank))
516 }
517
518 /// `org-latex-headline`.
519 private func headline(_ heading: SyntaxNode, section: SyntaxNode, contents: String?, preBlank: Int) throws -> String {
520 let tokens = heading.tokens
521 let level = (tokens.first { $0.kind == .stars }?.text.count ?? 1) + levelOffset
522 if let index = model.headings.firstIndex(where: { $0.headingRange.lowerBound == heading.range.lowerBound }) {
523 let keys = model.headings[index].properties.map { $0.key.uppercased() }
524 if keys.contains("UNNUMBERED") || keys.contains("ALT_TITLE") { throw Unsupported(reason: "UNNUMBERED and ALT_TITLE properties") }
525 }
526 let isNumbered = numbered && (num.map { level <= $0 } ?? true)
527 let titleNode = heading.firstChild(.title)
528 if titleNode?.descendants().contains(where: { $0.kind == .footnoteReference }) == true { throw Unsupported(reason: "Footnotes in headings") }
529 let text = try titleNode.map { try Self.trim(inline($0, sectionTitle: true)) } ?? ""
530 var full = ""
531 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
532 full += "{\\bfseries\\sffamily \(plainText(todo))} "
533 }
534 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text,
535 let letter = priority.firstMatch(of: /\[#(.+)\]/)?.1 {
536 full += "\\framebox{\\#\(letter)} "
537 }
538 full += text
539 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
540 let shown = tags.split(separator: ":").map(String.init)
541 if !shown.isEmpty { full += "\\hfill{}\\textsc{\(shown.map(Self.protect).joined(separator: ":"))}" }
542 }
543 let label = "\\label{sec:\(reference("heading@\(heading.range.lowerBound)"))}\n"
544 let pre = String(repeating: "\n", count: preBlank)
545 let sections = LaTeXExport.classes[className]!.sections
546 if level > options.headlineLevels || level > sections.count {
547 let siblings = exportedSiblings(section)
548 let first = siblings.first == section.range.lowerBound
549 let last = siblings.last == section.range.lowerBound
550 let list = isNumbered ? "enumerate" : "itemize"
551 var out = first ? "\\begin{\(list)}\n" : ""
552 out += "\\item" + (full.firstMatch(of: /^[ \t]*\[/) != nil ? "\\relax" : "") + " " + full + "\n" + label + pre + (contents ?? "")
553 if last {
554 while let c = out.last, c == " " || c == "\t" || c == "\n" { out.removeLast() }
555 out += "\n\\end{\(list)}"
556 }
557 return out
558 }
559 let format = isNumbered ? sections[level - 1].0 : sections[level - 1].1
560 return format.replacingOccurrences(of: "%s", with: full) + "\n" + label + pre + (contents ?? "")
561 }
562
563 /// The headline sections exported beside `section` at its level, by start: a low-level
564 /// headline opens its list when it is the first and closes it when it is the last.
565 private func exportedSiblings(_ section: SyntaxNode) -> [Int] {
566 guard let parent = section.parent else { return [section.range.lowerBound] }
567 // A section with a body before it means the headline isn't first.
568 var starts: [Int] = []
569 var bodyBefore = false
570 for child in parent.children where child.kind != .heading {
571 if child.kind != .section {
572 if starts.isEmpty { bodyBefore = true }
573 continue
574 }
575 guard let heading = child.firstChild(.heading), HTMLRenderer.sectionExport(heading, options: options, selected: selected) != .nothing else { continue }
576 starts.append(child.range.lowerBound)
577 }
578 _ = bodyBefore
579 return starts
580 }
581
582 // MARK: - Elements
583
584 private func blockType(_ node: SyntaxNode) -> String {
585 node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/).map { $0.1.lowercased() } ?? ""
586 }
587
588 /// One element's transcoding, nil for none.
589 private func element(_ node: SyntaxNode, affiliated: Affiliated, previous: SyntaxNode?, previousBlank: Int) throws -> String? {
590 switch node.kind {
591 case .paragraph:
592 return try paragraph(node, affiliated: affiliated)
593 case .plainList:
594 return try list(node, affiliated: affiliated)
595 case .table:
596 return try table(node, affiliated: affiliated)
597 case .block:
598 return try block(node, affiliated: affiliated)
599 case .horizontalRule:
600 var out = previous != nil && previousBlank == 0 ? "\n" : ""
601 out += try wrapLabel(affiliated, "\\noindent\\rule{\(affiliated.value("width") ?? "\\textwidth")}{\(affiliated.value("thickness") ?? "0.5pt")}")
602 return out
603 case .fixedWidth:
604 let value = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }
605 .map { $0.replacingOccurrences(of: "^[ \\t]*: ?", with: "", options: .regularExpression) }.joined(separator: "\n")
606 return try wrapLabel(affiliated, "\\begin{verbatim}\n\(try Self.removeIndentation(value))\n\\end{verbatim}")
607 case .latexEnvironment:
608 guard options.tex else { return nil }
609 if affiliated.name != nil || !affiliated.caption.isEmpty { throw Unsupported(reason: "Named or captioned LaTeX environments") }
610 var value = node.text
611 while value.hasSuffix("\n") { value.removeLast() }
612 return try Self.removeIndentation(value) + "\n"
613 case .keyword:
614 return try keyword(node)
615 case .drawer:
616 if drawerName(node).uppercased() == "LOGBOOK" { return nil }
617 let inner = node.children
618 return try wrapLabel(affiliated, Self.normalize(try elements(inner, end: node.range.upperBound)))
619 case .dynamicBlock:
620 let lines = node.text.components(separatedBy: "\n")
621 return try wrapLabel(affiliated, Self.normalize(try blocks(lines.dropFirst().dropLast(2).joined(separator: "\n"))))
622 case .planning, .propertyDrawer, .clock, .footnoteDefinition, .nodeProperty:
623 return nil
624 default:
625 throw Unsupported(reason: "\(node.kind)")
626 }
627 }
628
629 /// `org-latex--wrap-label`.
630 private func wrapLabel(_ affiliated: Affiliated, _ output: String) throws -> String {
631 guard let name = affiliated.name, output.contains(where: { !$0.isWhitespace }) else { return output }
632 return "\\phantomsection\n\\label{\(reference("name:" + name))}\n" + output
633 }
634
635 /// Org text parsed and transcoded as elements.
636 func blocks(_ text: String) throws -> String {
637 let tree = OrgParser.parse(text, defaults: settings)
638 let saved = exportSource
639 exportSource = ExportSource(tree: tree, text: text)
640 defer { exportSource = saved }
641 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
642 if nodes.contains(where: { $0.kind == .section }) { throw Unsupported(reason: "Headings inside blocks") }
643 let saveSource = currentSource
644 currentSource = text as NSString
645 defer { currentSource = saveSource }
646 return try elements(nodes, end: (text as NSString).length)
647 }
648
649 /// The text blank lines are counted in, when it isn't the document's.
650 private var currentSource: NSString?
651
652 private func keyword(_ node: SyntaxNode) throws -> String? {
653 let line = node.text.trimmingCharacters(in: .newlines)
654 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { return nil }
655 let value = m.2.map(String.init) ?? ""
656 switch m.1.uppercased() {
657 case "LATEX": return value
658 case "INDEX": return "\\index{\(value)}"
659 case "TOC":
660 if value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil { throw Unsupported(reason: "#+TOC: local") }
661 if value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil {
662 let depth = value.firstMatch(of: /\b([0-9]+)\b/).map { "\\setcounter{tocdepth}{\($0.1)}\n" } ?? ""
663 return depth + "\\tableofcontents"
664 }
665 if value.range(of: "\\btables\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\listoftables" }
666 if value.range(of: "\\blistings\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\lstlistoflistings" }
667 return nil
668 default: return nil
669 }
670 }
671
672 // MARK: Paragraphs
673
674 private func paragraph(_ node: SyntaxNode, affiliated: Affiliated, ignoreFirst: Bool = false) throws -> String {
675 var items = Self.normalizeIndentation(try inlineItems(node), ignoreFirst: ignoreFirst)
676 if let image = soleImage(items) {
677 items = []
678 return try inlineImage(image, affiliated: affiliated, alone: true)
679 }
680 if items.contains(where: { if case .object(let n, _) = $0, n.kind == .link, isImage(n) { return true } else { return false } }) {
681 currentAffiliated = affiliated
682 defer { currentAffiliated = nil }
683 return Self.removeBlankLines(try transcode(items))
684 }
685 if !affiliated.caption.isEmpty { throw Unsupported(reason: "Captioned paragraphs") }
686 return Self.removeBlankLines(try transcode(items))
687 }
688
689 private var currentAffiliated: Affiliated?
690
691 /// `org-remove-blank-lines`.
692 static func removeBlankLines(_ s: String) -> String {
693 s.replacing(#/\n(?:[ \t]*\n)+/#, with: "\n")
694 }
695
696 // MARK: Lists
697
698 private func isOrderedBullet(_ item: SyntaxNode) -> Bool {
699 let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
700 return bullet.first.map { $0.isASCII && ($0.isLetter || $0.isNumber) } ?? false
701 }
702
703 /// `org-latex-plain-list`, its type from the first item.
704 private func list(_ node: SyntaxNode, affiliated: Affiliated, orderedDepth: Int = 0) throws -> String {
705 let items = node.children.filter { $0.kind == .item }
706 guard let first = items.first else { return "" }
707 let ordered = isOrderedBullet(first)
708 let description = !ordered && first.firstChild(.itemTag) != nil
709 let type = affiliated.value("environment") ?? (ordered ? "enumerate" : description ? "description" : "itemize")
710 let depth = orderedDepth + (ordered ? 1 : 0)
711 var contents = ""
712 for (index, item) in items.enumerated() {
713 let next = index + 1 < items.count ? items[index + 1].range.lowerBound : node.range.upperBound
714 let text = try self.item(item, ordered: ordered, depth: depth)
715 contents += Self.normalize(text) + String(repeating: "\n", count: blankLines(from: item.range.lowerBound, to: next))
716 }
717 return try wrapLabel(affiliated, "\\begin{\(type)}\(affiliated.value("options") ?? "")\n\(Self.normalize(contents))\\end{\(type)}")
718 }
719
720 private var listDepth = 0
721
722 /// `org-latex-item`.
723 private func item(_ item: SyntaxNode, ordered: Bool, depth: Int) throws -> String {
724 var counter = ""
725 if let value = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+)/) {
726 guard ordered, depth < 5, let n = Int(value.1) else { throw Unsupported(reason: "Counters outside ordered lists") }
727 counter = "\\setcounter{enum\(["i", "ii", "iii", "iv"][depth - 1])}{\(n - 1)}\n"
728 } else if item.tokens.contains(where: { $0.kind == .counter }) {
729 throw Unsupported(reason: "Alphabetical counters")
730 }
731 let checkbox: String? = item.tokens.first { $0.kind == .checkbox }.map {
732 switch $0.text.uppercased() {
733 case "[X]": "$\\boxtimes$"
734 case "[-]": "$\\boxminus$"
735 default: "$\\square$"
736 }
737 }
738 var tag: String?
739 if let tagNode = item.firstChild(.itemTag) {
740 if tagNode.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in item tags") }
741 tag = try transcode(Self.merge(try inlineItems(tagNode)))
742 }
743 let children = item.children.filter { $0.kind != .itemTag }
744 var contents = ""
745 var previous: SyntaxNode?
746 for (index, child) in children.enumerated() {
747 let next = index + 1 < children.count ? children[index + 1].range.lowerBound : item.range.upperBound
748 var result: String?
749 if child.kind == .paragraph, previous == nil, index == 0 {
750 // The first paragraph's first line follows the bullet: its indentation doesn't count.
751 let bulletLine = source.lineRange(for: NSRange(location: item.range.lowerBound, length: 0))
752 let ignore = child.range.lowerBound < NSMaxRange(bulletLine)
753 result = try paragraph(child, affiliated: Affiliated(), ignoreFirst: ignore)
754 } else if child.kind == .plainList {
755 result = try list(child, affiliated: Affiliated(), orderedDepth: depth)
756 } else {
757 // Elements with affiliated keywords go through `elements`.
758 result = try elements([child], end: next)
759 if result == "" { result = nil }
760 if let r = result {
761 contents += r
762 previous = child
763 continue
764 }
765 }
766 guard let result else { continue }
767 previous = child
768 var text = Self.normalize(result) + String(repeating: "\n", count: blankLines(from: child.range.lowerBound, to: next))
769 if child.kind == .paragraph { text = Self.cleanLineBreaks(text) }
770 contents += text
771 }
772 if children.contains(where: { $0.kind == .affiliatedKeyword }) { throw Unsupported(reason: "Affiliated keywords in list items") }
773 contents = Self.normalize(contents)
774 var out = counter + "\\item"
775 if let checkbox, let tag {
776 out += ordered ? "{\(checkbox) \(tag)} " : "[{\(checkbox) \(tag)}] "
777 } else if let label = checkbox ?? tag {
778 out += ordered ? "{\(label)} " : "[{\(label)}] "
779 } else if contents.firstMatch(of: /^[ \t]*\[/) != nil {
780 out += "\\relax "
781 } else {
782 out += " "
783 }
784 return out + Self.trim(contents)
785 }
786
787 // MARK: Tables
788
789 /// `org-table-number-regexp`.
790 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)$")
791
792 private func table(_ node: SyntaxNode, affiliated: Affiliated) throws -> String {
793 let rows = node.children.filter { $0.kind == .tableRow }
794 if node.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in tables") }
795 let mode = affiliated.value("mode") ?? "table"
796 guard mode == "table" else { throw Unsupported(reason: "#+ATTR_LATEX: :mode \(mode)") }
797 let environment = affiliated.value("environment") ?? "tabular"
798 if ["longtable", "longtabu", "tabbing"].contains(environment) { throw Unsupported(reason: "#+ATTR_LATEX: :environment \(environment)") }
799 let booktabs = affiliated.has("booktabs") ? affiliated.value("booktabs") != nil : false
800 if booktabs { throw Unsupported(reason: "Booktabs tables") }
801 // Cells as transcoded, rules as nil.
802 var cells: [[String]?] = []
803 for row in rows {
804 let rowCells = row.children.filter { $0.kind == .tableCell }
805 if rowCells.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
806 cells.append(nil)
807 continue
808 }
809 if rowCells.isEmpty { continue }
810 cells.append(try rowCells.map { try transcode(Self.merge(try inlineItems($0, trimmed: true))) })
811 }
812 let data = cells.compactMap { $0 }
813 if Self.hasSpecialRows(data.map { $0 }, raw: rows) { throw Unsupported(reason: "Tables with alignment cookies or special columns") }
814 let columns = data.first?.count ?? 0
815 var align = ""
816 for c in 0..<columns {
817 var numbers = 0, total = 0
818 var previousNumber = false
819 for row in data {
820 let value = c < row.count ? row[c] : ""
821 total += 1
822 let isNumber = Self.numberPattern.firstMatch(in: value, range: NSRange(location: 0, length: (value as NSString).length)) != nil
823 if isNumber || (value.isEmpty && previousNumber) {
824 previousNumber = true
825 numbers += 1
826 } else {
827 previousNumber = false
828 }
829 }
830 align += total > 0 && Double(numbers) / Double(total) >= 0.5 ? "r" : "l"
831 }
832 let alignment = affiliated.value("align") ?? align
833 var contents = ""
834 for row in cells {
835 guard let row else {
836 contents += "\\hline\n"
837 continue
838 }
839 contents += Self.normalize(row.joined(separator: " & ") + "\\\\\n")
840 }
841 contents = Self.normalize(contents)
842 var width = ""
843 if let w = affiliated.value("width"), !["tabular", "longtable"].contains(environment) {
844 if ["tabu", "longtabu"].contains(environment) { throw Unsupported(reason: "tabu tables") }
845 width = "{\(w)}"
846 }
847 let opt = affiliated.value("options").map { "[\($0)]" } ?? ""
848 let table = "\\begin{\(environment)}\(opt)\(width){\(alignment)}\n\(contents)\\end{\(environment)}"
849 let caption = try captionLabel(affiliated, type: "table", prefix: "tab:")
850 return decorate(table, affiliated: affiliated, caption: caption, above: true)
851 }
852
853 /// Whether a table has rows of alignment cookies or a column of row marks.
854 static func hasSpecialRows(_ data: [[String]], raw: [SyntaxNode]) -> Bool {
855 let cookie = /^<[lrc]?[0-9]*>$/
856 for row in raw {
857 let cells = row.children.filter { $0.kind == .tableCell }.map { $0.text.trimmingCharacters(in: .whitespaces) }
858 guard !cells.isEmpty else { continue }
859 if cells.allSatisfy({ $0.isEmpty || $0.wholeMatch(of: cookie) != nil }), cells.contains(where: { !$0.isEmpty }) { return true }
860 }
861 let marks: Set<String> = ["", "#", "!", "$", "*", "^", "_", "/"]
862 let first = raw.compactMap { $0.children.first { $0.kind == .tableCell }?.text.trimmingCharacters(in: .whitespaces) }
863 return !first.isEmpty && first.allSatisfy(marks.contains) && first.contains { !$0.isEmpty }
864 }
865
866 /// `org-latex--decorate-table`.
867 private func decorate(_ table: String, affiliated: Affiliated, caption: String, above: Bool) -> String {
868 let floatEnvironment: String?
869 let float = affiliated.attribute("float")
870 switch float {
871 case .some(nil): floatEnvironment = nil
872 case .some(.some(let f)) where f == "sidewaystable" || f == "sideways": floatEnvironment = "sidewaystable"
873 case .some(.some("multicolumn")): floatEnvironment = "table*"
874 case .some(.some("t")): floatEnvironment = "table"
875 case .some(.some(let f)): floatEnvironment = f
876 case .none: floatEnvironment = caption.contains(where: { !$0.isWhitespace }) ? "table" : nil
877 }
878 let placement = affiliated.value("placement") ?? "[htbp]"
879 let center = affiliated.has("center") ? affiliated.value("center") != nil : true
880 let font = affiliated.value("font").map { $0 + "\n" }
881 let captionText: String? = caption.isEmpty ? nil : caption
882 var out = ""
883 if let floatEnvironment {
884 out = "\\begin{\(floatEnvironment)}\(placement)\n" + (above ? caption : "") + (center ? "\\centering\n" : "") + (font ?? "")
885 } else if captionText != nil {
886 out = (center ? "\\begin{center}\n" : "") + (above ? caption : "") + (font.map { center ? $0 : "{" + $0 } ?? "")
887 } else if center {
888 out = "\\begin{center}\n" + (font ?? "")
889 } else if let font {
890 out = "{" + font
891 }
892 out += table
893 if let floatEnvironment {
894 out += (above ? "" : "\n" + caption) + "\n\\end{\(floatEnvironment)}"
895 } else if captionText != nil {
896 out += (above ? "" : "\n" + caption) + (center ? "\n\\end{center}" : "") + (font != nil && !center ? "}" : "")
897 } else if center {
898 out += "\n\\end{center}"
899 } else if font != nil {
900 out += "}"
901 }
902 return out
903 }
904
905 /// `org-latex--caption/label-string` for a float.
906 private func captionLabel(_ affiliated: Affiliated, type: String, prefix: String, srcBlock: Bool = false) throws -> String {
907 let nonfloat = (affiliated.attribute("float") == .some(nil) && !affiliated.caption.isEmpty) || (srcBlock && affiliated.value("float") == nil)
908 let label = affiliated.name.map { "\\label{\(prefix)\(reference("name:" + $0))}\n" } ?? ""
909 if let fromAttr = affiliated.value("caption"), fromAttr.contains(where: { !$0.isWhitespace }) { return fromAttr + "\n" }
910 guard !affiliated.caption.isEmpty else { return label }
911 let main = try inlineString(affiliated.caption.joined(separator: " "))
912 let trimmedLabel = Self.trim(label)
913 return nonfloat ? "\\captionof{\(type)}{\(trimmedLabel)\(main)}\n" : "\\caption{\(trimmedLabel)\(main)}\n"
914 }
915
916 // MARK: Blocks
917
918 private func block(_ node: SyntaxNode, affiliated: Affiliated) throws -> String? {
919 var lines = node.text.components(separatedBy: "\n")
920 if lines.last == "" { lines.removeLast() }
921 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
922 let type = m.1.lowercased()
923 let parameters = String(m.2)
924 let body = Array(lines.dropFirst().dropLast())
925 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
926 let text = unescaped.joined(separator: "\n")
927 switch type {
928 case "src":
929 guard text.contains(where: { !$0.isWhitespace }) else { return nil }
930 if affiliated.has("float") { throw Unsupported(reason: "Floating source blocks") }
931 let code = try formatCode(lines)
932 let verbatim = "\\begin{verbatim}\n\(code)\\end{verbatim}"
933 guard !affiliated.caption.isEmpty else { return verbatim }
934 return verbatim + "\n" + (try captionLabel(affiliated, type: "figure", prefix: "lst:", srcBlock: true))
935 case "example":
936 guard text.contains(where: { !$0.isWhitespace }) else { return nil }
937 let environment = affiliated.value("environment") ?? "verbatim"
938 return try wrapLabel(affiliated, "\\begin{\(environment)}\n\(try formatCode(lines))\\end{\(environment)}")
939 case "quote":
940 let environment = affiliated.value("environment") ?? "quote"
941 return try wrapLabel(affiliated, "\\begin{\(environment)}\(affiliated.value("options") ?? "")\n\(Self.normalize(try blocks(text)))\\end{\(environment)}")
942 case "center":
943 return try wrapLabel(affiliated, "\\begin{center}\n\(Self.normalize(try blocks(text)))\\end{center}")
944 case "verse":
945 if !affiliated.attr.isEmpty { throw Unsupported(reason: "#+ATTR_LATEX on verse blocks") }
946 return try wrapLabel(affiliated, try verse(unescaped))
947 case "export":
948 let backend = parameters.split(separator: " ").first.map { $0.uppercased() } ?? ""
949 guard backend == "LATEX" || backend == "TEX" else { return nil }
950 return try Self.removeIndentation(text + "\n")
951 case "comment":
952 return nil
953 default:
954 let caption = try captionLabel(affiliated, type: "figure", prefix: "")
955 if !caption.isEmpty { throw Unsupported(reason: "Captioned special blocks") }
956 return "\\begin{\(m.1)}\(affiliated.value("options") ?? "")\n" + Self.normalize(try blocks(text)) + "\\end{\(m.1)}"
957 }
958 }
959
960 /// `org-export-format-code-default` for a src or example block's lines.
961 private func formatCode(_ lines: [String]) throws -> String {
962 guard let parsed = Coderef.block(lines) else { return "" }
963 var value = parsed.body.joined(separator: "\n")
964 if !value.isEmpty { value += "\n" }
965 let preserve = lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b.*\s-i\b/) != nil
966 var code = preserve ? value : try Self.removeIndentation(value)
967 if code.hasSuffix("\n") { code.removeLast() }
968 let (lines, refs) = Coderef.unravel(code.components(separatedBy: "\n"), format: parsed.switches.labelFormat)
969 let loc = parsed.switches.numberLines == nil ? nil : blockLoc(lines: lines)
970 guard loc != nil || (parsed.switches.retainLabels && !refs.isEmpty) else { return lines.joined(separator: "\n") + "\n" }
971 let width = loc.map { String($0 + lines.count).count } ?? 0
972 let numberWidth = loc == nil ? 0 : width + 2
973 let maxWidth = (lines.map(\.count).max() ?? 0) + numberWidth
974 return lines.enumerated().map { index, line in
975 var out = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1) " } ?? ""
976 out += line
977 if parsed.switches.retainLabels, let ref = refs[index + 1] {
978 out += String(repeating: " ", count: maxWidth + 6 - out.count) + "(\(ref))"
979 }
980 return out
981 }.joined(separator: "\n") + "\n"
982 }
983
984 private var blockLocs: [Int?]?
985 private var blockIndex = 0
986
987 /// `org-export-get-loc` of the next numbered block.
988 private func blockLoc(lines: [String]) -> Int? {
989 if blockLocs == nil {
990 let blocks = Coderef.blocks(tree).compactMap(Coderef.block)
991 blockLocs = Coderef.locs(blocks)
992 }
993 _ = lines
994 defer { blockIndex += 1 }
995 return blockIndex < blockLocs!.count ? blockLocs![blockIndex] : nil
996 }
997
998 /// `org-latex-verse-block` and the verse rules of `org-latex-plain-text`.
999 private func verse(_ lines: [String]) throws -> String {
1000 let text = lines.joined(separator: "\n") + "\n"
1001 // The contents are objects: paragraphs and the blank lines between them.
1002 let tree = OrgParser.parse(text, defaults: settings)
1003 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1004 guard nodes.allSatisfy({ $0.kind == .paragraph }), let firstNode = nodes.first else { throw Unsupported(reason: "Verse blocks with more than text") }
1005 let ns = text as NSString
1006 var raw: [Inline] = [.text(ns.substring(to: firstNode.range.lowerBound))]
1007 for (index, node) in nodes.enumerated() {
1008 raw += try inlineItems(node)
1009 let end = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : ns.length
1010 raw.append(.text(ns.substring(with: NSRange(location: node.range.upperBound, length: end - node.range.upperBound))))
1011 }
1012 inVerse = true
1013 defer { inVerse = false }
1014 let items = Self.normalizeIndentation(Self.merge(raw), ignoreFirst: false)
1015 var contents = try transcode(items)
1016 while let c = contents.last, c.isWhitespace { contents.removeLast() }
1017 return Self.cleanLineBreaks("\\begin{verse}\n" + contents + "\n\\end{verse}")
1018 }
1019
1020 private var inVerse = false
1021
1022 // MARK: - Objects
1023
1024 /// Inline content: text runs and objects with their own contents.
1025 indirect enum Inline {
1026 case text(String)
1027 case object(SyntaxNode, [Inline])
1028 }
1029
1030 /// The contents of `node` as `Inline`s, markers left out, a line break's newline taken in.
1031 func inlineItems(_ node: SyntaxNode, trimmed: Bool = false) throws -> [Inline] {
1032 var items: [Inline] = []
1033 var skipNewline = false
1034 for element in node.elements {
1035 switch element {
1036 case .token(let token):
1037 switch token.kind {
1038 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1039 continue
1040 default:
1041 var text = token.text
1042 if skipNewline {
1043 let rest = text.drop { $0 == " " || $0 == "\t" }
1044 if rest.hasPrefix("\n") { text = String(rest.dropFirst()); skipNewline = false } else if !rest.isEmpty { skipNewline = false } else { text = "" }
1045 }
1046 if !text.isEmpty { items.append(.text(text)) }
1047 }
1048 case .node(let child):
1049 skipNewline = false
1050 switch child.kind {
1051 case .bold, .italic, .underline, .strikeThrough, .linkDescription:
1052 items.append(.object(child, try inlineItems(child)))
1053 case .link:
1054 items.append(.object(child, try child.firstChild(.linkDescription).map { try inlineItems($0) } ?? []))
1055 case .superscript, .subscript:
1056 let text = child.text
1057 let braced = text.dropFirst().hasPrefix("{")
1058 if options.scripts == .off || (options.scripts == .braces && !braced) {
1059 items.append(.text(text))
1060 } else if braced {
1061 items.append(.object(child, try inlineItems(child)))
1062 } else {
1063 items.append(.object(child, [.text(String(text.dropFirst()))]))
1064 }
1065 case .lineBreak where trimmed:
1066 // A table cell has no line ends.
1067 items.append(.text(child.text))
1068 case .lineBreak:
1069 items.append(.object(child, []))
1070 skipNewline = true
1071 default:
1072 items.append(.object(child, []))
1073 }
1074 }
1075 }
1076 if trimmed {
1077 if case .text(let t) = items.first { items[0] = .text(String(t.drop { $0 == " " || $0 == "\t" })) }
1078 if case .text(let t) = items.last { items[items.count - 1] = .text(String(t.reversed().drop { $0 == " " || $0 == "\t" }.reversed())) }
1079 }
1080 return Self.merge(items)
1081 }
1082
1083 /// Adjacent text runs joined.
1084 static func merge(_ items: [Inline]) -> [Inline] {
1085 var out: [Inline] = []
1086 for item in items {
1087 if case .text(let t) = item, case .text(let previous)? = out.last {
1088 out[out.count - 1] = .text(previous + t)
1089 } else if case .text(let t) = item, t.isEmpty {
1090 continue
1091 } else {
1092 out.append(item)
1093 }
1094 }
1095 return out
1096 }
1097
1098 /// `org-element-normalize-contents`: the common indentation of the lines taken away.
1099 static func normalizeIndentation(_ items: [Inline], ignoreFirst: Bool) -> [Inline] {
1100 var minimum = Int.max
1101 var zero = false
1102 func scan(_ items: [Inline], _ firstFlag: inout Bool) {
1103 for item in items {
1104 if zero { return }
1105 if firstFlag {
1106 firstFlag = false
1107 guard case .text(let t) = item, let m = t.firstMatch(of: /^([ \t]+)([^ \t\n]|\n|$)/) else { zero = true; return }
1108 if m.2 != "\n" { minimum = min(minimum, width(m.1)) }
1109 }
1110 switch item {
1111 case .text(let t):
1112 // Every line start, a blank line's next line included.
1113 var rest = t[...]
1114 while let newline = rest.firstIndex(of: "\n") {
1115 let after = rest[rest.index(after: newline)...]
1116 let indent = after.prefix { $0 == " " || $0 == "\t" }
1117 let next = after.dropFirst(indent.count).first
1118 if indent.isEmpty {
1119 if next != nil, next != "\n" { zero = true; return }
1120 } else if next != "\n" {
1121 minimum = min(minimum, width(indent))
1122 }
1123 rest = after
1124 }
1125 case .object(let node, let children):
1126 if node.kind == .lineBreak {
1127 firstFlag = true
1128 } else if [.bold, .italic, .underline, .strikeThrough, .link, .linkDescription, .superscript, .subscript].contains(node.kind) {
1129 scan(children, &firstFlag)
1130 }
1131 }
1132 }
1133 }
1134 var first = !ignoreFirst
1135 scan(items, &first)
1136 guard !zero, minimum != Int.max, minimum > 0 else { return items }
1137 func strip(_ items: [Inline], _ firstFlag: inout Bool) -> [Inline] {
1138 items.map { item in
1139 switch item {
1140 case .text(var t):
1141 if firstFlag {
1142 firstFlag = false
1143 t = dedent(t, atStart: true, by: minimum)
1144 } else {
1145 t = dedent(t, atStart: false, by: minimum)
1146 }
1147 return .text(t)
1148 case .object(let node, let children):
1149 if firstFlag { firstFlag = false }
1150 if node.kind == .lineBreak { firstFlag = true; return item }
1151 var flag = false
1152 return .object(node, strip(children, &flag))
1153 }
1154 }
1155 }
1156 var flag = !ignoreFirst
1157 return strip(items, &flag)
1158 }
1159
1160 static func width(_ s: Substring) -> Int { s.reduce(0) { $0 + ($1 == "\t" ? 8 : 1) } }
1161
1162 /// Indentation after each newline (and at the start) less `by` columns; blank lines lose theirs.
1163 static func dedent(_ t: String, atStart: Bool, by: Int) -> String {
1164 var lines = t.components(separatedBy: "\n")
1165 for i in lines.indices where i > 0 || atStart {
1166 let indent = lines[i].prefix { $0 == " " || $0 == "\t" }
1167 guard !indent.isEmpty else { continue }
1168 let rest = lines[i].dropFirst(indent.count)
1169 if rest.isEmpty && i < lines.count - 1 {
1170 lines[i] = ""
1171 } else if rest.isEmpty {
1172 lines[i] = String(repeating: " ", count: max(0, width(indent) - by))
1173 } else {
1174 lines[i] = String(repeating: " ", count: max(0, width(indent) - by)) + rest
1175 }
1176 }
1177 return lines.joined(separator: "\n")
1178 }
1179
1180 /// One line of Org text transcoded, for keywords and captions.
1181 func inlineString(_ text: String) throws -> String {
1182 let tree = OrgParser.parse(text, defaults: settings)
1183 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1184 let saved = exportSource
1185 exportSource = ExportSource(tree: tree, text: text)
1186 defer { exportSource = saved }
1187 return Self.trim(try transcode(try inlineItems(paragraph)))
1188 }
1189
1190 /// `node`'s contents transcoded, as a heading's title is.
1191 private func inline(_ node: SyntaxNode, sectionTitle: Bool) throws -> String {
1192 let saved = inTitle
1193 inTitle = sectionTitle
1194 defer { inTitle = saved }
1195 return try transcode(try inlineItems(node))
1196 }
1197
1198 private var inTitle = false
1199
1200 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`),
1201 /// objects that export nothing taking their blanks with them unless they are needed.
1202 func transcode(_ items: [Inline]) throws -> String {
1203 var out = ""
1204 var index = 0
1205 var dropBlanks = false
1206 while index < items.count {
1207 let item = items[index]
1208 switch item {
1209 case .text(var t):
1210 if dropBlanks { t = String(t.drop { $0 == " " || $0 == "\t" }) }
1211 dropBlanks = false
1212 out += plainText(t)
1213 index += 1
1214 case .object(let node, let children):
1215 dropBlanks = false
1216 if let math = mathValue(node) {
1217 var values = [math]
1218 var next = index + 1
1219 while next < items.count, case .object(let n, _) = items[next], let v = mathValue(n) {
1220 values.append(v)
1221 next += 1
1222 }
1223 let joined = Self.trim(values.joined(separator: " "))
1224 if !joined.isEmpty { out += "\\(\(joined)\\)" }
1225 index = next
1226 continue
1227 }
1228 if var result = try object(node, children) {
1229 // `org-timestamp-translate` keeps the blanks after the timestamp.
1230 if node.kind == .timestamp, index + 1 < items.count, case .text(let t) = items[index + 1] {
1231 result = result.dropLast() + String(t.prefix { $0 == " " || $0 == "\t" }) + "}"
1232 }
1233 out += result
1234 } else {
1235 // `org-export--keep-spaces`: blanks after a dropped object stay only
1236 // between text that has none.
1237 let previousBlank: Bool
1238 if index == 0 {
1239 previousBlank = true
1240 } else if case .text(let t) = items[index - 1] {
1241 previousBlank = t.last.map { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ?? false
1242 } else {
1243 previousBlank = false
1244 }
1245 dropBlanks = previousBlank
1246 }
1247 index += 1
1248 }
1249 }
1250 return out
1251 }
1252
1253 /// The LaTeX inside `\(…\)` for an object a math block takes, nil for others.
1254 private func mathValue(_ node: SyntaxNode) -> String? {
1255 switch node.kind {
1256 case .entity:
1257 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1258 guard let (latex, math) = OrgEntities.latex[name], math else { return nil }
1259 return latex
1260 case .latexFragment:
1261 guard options.tex else { return nil }
1262 let value = node.text
1263 if value.hasPrefix("\\(") { return String(value.dropFirst(2).dropLast(2)) }
1264 if value.hasPrefix("$"), !value.hasPrefix("$$") { return String(value.dropFirst().dropLast()) }
1265 return nil
1266 default:
1267 return nil
1268 }
1269 }
1270
1271 private func object(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1272 switch node.kind {
1273 case .bold: return "\\textbf{\(try transcode(children))}"
1274 case .italic: return "\\emph{\(try transcode(children))}"
1275 case .underline: return inTitle ? "\\underline{\(try transcode(children))}" : "\\uline{\(try transcode(children))}"
1276 case .strikeThrough: return "\\sout{\(try transcode(children))}"
1277 case .verbatim, .code:
1278 return Self.texttt(String(node.text.dropFirst().dropLast()))
1279 case .link: return try link(node, children)
1280 case .linkDescription: return try transcode(children)
1281 case .timestamp: return try timestamp(node.text)
1282 case .footnoteReference: return try footnote(node)
1283 case .entity:
1284 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1285 guard let (latex, _) = OrgEntities.latex[name] else { throw Unsupported(reason: "Unknown entity \(node.text)") }
1286 return latex
1287 case .superscript: return "\\textsuperscript{\(try transcode(children))}"
1288 case .subscript: return "\\textsubscript{\(try transcode(children))}"
1289 case .lineBreak: return "\\\\\n"
1290 case .latexFragment: return options.tex ? node.text : nil
1291 case .statisticsCookie: return node.text.replacingOccurrences(of: "%", with: "\\%")
1292 case .exportSnippet:
1293 let backend = node.tokens.first?.text.dropFirst(2).dropLast() ?? ""
1294 guard backend == "latex" else { return nil }
1295 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1296 case .target:
1297 let name = String(node.text.dropFirst(2).dropLast(2))
1298 return "\\label{\(reference("target:" + name))}"
1299 case .macro:
1300 guard case .some(let value) = exportSource.resultsMacro(node) else { return nil }
1301 return try value.map(inlineString)
1302 default:
1303 throw Unsupported(reason: "\(node.kind)")
1304 }
1305 }
1306
1307 // MARK: Plain text
1308
1309 /// `org-latex-plain-text`.
1310 func plainText(_ text: String) -> String {
1311 let special = options.specialStrings
1312 var out = ""
1313 let chars = Array(text)
1314 var i = 0
1315 while i < chars.count {
1316 let c = chars[i]
1317 switch c {
1318 case "%", "$", "#", "&", "{", "}", "_":
1319 out += "\\" + String(c)
1320 case "~": out += "\\textasciitilde{}"
1321 case "^": out += "\\^{}"
1322 case "\\":
1323 if special {
1324 if i + 1 < chars.count {
1325 if chars[i + 1] == "-" {
1326 out += "\\"
1327 } else {
1328 out += "$\\backslash$" + String(chars[i + 1])
1329 i += 1
1330 }
1331 } else {
1332 out += "$\\backslash$"
1333 }
1334 } else {
1335 out += "$\\backslash$"
1336 }
1337 default:
1338 out.append(c)
1339 }
1340 i += 1
1341 }
1342 out = Self.texLogos(out)
1343 if special { out = out.replacingOccurrences(of: "...", with: "\\ldots{}") }
1344 out = out.replacing(#/(?m)^(\s*)\[/#) { $0.1 + "{[}" }
1345 if inVerse {
1346 out = out.replacing(#/(?:[ \t]*\\\\)?[ \t]*\n/#, with: "\\\\\n")
1347 out = out.replacing(#/(\\\\\n)(?:(?m:^)[ \t]*\\\\\n)+/#, with: "\n\n")
1348 out = out.replacing(#/(?m)^[ \t]+/#) { "\\hspace*{\($0.output.count)\\fontdimen2\\font}" }
1349 }
1350 return out
1351 }
1352
1353 /// `LaTeX` and `TeX` as words, as their commands.
1354 static func texLogos(_ s: String) -> String {
1355 guard s.contains("TeX") else { return s }
1356 let chars = Array(s)
1357 var out = ""
1358 var i = 0
1359 // Word constituents in Org's syntax table, the apostrophe among them.
1360 func isWord(_ c: Character) -> Bool { c.isLetter || c.isNumber || c == "'" }
1361 outer: while i < chars.count {
1362 if i == 0 || !isWord(chars[i - 1]) {
1363 for word in ["LaTeX", "TeX"] {
1364 let w = Array(word)
1365 if i + w.count <= chars.count, Array(chars[i..<(i + w.count)]) == w, i + w.count == chars.count || !isWord(chars[i + w.count]) {
1366 out += "\\" + word + "{}"
1367 i += w.count
1368 continue outer
1369 }
1370 }
1371 }
1372 out.append(chars[i])
1373 i += 1
1374 }
1375 return out
1376 }
1377
1378 // MARK: Timestamps
1379
1380 /// `org-latex-timestamp`: `org-element-timestamp-interpreter`'s text in `\textit`, with the
1381 /// blanks after the timestamp.
1382 private func timestamp(_ text: String) throws -> String? {
1383 guard let stamp = Timestamp.parse(text) else { throw Unsupported(reason: "Timestamp \(text)") }
1384 let open = stamp.active ? "<" : "["
1385 let close = stamp.active ? ">" : "]"
1386 func date(_ p: Timestamp.Point, time: Bool) -> String {
1387 var components = DateComponents(year: p.year, month: p.month, day: p.day)
1388 components.calendar = Calendar(identifier: .gregorian)
1389 let weekday = components.calendar!.date(from: components).map { components.calendar!.component(.weekday, from: $0) } ?? 1
1390 let name = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][weekday - 1]
1391 var s = String(format: "%04d-%02d-%02d ", p.year, p.month, p.day) + name
1392 if time, let h = p.hour, let m = p.minute { s += String(format: " %02d:%02d", h, m) }
1393 return s
1394 }
1395 var suffix = ""
1396 if let r = stamp.repeater {
1397 suffix += " " + r.kind.rawValue + "\(r.interval.value)\(r.interval.unit.rawValue)"
1398 if let d = r.habitDeadline { suffix += "/\(d.value)\(d.unit.rawValue)" }
1399 }
1400 if let w = stamp.warning { suffix += " " + (w.firstOccurrenceOnly ? "--" : "-") + "\(w.interval.value)\(w.interval.unit.rawValue)" }
1401 var out = open + date(stamp.start, time: true)
1402 let dateRange = text.contains(">--<") || text.contains("]--[")
1403 if let end = stamp.end {
1404 if dateRange {
1405 out += suffix + close + "--" + open + date(end, time: true) + suffix + close
1406 } else {
1407 if let h = end.hour, let m = end.minute, h != stamp.start.hour || m != stamp.start.minute {
1408 out += String(format: "-%02d:%02d", h, m)
1409 }
1410 out += suffix + close
1411 }
1412 } else {
1413 out += suffix + close
1414 }
1415 guard options.items["<"] ?? "t" == "t" else { return nil }
1416 return "\\textit{\(plainText(out))}"
1417 }
1418
1419 // MARK: Links
1420
1421 private func linkTarget(_ node: SyntaxNode) -> (type: String, path: String) {
1422 var raw = node.tokens.first { $0.kind == .linkPath }?.text ?? node.text
1423 if node.tokens.first(where: { $0.kind == .linkPath }) == nil, raw.hasPrefix("<"), raw.hasSuffix(">") {
1424 raw = String(raw.dropFirst().dropLast())
1425 }
1426 if raw.hasPrefix("#") { return ("custom-id", String(raw.dropFirst())) }
1427 if raw.hasPrefix("(") && raw.hasSuffix(")") { return ("coderef", String(raw.dropFirst().dropLast())) }
1428 if raw.hasPrefix("./") || raw.hasPrefix("../") || raw.hasPrefix("/") || raw.hasPrefix("~") { return ("file", raw) }
1429 if let m = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/), Self.linkTypes.contains(m.1.lowercased()) {
1430 let type = m.1.lowercased()
1431 var path = String(m.2)
1432 if type == "file", path.hasPrefix("//") == false, let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
1433 return (type, path)
1434 }
1435 return ("fuzzy", raw)
1436 }
1437
1438 /// `org-link-parameters` under `emacs -Q` with ox-latex loaded.
1439 static let linkTypes: Set<String> = ["attachment", "id", "file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
1440
1441 private func isImage(_ node: SyntaxNode) -> Bool {
1442 guard node.kind == .link, node.firstChild(.linkDescription) == nil else { return false }
1443 let (type, path) = linkTarget(node)
1444 guard type == "file" || type == "https" else { return false }
1445 let ext = (path as NSString).pathExtension.lowercased()
1446 let image = type == "file" ? ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"] : ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"]
1447 return image.contains(ext) && path.lowercased().hasSuffix("." + ext)
1448 }
1449
1450 /// The image link of a paragraph holding only it and blanks.
1451 private func soleImage(_ items: [Inline]) -> SyntaxNode? {
1452 var image: SyntaxNode?
1453 for item in items {
1454 switch item {
1455 case .text(let t): if t.contains(where: { !$0.isWhitespace }) { return nil }
1456 case .object(let node, _):
1457 guard image == nil, isImage(node) else { return nil }
1458 image = node
1459 }
1460 }
1461 return image
1462 }
1463
1464 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1465 let (type, path) = linkTarget(node)
1466 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
1467 if description == "" { description = nil }
1468 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1469 throw Unsupported(reason: "Links in link descriptions")
1470 }
1471 if let d = node.firstChild(.linkDescription)?.text, d.firstMatch(of: /^(?:[A-Za-z]+:\S+|<[^>]+>)$/) != nil {
1472 throw Unsupported(reason: "Images as link descriptions")
1473 }
1474 if isImage(node) { return try inlineImage(node, affiliated: currentAffiliated ?? Affiliated(), alone: false) }
1475 switch type {
1476 case "custom-id", "fuzzy", "id":
1477 let label: String
1478 let numberedHeading: Bool
1479 var title: String?
1480 if type == "fuzzy", !path.hasPrefix("*"), let found = target(path).map({ reference("target:" + $0) }) ?? namedElement(path) {
1481 return description.map { "\\hyperref[\(found)]{\($0)}" } ?? "\\ref{\(found)}"
1482 }
1483 guard let heading = try resolveHeading(type: type, path: path) else {
1484 throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"")
1485 }
1486 label = "sec:" + reference("heading@\(heading.headingRange.lowerBound)")
1487 numberedHeading = numbered && (num.map { heading.level + levelOffset <= $0 } ?? true)
1488 if description == nil, numberedHeading { return "\\ref{\(label)}" }
1489 if description == nil {
1490 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1491 title = try node?.firstChild(.title).map { try Self.trim(inline($0, sectionTitle: false)) } ?? ""
1492 }
1493 return "\\hyperref[\(label)]{\(description ?? title ?? "")}"
1494 case "coderef":
1495 guard let resolved = Coderef.resolve(path, in: tree) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
1496 // `org-export-get-coderef-format` on the transcoded description, then `format`.
1497 var format = description ?? "%s"
1498 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
1499 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
1500 case "file":
1501 if path.hasPrefix("~") { throw Unsupported(reason: "File links under ~") }
1502 let uri = path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path
1503 let protected = Self.protect(uri)
1504 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}"
1505 case "http", "https", "ftp", "mailto", "news":
1506 let protected = Self.protect(type + ":" + path)
1507 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}"
1508 default:
1509 throw Unsupported(reason: "\(type): links")
1510 }
1511 }
1512
1513 /// Words of a fuzzy link or a title, as `org-export-search-cells` compares them.
1514 static func words(_ s: String) -> [String] {
1515 s.uppercased().split(whereSeparator: \.isWhitespace).map(String.init)
1516 }
1517
1518 /// The `<<target>>` a fuzzy link names.
1519 private func target(_ path: String) -> String? {
1520 let search = Self.words(path)
1521 return tree.root.descendants().first { $0.kind == .target && Self.words(String($0.text.dropFirst(2).dropLast(2))) == search }
1522 .map { String($0.text.dropFirst(2).dropLast(2)) }
1523 }
1524
1525 /// The label of the element whose `#+NAME` a fuzzy link names, as the element writes it.
1526 private func namedElement(_ path: String) -> String? {
1527 let search = path.split(whereSeparator: \.isWhitespace).map(String.init)
1528 for node in tree.root.descendants() where node.kind == .affiliatedKeyword {
1529 guard let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { continue }
1530 let name = String(m.1)
1531 let words = name.split(whereSeparator: \.isWhitespace).map(String.init)
1532 guard words == search || words == search.map({ $0.uppercased() }), let parent = node.parent else { continue }
1533 let siblings = parent.children
1534 guard let index = siblings.firstIndex(where: { $0.range == node.range }) else { continue }
1535 let keywords = siblings[index...].prefix { $0.kind == .affiliatedKeyword }
1536 guard let element = siblings[index...].first(where: { $0.kind != .affiliatedKeyword }) else { continue }
1537 let captioned = keywords.contains { $0.text.firstMatch(of: /^[ \t]*#\+(?i:caption)/) != nil }
1538 let prefix: String
1539 switch element.kind {
1540 case .table: prefix = "tab:"
1541 case .block where blockType(element) == "src": prefix = "lst:"
1542 case .paragraph where captioned: prefix = "fig:"
1543 default: prefix = ""
1544 }
1545 return prefix + reference("name:" + name)
1546 }
1547 return nil
1548 }
1549
1550 /// The heading a link goes to: by `CUSTOM_ID`, `ID` or title.
1551 private func resolveHeading(type: String, path: String) throws -> HeadingInfo? {
1552 switch type {
1553 case "custom-id":
1554 return model.headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } }
1555 case "id":
1556 return model.headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } }
1557 default:
1558 let search = Self.words(path.hasPrefix("*") ? String(path.dropFirst()) : path)
1559 return model.headings.first { heading in
1560 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1561 let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ")
1562 return Self.words(raw) == search
1563 }
1564 }
1565 }
1566
1567 /// `org-latex--inline-image`.
1568 private func inlineImage(_ node: SyntaxNode, affiliated: Affiliated, alone: Bool) throws -> String {
1569 let (type, path) = linkTarget(node)
1570 if type != "file" { throw Unsupported(reason: "Remote images") }
1571 if path.hasPrefix("~") || path.hasPrefix("/") { throw Unsupported(reason: "Images with absolute paths") }
1572 let ext = (path as NSString).pathExtension.lowercased()
1573 let caption = try captionLabel(affiliated, type: "figure", prefix: !affiliated.caption.isEmpty ? "fig:" : "")
1574 enum Float: Equatable { case none, nonfloat, figure, wrap, sideways, multicolumn, env(String) }
1575 var float: Float
1576 let attrFloat = affiliated.attribute("float")
1577 if !alone {
1578 float = .none
1579 } else {
1580 switch attrFloat {
1581 case .some(.some("wrap")): float = .wrap
1582 case .some(.some("sideways")): float = .sideways
1583 case .some(.some("multicolumn")): float = .multicolumn
1584 case .some(.some("t")): float = .figure
1585 case .some(nil): float = .nonfloat
1586 case .some(.some(let f)): float = .env(f)
1587 case .none: float = !affiliated.caption.isEmpty || affiliated.value("caption") != nil ? .figure : .nonfloat
1588 }
1589 }
1590 let placement: String
1591 if let p = affiliated.value("placement") {
1592 placement = p
1593 } else if float == .wrap {
1594 placement = "{l}{0.5\\textwidth}"
1595 } else if float == .figure {
1596 placement = "[htbp]"
1597 } else {
1598 placement = ""
1599 }
1600 let center = affiliated.has("center") ? affiliated.value("center") != nil : true
1601 let scale = float == .wrap ? "" : affiliated.value("scale") ?? ""
1602 let width: String = !scale.isEmpty ? "" : affiliated.value("width") ?? (affiliated.value("height") != nil ? "" : float == .wrap ? "0.48\\textwidth" : ".9\\linewidth")
1603 let height: String = !scale.isEmpty ? "" : affiliated.value("height") ?? ""
1604 var options = affiliated.value("options") ?? ""
1605 if let m = options.wholeMatch(of: /\[(.*)\]/) { options = String(m.1) }
1606 if ext == "tikz" || ext == "pgf" { throw Unsupported(reason: "TikZ images") }
1607 if affiliated.value("comment-include") != nil { throw Unsupported(reason: ":comment-include") }
1608 if !scale.isEmpty {
1609 options += ",scale=" + scale
1610 } else {
1611 if !width.isEmpty { options += ",width=" + width }
1612 if !height.isEmpty { options += ",height=" + height }
1613 }
1614 let optionString = options.isEmpty ? "" : options.hasPrefix(",") ? "[\(options.dropFirst())]" : "[\(options)]"
1615 var imagePath = path
1616 if ext == "svg", imagePath.contains(where: { !$0.isASCII }) { imagePath = "\\detokenize{\(imagePath)}" }
1617 var code = "\\includegraphics\(optionString){\(imagePath)}"
1618 if ext == "svg" {
1619 code = "\\includesvg" + code.dropFirst("\\includegraphics".count)
1620 code = code.replacingOccurrences(of: ".svg}", with: "}")
1621 }
1622 let above = false
1623 switch float {
1624 case .env(let env):
1625 return "\\begin{\(env)}\(placement)\n\(above ? caption : "")\(center ? "\\centering" : "")\n\(code)\n\(above ? "" : caption)\\end{\(env)}"
1626 case .wrap:
1627 return "\\begin{wrapfigure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{wrapfigure}"
1628 case .sideways:
1629 return "\\begin{sidewaysfigure}\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{sidewaysfigure}"
1630 case .multicolumn:
1631 return "\\begin{figure*}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure*}"
1632 case .figure:
1633 return "\\begin{figure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure}"
1634 case .none, .nonfloat:
1635 if center { return "\\begin{center}\n\(code)\n\(caption)\\end{center}" }
1636 return code
1637 }
1638 }
1639
1640 // MARK: Footnotes
1641
1642 private var footnoteReferences: [String: Int] = [:]
1643 private var footnotesSeen: Set<String> = []
1644 private var definitions: [String: String] = [:]
1645 private var anonymous = 0
1646
1647 /// Footnote definitions, and how many references each label has.
1648 private func countFootnotes() throws {
1649 for node in tree.root.descendants() {
1650 if node.kind == .footnoteDefinition, let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
1651 // A definition goes on to the next one, a heading or two blank lines.
1652 if let parent = node.parent, let index = parent.children.firstIndex(where: { $0.range == node.range }), index + 1 < parent.children.count {
1653 let next = parent.children[index + 1]
1654 if next.kind != .footnoteDefinition, next.kind != .section, blankLines(from: node.range.lowerBound, to: next.range.lowerBound) < 2 {
1655 throw Unsupported(reason: "Footnote definitions of several paragraphs")
1656 }
1657 }
1658 definitions[String(m.1)] = String(node.text[m.range.upperBound...])
1659 }
1660 if node.kind == .footnoteReference, let m = node.text.firstMatch(of: /^\[fn:([^:\]]+)/) {
1661 if node.parent.map({ Self.excluded($0, by: self) }) == true { continue }
1662 footnoteReferences[String(m.1), default: 0] += 1
1663 }
1664 }
1665 }
1666
1667 /// Whether `node` is under a section the export leaves out.
1668 private static func excluded(_ node: SyntaxNode, by renderer: LaTeXRenderer) -> Bool {
1669 var current: SyntaxNode? = node
1670 while let n = current {
1671 if n.kind == .section, let heading = n.firstChild(.heading),
1672 HTMLRenderer.sectionExport(heading, options: renderer.options, selected: renderer.selected) != .all { return true }
1673 current = n.parent
1674 }
1675 return false
1676 }
1677
1678 /// `org-latex-footnote-reference`.
1679 private func footnote(_ node: SyntaxNode) throws -> String {
1680 guard let m = node.text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { throw Unsupported(reason: "Footnote \(node.text)") }
1681 let label = String(m.1)
1682 if inFootnote { throw Unsupported(reason: "Footnotes inside footnotes") }
1683 var separator = ""
1684 if let previous = previousSibling(node), previous.kind == .footnoteReference { separator = "\\textsuperscript{,}\\," }
1685 if let inline = m.2 {
1686 if !label.isEmpty {
1687 if footnotesSeen.contains(label) { return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}" }
1688 footnotesSeen.insert(label)
1689 }
1690 inFootnote = true
1691 defer { inFootnote = false }
1692 let content = try inlineString(String(inline))
1693 let labelText = !label.isEmpty && (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : ""
1694 return separator + "\\footnote{\(content)\(labelText)}"
1695 }
1696 guard !label.isEmpty, let definition = definitions[label] else { throw Unsupported(reason: "Definition not found for footnote \(label)") }
1697 if footnotesSeen.contains(label) {
1698 return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}"
1699 }
1700 footnotesSeen.insert(label)
1701 inFootnote = true
1702 defer { inFootnote = false }
1703 let content = Self.trim(try footnoteBody(definition))
1704 let labelText = (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : ""
1705 return separator + "\\footnote{\(content)\(labelText)}"
1706 }
1707
1708 private var inFootnote = false
1709
1710 /// A definition's text transcoded, its first paragraph's first line left as it is.
1711 private func footnoteBody(_ text: String) throws -> String {
1712 let tree = OrgParser.parse(text, defaults: settings)
1713 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1714 if nodes.count == 1, nodes[0].kind == .paragraph {
1715 return try paragraph(nodes[0], affiliated: Affiliated(), ignoreFirst: true)
1716 }
1717 return try blocks(text)
1718 }
1719
1720 /// The object or text before `node` in its parent.
1721 private func previousSibling(_ node: SyntaxNode) -> SyntaxNode? {
1722 guard let parent = node.parent else { return nil }
1723 var previous: SyntaxNode.Element?
1724 for element in parent.elements {
1725 if case .node(let n) = element, n.range == node.range {
1726 if case .node(let p)? = previous { return p }
1727 return nil
1728 }
1729 previous = element
1730 }
1731 return nil
1732 }
1733}
Sources/OrgCore/Semantic/OrgEntities.swift +417
@@ -416,4 +416,421 @@ enum OrgEntities {
416 "_ ": "                   ", 416 "_ ": "                   ",
417 "_ ": "                    ", 417 "_ ": "                    ",
418 ] 418 ]
419
420 /// Entity name to its LaTeX and whether that is math (`org-entities`' second and third
421 /// fields), for LaTeX export. The first definition of a name wins.
422 static let latex: [String: (String, Bool)] = [
423 "Agrave": ("\\`{A}", false),
424 "agrave": ("\\`{a}", false),
425 "Aacute": ("\\'{A}", false),
426 "aacute": ("\\'{a}", false),
427 "Acirc": ("\\^{A}", false),
428 "acirc": ("\\^{a}", false),
429 "Amacr": ("\\={A}", false),
430 "amacr": ("\\={a}", false),
431 "Atilde": ("\\~{A}", false),
432 "atilde": ("\\~{a}", false),
433 "Auml": ("\\\"{A}", false),
434 "auml": ("\\\"{a}", false),
435 "Aring": ("\\AA{}", false),
436 "AA": ("\\AA{}", false),
437 "aring": ("\\aa{}", false),
438 "AElig": ("\\AE{}", false),
439 "aelig": ("\\ae{}", false),
440 "Ccedil": ("\\c{C}", false),
441 "ccedil": ("\\c{c}", false),
442 "Egrave": ("\\`{E}", false),
443 "egrave": ("\\`{e}", false),
444 "Eacute": ("\\'{E}", false),
445 "eacute": ("\\'{e}", false),
446 "Ecirc": ("\\^{E}", false),
447 "ecirc": ("\\^{e}", false),
448 "Euml": ("\\\"{E}", false),
449 "euml": ("\\\"{e}", false),
450 "Igrave": ("\\`{I}", false),
451 "igrave": ("\\`{i}", false),
452 "Iacute": ("\\'{I}", false),
453 "iacute": ("\\'{i}", false),
454 "Idot": ("\\.{I}", false),
455 "inodot": ("\\i", false),
456 "Icirc": ("\\^{I}", false),
457 "icirc": ("\\^{i}", false),
458 "Iuml": ("\\\"{I}", false),
459 "iuml": ("\\\"{i}", false),
460 "Ntilde": ("\\~{N}", false),
461 "ntilde": ("\\~{n}", false),
462 "Ograve": ("\\`{O}", false),
463 "ograve": ("\\`{o}", false),
464 "Oacute": ("\\'{O}", false),
465 "oacute": ("\\'{o}", false),
466 "Ocirc": ("\\^{O}", false),
467 "ocirc": ("\\^{o}", false),
468 "Otilde": ("\\~{O}", false),
469 "otilde": ("\\~{o}", false),
470 "Ouml": ("\\\"{O}", false),
471 "ouml": ("\\\"{o}", false),
472 "Oslash": ("\\O", false),
473 "oslash": ("\\o{}", false),
474 "OElig": ("\\OE{}", false),
475 "oelig": ("\\oe{}", false),
476 "Scaron": ("\\v{S}", false),
477 "scaron": ("\\v{s}", false),
478 "szlig": ("\\ss{}", false),
479 "Ugrave": ("\\`{U}", false),
480 "ugrave": ("\\`{u}", false),
481 "Uacute": ("\\'{U}", false),
482 "uacute": ("\\'{u}", false),
483 "Ucirc": ("\\^{U}", false),
484 "ucirc": ("\\^{u}", false),
485 "Uuml": ("\\\"{U}", false),
486 "uuml": ("\\\"{u}", false),
487 "Yacute": ("\\'{Y}", false),
488 "yacute": ("\\'{y}", false),
489 "Yuml": ("\\\"{Y}", false),
490 "yuml": ("\\\"{y}", false),
491 "fnof": ("\\textit{f}", false),
492 "real": ("\\Re", true),
493 "image": ("\\Im", true),
494 "weierp": ("\\wp", true),
495 "ell": ("\\ell", true),
496 "imath": ("\\imath", true),
497 "jmath": ("\\jmath", true),
498 "Alpha": ("A", false),
499 "alpha": ("\\alpha", true),
500 "Beta": ("B", false),
501 "beta": ("\\beta", true),
502 "Gamma": ("\\Gamma", true),
503 "gamma": ("\\gamma", true),
504 "Delta": ("\\Delta", true),
505 "delta": ("\\delta", true),
506 "Epsilon": ("E", false),
507 "epsilon": ("\\epsilon", true),
508 "varepsilon": ("\\varepsilon", true),
509 "Zeta": ("Z", false),
510 "zeta": ("\\zeta", true),
511 "Eta": ("H", false),
512 "eta": ("\\eta", true),
513 "Theta": ("\\Theta", true),
514 "theta": ("\\theta", true),
515 "thetasym": ("\\vartheta", true),
516 "vartheta": ("\\vartheta", true),
517 "Iota": ("I", false),
518 "iota": ("\\iota", true),
519 "Kappa": ("K", false),
520 "kappa": ("\\kappa", true),
521 "Lambda": ("\\Lambda", true),
522 "lambda": ("\\lambda", true),
523 "Mu": ("M", false),
524 "mu": ("\\mu", true),
525 "nu": ("\\nu", true),
526 "Nu": ("N", false),
527 "Xi": ("\\Xi", true),
528 "xi": ("\\xi", true),
529 "Omicron": ("O", false),
530 "omicron": ("\\textit{o}", false),
531 "Pi": ("\\Pi", true),
532 "pi": ("\\pi", true),
533 "Rho": ("P", false),
534 "rho": ("\\rho", true),
535 "Sigma": ("\\Sigma", true),
536 "sigma": ("\\sigma", true),
537 "sigmaf": ("\\varsigma", true),
538 "varsigma": ("\\varsigma", true),
539 "Tau": ("T", false),
540 "Upsilon": ("\\Upsilon", true),
541 "upsih": ("\\Upsilon", true),
542 "upsilon": ("\\upsilon", true),
543 "Phi": ("\\Phi", true),
544 "phi": ("\\phi", true),
545 "varphi": ("\\varphi", true),
546 "Chi": ("X", false),
547 "chi": ("\\chi", true),
548 "acutex": ("\\acute x", true),
549 "Psi": ("\\Psi", true),
550 "psi": ("\\psi", true),
551 "tau": ("\\tau", true),
552 "Omega": ("\\Omega", true),
553 "omega": ("\\omega", true),
554 "piv": ("\\varpi", true),
555 "varpi": ("\\varpi", true),
556 "partial": ("\\partial", true),
557 "alefsym": ("\\aleph", true),
558 "aleph": ("\\aleph", true),
559 "gimel": ("\\gimel", true),
560 "beth": ("\\beth", true),
561 "dalet": ("\\daleth", true),
562 "ETH": ("\\DH{}", false),
563 "eth": ("\\dh{}", false),
564 "THORN": ("\\TH{}", false),
565 "thorn": ("\\th{}", false),
566 "dots": ("\\dots{}", false),
567 "cdots": ("\\cdots{}", true),
568 "hellip": ("\\dots{}", false),
569 "middot": ("\\textperiodcentered{}", false),
570 "iexcl": ("!`", false),
571 "iquest": ("?`", false),
572 "shy": ("\\-", false),
573 "ndash": ("--", false),
574 "mdash": ("---", false),
575 "quot": ("\\textquotedbl{}", false),
576 "acute": ("\\textasciiacute{}", false),
577 "ldquo": ("\\textquotedblleft{}", false),
578 "rdquo": ("\\textquotedblright{}", false),
579 "bdquo": ("\\quotedblbase{}", false),
580 "lsquo": ("\\textquoteleft{}", false),
581 "rsquo": ("\\textquoteright{}", false),
582 "sbquo": ("\\quotesinglbase{}", false),
583 "laquo": ("\\guillemotleft{}", false),
584 "raquo": ("\\guillemotright{}", false),
585 "lsaquo": ("\\guilsinglleft{}", false),
586 "rsaquo": ("\\guilsinglright{}", false),
587 "circ": ("\\^{}", false),
588 "vert": ("\\vert{}", true),
589 "vbar": ("|", false),
590 "brvbar": ("\\textbrokenbar{}", false),
591 "S": ("\\S", false),
592 "sect": ("\\S", false),
593 "P": ("\\P{}", false),
594 "para": ("\\P{}", false),
595 "amp": ("\\&", false),
596 "lt": ("\\textless{}", false),
597 "gt": ("\\textgreater{}", false),
598 "tilde": ("\\textasciitilde{}", false),
599 "slash": ("/", false),
600 "plus": ("+", false),
601 "under": ("\\_", false),
602 "equal": ("=", false),
603 "asciicirc": ("\\textasciicircum{}", false),
604 "dagger": ("\\textdagger{}", false),
605 "dag": ("\\dag{}", false),
606 "Dagger": ("\\textdaggerdbl{}", false),
607 "ddag": ("\\ddag{}", false),
608 "nbsp": ("~", false),
609 "ensp": ("\\hspace*{.5em}", false),
610 "emsp": ("\\hspace*{1em}", false),
611 "thinsp": ("\\hspace*{.2em}", false),
612 "curren": ("\\textcurrency{}", false),
613 "cent": ("\\textcent{}", false),
614 "pound": ("\\pounds{}", false),
615 "yen": ("\\textyen{}", false),
616 "euro": ("\\texteuro{}", false),
617 "EUR": ("\\texteuro{}", false),
618 "dollar": ("\\$", false),
619 "USD": ("\\$", false),
620 "copy": ("\\textcopyright{}", false),
621 "reg": ("\\textregistered{}", false),
622 "trade": ("\\texttrademark{}", false),
623 "minus": ("-", true),
624 "pm": ("\\textpm{}", false),
625 "plusmn": ("\\textpm{}", false),
626 "times": ("\\texttimes{}", false),
627 "frasl": ("/", false),
628 "colon": ("\\colon", true),
629 "div": ("\\textdiv{}", false),
630 "frac12": ("\\textonehalf{}", false),
631 "frac14": ("\\textonequarter{}", false),
632 "frac34": ("\\textthreequarters{}", false),
633 "permil": ("\\textperthousand{}", false),
634 "sup1": ("\\textonesuperior{}", false),
635 "sup2": ("\\texttwosuperior{}", false),
636 "sup3": ("\\textthreesuperior{}", false),
637 "radic": ("\\sqrt{\\,}", true),
638 "sum": ("\\sum", true),
639 "prod": ("\\prod", true),
640 "micro": ("\\textmu{}", false),
641 "macr": ("\\textasciimacron{}", false),
642 "deg": ("\\textdegree{}", false),
643 "prime": ("\\prime", true),
644 "Prime": ("\\prime{}\\prime", true),
645 "infin": ("\\infty", true),
646 "infty": ("\\infty", true),
647 "prop": ("\\propto", true),
648 "propto": ("\\propto", true),
649 "not": ("\\textlnot{}", false),
650 "neg": ("\\neg{}", true),
651 "land": ("\\land", true),
652 "wedge": ("\\wedge", true),
653 "lor": ("\\lor", true),
654 "vee": ("\\vee", true),
655 "cap": ("\\cap", true),
656 "cup": ("\\cup", true),
657 "smile": ("\\smile", true),
658 "frown": ("\\frown", true),
659 "int": ("\\int", true),
660 "therefore": ("\\therefore", true),
661 "there4": ("\\therefore", true),
662 "because": ("\\because", true),
663 "sim": ("\\sim", true),
664 "cong": ("\\cong", true),
665 "simeq": ("\\simeq", true),
666 "asymp": ("\\asymp", true),
667 "approx": ("\\approx", true),
668 "ne": ("\\ne", true),
669 "neq": ("\\neq", true),
670 "equiv": ("\\equiv", true),
671 "triangleq": ("\\triangleq", true),
672 "le": ("\\le", true),
673 "leq": ("\\le", true),
674 "ge": ("\\ge", true),
675 "geq": ("\\ge", true),
676 "lessgtr": ("\\lessgtr", true),
677 "lesseqgtr": ("\\lesseqgtr", true),
678 "ll": ("\\ll", true),
679 "Ll": ("\\lll", true),
680 "lll": ("\\lll", true),
681 "gg": ("\\gg", true),
682 "Gg": ("\\ggg", true),
683 "ggg": ("\\ggg", true),
684 "prec": ("\\prec", true),
685 "preceq": ("\\preceq", true),
686 "preccurlyeq": ("\\preccurlyeq", true),
687 "succ": ("\\succ", true),
688 "succeq": ("\\succeq", true),
689 "succcurlyeq": ("\\succcurlyeq", true),
690 "sub": ("\\subset", true),
691 "subset": ("\\subset", true),
692 "sup": ("\\supset", true),
693 "supset": ("\\supset", true),
694 "nsub": ("\\not\\subset", true),
695 "sube": ("\\subseteq", true),
696 "nsup": ("\\not\\supset", true),
697 "supe": ("\\supseteq", true),
698 "setminus": ("\\setminus", true),
699 "forall": ("\\forall", true),
700 "exist": ("\\exists", true),
701 "exists": ("\\exists", true),
702 "nexist": ("\\nexists", true),
703 "nexists": ("\\nexists", true),
704 "empty": ("\\emptyset", true),
705 "emptyset": ("\\emptyset", true),
706 "isin": ("\\in", true),
707 "in": ("\\in", true),
708 "notin": ("\\notin", true),
709 "ni": ("\\ni", true),
710 "nabla": ("\\nabla", true),
711 "ang": ("\\angle", true),
712 "angle": ("\\angle", true),
713 "perp": ("\\perp", true),
714 "parallel": ("\\parallel", true),
715 "sdot": ("\\cdot", true),
716 "cdot": ("\\cdot", true),
717 "lceil": ("\\lceil", true),
718 "rceil": ("\\rceil", true),
719 "lfloor": ("\\lfloor", true),
720 "rfloor": ("\\rfloor", true),
721 "lang": ("\\langle", true),
722 "rang": ("\\rangle", true),
723 "langle": ("\\langle", true),
724 "rangle": ("\\rangle", true),
725 "hbar": ("\\hbar", true),
726 "mho": ("\\mho", true),
727 "larr": ("\\leftarrow", true),
728 "leftarrow": ("\\leftarrow", true),
729 "gets": ("\\gets", true),
730 "lArr": ("\\Leftarrow", true),
731 "Leftarrow": ("\\Leftarrow", true),
732 "uarr": ("\\uparrow", true),
733 "uparrow": ("\\uparrow", true),
734 "uArr": ("\\Uparrow", true),
735 "Uparrow": ("\\Uparrow", true),
736 "rarr": ("\\rightarrow", true),
737 "to": ("\\to", true),
738 "rightarrow": ("\\rightarrow", true),
739 "rArr": ("\\Rightarrow", true),
740 "Rightarrow": ("\\Rightarrow", true),
741 "darr": ("\\downarrow", true),
742 "downarrow": ("\\downarrow", true),
743 "dArr": ("\\Downarrow", true),
744 "Downarrow": ("\\Downarrow", true),
745 "harr": ("\\leftrightarrow", true),
746 "leftrightarrow": ("\\leftrightarrow", true),
747 "hArr": ("\\Leftrightarrow", true),
748 "Leftrightarrow": ("\\Leftrightarrow", true),
749 "crarr": ("\\hookleftarrow", true),
750 "hookleftarrow": ("\\hookleftarrow", true),
751 "arccos": ("\\arccos", true),
752 "arcsin": ("\\arcsin", true),
753 "arctan": ("\\arctan", true),
754 "arg": ("\\arg", true),
755 "cos": ("\\cos", true),
756 "cosh": ("\\cosh", true),
757 "cot": ("\\cot", true),
758 "coth": ("\\coth", true),
759 "csc": ("\\csc", true),
760 "det": ("\\det", true),
761 "dim": ("\\dim", true),
762 "exp": ("\\exp", true),
763 "gcd": ("\\gcd", true),
764 "hom": ("\\hom", true),
765 "inf": ("\\inf", true),
766 "ker": ("\\ker", true),
767 "lg": ("\\lg", true),
768 "lim": ("\\lim", true),
769 "liminf": ("\\liminf", true),
770 "limsup": ("\\limsup", true),
771 "ln": ("\\ln", true),
772 "log": ("\\log", true),
773 "max": ("\\max", true),
774 "min": ("\\min", true),
775 "Pr": ("\\Pr", true),
776 "sec": ("\\sec", true),
777 "sin": ("\\sin", true),
778 "sinh": ("\\sinh", true),
779 "tan": ("\\tan", true),
780 "tanh": ("\\tanh", true),
781 "bull": ("\\textbullet{}", false),
782 "bullet": ("\\textbullet{}", false),
783 "star": ("\\star", true),
784 "lowast": ("\\ast", true),
785 "ast": ("\\ast", true),
786 "odot": ("\\odot", true),
787 "oplus": ("\\oplus", true),
788 "otimes": ("\\otimes", true),
789 "check": ("\\checkmark", true),
790 "checkmark": ("\\checkmark", true),
791 "ordf": ("\\textordfeminine{}", false),
792 "ordm": ("\\textordmasculine{}", false),
793 "cedil": ("\\c{}", false),
794 "oline": ("\\overline{~}", true),
795 "uml": ("\\textasciidieresis{}", false),
796 "zwnj": ("\\/{}", false),
797 "zwj": ("", false),
798 "lrm": ("", false),
799 "rlm": ("", false),
800 "smiley": ("\\ddot\\smile", true),
801 "blacksmile": ("\\ddot\\smile", true),
802 "sad": ("\\ddot\\frown", true),
803 "frowny": ("\\ddot\\frown", true),
804 "clubs": ("\\clubsuit", true),
805 "clubsuit": ("\\clubsuit", true),
806 "spades": ("\\spadesuit", true),
807 "spadesuit": ("\\spadesuit", true),
808 "hearts": ("\\heartsuit", true),
809 "heartsuit": ("\\heartsuit", true),
810 "diams": ("\\diamondsuit", true),
811 "diamondsuit": ("\\diamondsuit", true),
812 "diamond": ("\\diamondsuit", true),
813 "Diamond": ("\\diamondsuit", true),
814 "loz": ("\\lozenge", true),
815 "_ ": ("\\hspace*{0.5em}", false),
816 "_ ": ("\\hspace*{1.0em}", false),
817 "_ ": ("\\hspace*{1.5em}", false),
818 "_ ": ("\\hspace*{2.0em}", false),
819 "_ ": ("\\hspace*{2.5em}", false),
820 "_ ": ("\\hspace*{3.0em}", false),
821 "_ ": ("\\hspace*{3.5em}", false),
822 "_ ": ("\\hspace*{4.0em}", false),
823 "_ ": ("\\hspace*{4.5em}", false),
824 "_ ": ("\\hspace*{5.0em}", false),
825 "_ ": ("\\hspace*{5.5em}", false),
826 "_ ": ("\\hspace*{6.0em}", false),
827 "_ ": ("\\hspace*{6.5em}", false),
828 "_ ": ("\\hspace*{7.0em}", false),
829 "_ ": ("\\hspace*{7.5em}", false),
830 "_ ": ("\\hspace*{8.0em}", false),
831 "_ ": ("\\hspace*{8.5em}", false),
832 "_ ": ("\\hspace*{9.0em}", false),
833 "_ ": ("\\hspace*{9.5em}", false),
834 "_ ": ("\\hspace*{10.0em}", false),
835 ]
419} 836}
Tests/OrgCoreTests/ExportOptionsTests.swift +21
@@ -13,6 +13,27 @@ struct ExportOptionsTests {
13 #expect(ExportOptions.parse("#+OPTIONS: H:2 toc:t\n").toc == 2) 13 #expect(ExportOptions.parse("#+OPTIONS: H:2 toc:t\n").toc == 2)
14 } 14 }
15 15
16 /// ox-latex's keywords: the last class and class options, header lines in order, the first
17 /// compiler.
18 @Test func readsLaTeXKeywords() {
19 let o = ExportOptions.parse("""
20 #+LATEX_CLASS: article
21 #+LATEX_CLASS: report
22 #+LATEX_CLASS_OPTIONS: [a4paper]
23 #+LATEX_HEADER: \\usepackage{a}
24 #+LATEX_HEADER_EXTRA: \\usepackage{c}
25 #+LATEX_HEADER: \\usepackage{b}
26 #+LATEX_COMPILER: xelatex
27 #+LATEX_COMPILER: lualatex
28 #+OPTIONS: toc:nil toc:2 \\n:t
29 """)
30 #expect(o.latexClass == "report" && o.latexClassOptions == "[a4paper]")
31 #expect(o.latexHeader == ["\\usepackage{a}", "\\usepackage{b}"] && o.latexHeaderExtra == ["\\usepackage{c}"])
32 #expect(o.latexCompiler == "xelatex")
33 #expect(o.items["toc"] == "2" && o.items["\\n"] == "t")
34 #expect(ExportOptions.parse("x\n").latexClass == nil)
35 }
36
16 @Test func pagesFollowOptions() { 37 @Test func pagesFollowOptions() {
17 let org = """ 38 let org = """
18 #+TITLE: Doc 39 #+TITLE: Doc
Tests/OrgCoreTests/ExportScopeTests.swift +2 −3
@@ -26,12 +26,11 @@ struct ExportScopeTests {
26 static var project: Int { (file as NSString).range(of: "Body of").location } 26 static var project: Int { (file as NSString).range(of: "Body of").location }
27 27
28 /// As `org-export-as` with SUBTREEP in Emacs 31: the heading's title is the title, its 28 /// As `org-export-as` with SUBTREEP in Emacs 31: the heading's title is the title, its
29 /// EXPORT_AUTHOR the author; planning and drawer left out; children one level up. 29 /// EXPORT_AUTHOR the author, in place of the file's; planning and drawer left out; children
30 /// one level up.
30 @Test func subtreeIsADocumentOfItsOwn() throws { 31 @Test func subtreeIsADocumentOfItsOwn() throws {
31 let text = try #require(ExportScope.subtree(Self.file, at: Self.project)) 32 let text = try #require(ExportScope.subtree(Self.file, at: Self.project))
32 #expect(text == """ 33 #expect(text == """
33 #+TITLE: Whole file
34 #+AUTHOR: Ann
35 #+OPTIONS: toc:nil num:nil 34 #+OPTIONS: toc:nil num:nil
36 #+TITLE: Project 35 #+TITLE: Project
37 #+AUTHOR: Bob 36 #+AUTHOR: Bob
Tests/OrgCoreTests/LaTeXExportTests.swift added +231
@@ -0,0 +1,231 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// ox-latex under `emacs -Q`, for whole documents: each case is exported in its own file.
6enum LaTeXOracle {
7 static let author = "A. Writer"
8
9 struct Case {
10 var text: String
11 var bodyOnly = false
12 /// Emacs point to export the subtree at.
13 var subtree: Int?
14 }
15
16 /// Each case's `org-export-as 'latex`, or `ERROR: message`.
17 static func export(_ cases: [Case]) throws -> [String] {
18 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-latex-\(UUID().uuidString)")
19 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
20 defer { try? FileManager.default.removeItem(at: folder) }
21 var input: [[String]] = []
22 for (index, c) in cases.enumerated() {
23 let url = folder.appendingPathComponent("doc\(index).org")
24 try c.text.write(to: url, atomically: true, encoding: .utf8)
25 input.append([url.path, c.bodyOnly ? "1" : "0", c.subtree.map(String.init) ?? "0"])
26 }
27 let inputURL = folder.appendingPathComponent("input.json")
28 let output = folder.appendingPathComponent("output.json")
29 try JSONEncoder().encode(input).write(to: inputURL)
30 let script = folder.appendingPathComponent("export.el")
31 try #"""
32 ;;; -*- lexical-binding: t -*-
33 (require 'org)
34 (require 'ox-latex)
35 (require 'json)
36 (setq user-full-name "A. Writer")
37 (let ((results nil))
38 (seq-doseq (c (json-read-file (getenv "ORACLE_INPUT")))
39 (with-current-buffer (find-file-noselect (aref c 0))
40 (let ((point (string-to-number (aref c 2))))
41 (push (condition-case e
42 (progn (when (> point 0) (goto-char point))
43 (org-export-as 'latex (> point 0) nil (equal (aref c 1) "1")))
44 (error (concat "ERROR: " (error-message-string e))))
45 results))
46 (kill-buffer)))
47 (let ((coding-system-for-write 'utf-8-unix))
48 (with-temp-file (getenv "ORACLE_OUTPUT")
49 (insert (json-encode (vconcat (nreverse results)))))))
50 """#.write(to: script, atomically: true, encoding: .utf8)
51 let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": inputURL.path, "ORACLE_OUTPUT": output.path, "TZ": "UTC"])
52 guard let data = try? Data(contentsOf: output) else { throw EmacsOracle.EvaluateError(log: log) }
53 return try JSONDecoder().decode([String].self, from: data)
54 }
55
56 /// Ours for the same case, or `ERROR: reason`.
57 static func native(_ c: Case) -> String {
58 do {
59 var text = c.text
60 if let point = c.subtree {
61 guard let narrowed = ExportScope.subtree(text, at: EmacsOracle.offset(point, in: text)) else { return "ERROR: not in a subtree" }
62 text = narrowed
63 }
64 return try LaTeXExport.document(text, bodyOnly: c.bodyOnly, author: author)
65 } catch {
66 return "ERROR: \(error.localizedDescription)"
67 }
68 }
69
70 /// The output without what changes between runs: the `% Created` line, and labels, which
71 /// are numbered in the order they appear.
72 static func normalized(_ s: String) -> String {
73 var s = s.replacing(#/(?m)^% Created .*\n/#, with: "")
74 var labels: [String: String] = [:]
75 s = s.replacing(#/org[0-9a-f]{7}/#) { m in
76 let key = String(m.output)
77 if let existing = labels[key] { return existing }
78 let label = "org\(labels.count + 1)"
79 labels[key] = label
80 return label
81 }
82 return s
83 }
84}
85
86struct LaTeXExportTests {
87 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
88 static let folder = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Conformance")
89 static let corpus = ["minimal", "core", "headings", "listblocks", "lists", "table", "blocks", "timestamps", "footnote", "images", "tblfm"]
90
91 /// Snippets for what the corpus doesn't show.
92 static let snippets: [String] = [
93 "No title here.\n",
94 "#+TITLE: A /styled/ title\n#+SUBTITLE: and more\n#+AUTHOR: Someone & Co\n#+DATE: <2024-03-01 Fri>\n#+KEYWORDS: k1 k2\n#+DESCRIPTION: About $x$\n\nText.\n",
95 "#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil\n#+TITLE: T\n* One\n** Two\n*** Three\n**** Four\n***** Five\n",
96 "#+OPTIONS: toc:2 num:1 H:2\n* One\n** Two\n*** Three\nbody\n*** Four\n* Back\n",
97 "#+LATEX_CLASS: report\n#+LATEX_CLASS_OPTIONS: [a4paper,12pt]\n#+LATEX_HEADER: \\usepackage{xcolor}\n#+LATEX_HEADER_EXTRA: \\usepackage{tikz}\n* Part\n** Chapter\n*** Section\n",
98 "#+LATEX_CLASS: book\n#+LATEX_COMPILER: xelatex\n#+LANGUAGE: fr\n* P\nx\n",
99 "#+LATEX_COMPILER: lualatex\n#+LANGUAGE: nb\nText.\n",
100 "Special: % $ # & { } _ ~ ^ \\ \\% \\- LaTeX TeX LaTeXs ... -- --- 3 < 4 > 2 a\\\\b\n[bracket] at the start\nand *bold*[x] then.\n",
101 "Math \\(a+b\\) and $x^2$ and \\[y\\] and $$z$$ and \\alpha$\\beta$ then \\frac{1}{2} \\alpha{} \\aacute ok.\n",
102 "Scripts x^2 y_{i} a_b and \\nbsp{}here.\n",
103 "#+OPTIONS: ^:{}\nScripts x^2 y_{i} a_b.\n",
104 "#+OPTIONS: ^:nil tex:nil\nScripts x^2 y_{i} and \\(a\\) gone.\n",
105 "Markup *b* /i/ _u_ +s+ =v $ { -- <<= ~c \\ ^ ~= and *nested /italic/ bold*.\n",
106 "Snippets @@latex:\\newpage@@ and @@html:<br>@@ gone. Also @@html:x@@ @@html:y@@ end.\n@@html:z@@ start\n",
107 "Line one\\\\\nline two \\\\\n\\\\\nafter\n",
108 "Links: [[https://orgmode.org][Org & co]] <https://a.b/c_d> https://x.y/%20 [[mailto:me@x.org]] [[file:doc.pdf][the doc]] [[./rel/file.txt]] [[file:/abs/path.org]]\n",
109 "* Target section\nA <<anchor>> here and [[anchor]] and [[anchor][desc]].\n* Other\nSee [[*Target section]] and [[Target section][named]] and [[#cid]].\n* Third\n:PROPERTIES:\n:CUSTOM_ID: cid\n:END:\nx\n",
110 "#+OPTIONS: num:nil\n* Head\nSee [[*Head]].\n",
111 "Footnotes[fn:1] twice[fn:1] and[fn:2][fn:3] and inline[fn::anon /x/] and[fn:named:inline def].\n\n[fn:1] First.\n\n[fn:2] Second\n with two lines.\n\n[fn:3] Third.\n",
112 "1. one\n2. [@5] five\n 1. nested\n 2. [@3] three\n3. after\n\n- [X] done\n- [-] half\n- [ ] todo\n\n- term :: def\n- [X] checked term :: def2\n- [bracketed] item\n",
113 "1. [ ] ordered box\n2. [X] done box\n\n+ plus bullet\n+ second\n\n#+ATTR_LATEX: :environment compactitem :options [x]\n- a\n- b\n",
114 "#+CAPTION: Scores\n#+NAME: tab:scores\n| Name | Score |\n|------+-------|\n| a | 1.5 |\n| b | |\n| c | 1e3 |\n\nSee [[tab:scores]].\n",
115 "#+ATTR_LATEX: :environment tabularx :width \\textwidth :align lX :center nil\n| a | b |\n| c | d |\n\n#+ATTR_LATEX: :float sideways :placement [H] :font \\small\n#+CAPTION: Side\n| 1 | 2 |\n\n#+ATTR_LATEX: :float nil\n#+CAPTION: Not floating\n| x | y |\n",
116 "| *b* | =v= | [[https://x.y][l]] |\n|-----+-----+-----|\n| 1 | -2 | 3% |\n| x | | 4 |\n|-----+-----+-----|\n",
117 "#+NAME: code\n#+CAPTION: A listing\n#+begin_src python -n\nprint(1)\nprint(2)\n#+end_src\n\n#+begin_src emacs-lisp +n 10\n(a)\n#+end_src\n\n#+begin_example -r\nline (ref:x)\n#+end_example\n\n#+begin_src sh\n indented\n more\n#+end_src\n\n#+begin_src\n#+end_src\n",
118 "#+begin_src c -n -k\nint x; (ref:decl)\nreturn x;\n#+end_src\n\nSee line [[(decl)]] and [[(decl)][line %s]].\n",
119 "#+NAME: ex\n#+begin_example\n,* not a heading\n,#+not keyword\n#+end_example\n\n#+ATTR_LATEX: :environment lstlisting\n#+begin_example\nx\n#+end_example\n",
120 "#+begin_quote\nQ /one/.\n\nQ two.\n#+end_quote\n#+ATTR_LATEX: :environment displayquote :options [x]\n#+begin_quote\nd\n#+end_quote\n\n#+begin_center\nC\n#+end_center\n#+begin_verse\n Roses are red,\n violets blue\n\nnext stanza\n#+end_verse\n",
121 "#+begin_warning\nW *b*.\n#+end_warning\n\n#+ATTR_LATEX: :options [Note]\n#+begin_theorem\nT.\n#+end_theorem\n\n#+begin_export latex\n \\begin{x}\n y\n \\end{x}\n#+end_export\n#+begin_export html\n<p>no</p>\n#+end_export\n#+begin_comment\nhidden\n#+end_comment\nafter\n",
122 "#+LATEX: \\clearpage\n#+TOC: headlines 2\n#+TOC: tables\n#+INDEX: term\n: fixed\n: width\n\n-----\n\nText\n-----\nmore\n",
123 "\\begin{equation}\nx = 1\n\\end{equation}\n\n \\begin{align}\n a &= b\n \\end{align}\n",
124 "Para one.\n# a comment\nPara two.\n\n# comment\n\nPara three.\n#+begin_comment\nc\n#+end_comment\n\nfour\n",
125 "* TODO [#B] Task :work:urgent_x:\nSCHEDULED: <2024-01-01 Mon>\n:PROPERTIES:\n:X: 1\n:END:\n:LOGBOOK:\n- note\n:END:\n:NOTES:\nDrawer *text*.\n:END:\nCLOCK: [2024-01-01 Mon 10:00]--[2024-01-01 Mon 11:00] => 1:00\nbody\n* Archived :ARCHIVE:\nhidden\n** child\n* Kept\n* Drop :noexport:\nx\n* COMMENT Gone\ny\n",
126 "#+OPTIONS: pri:t tags:nil todo:nil\n* TODO [#A] Title [1/2] [50%]\n- [X] a\n- [ ] b\n",
127 "#+SELECT_TAGS: pick\nPreamble text.\n* A\n* B :pick:\n** B1\n* C\n",
128 "Dates <2024-01-15 Mon 9:05> [2024-02-29 Thu 10:00-11:30] <2024-01-15 Mon +1w -2d> <2024-01-15 Mon>--<2024-01-17 Wed> [2024-01-15 Mon .+1d]\n",
129 "#+CAPTION: Fig /one/\n#+NAME: fig:one\n#+ATTR_LATEX: :width 5cm\n[[file:img.png]]\n\n#+ATTR_LATEX: :float wrap :width 0.4\\textwidth :placement {r}{0.4\\textwidth}\n[[file:w.jpg]]\n\n#+ATTR_LATEX: :scale 0.5 :center nil\n[[./s.pdf]]\n\n#+ATTR_LATEX: :height 2cm :options angle=90\n[[file:h.eps]]\n\nInline [[file:i.png]] image.\n\n#+ATTR_LATEX: :float multicolumn\n#+CAPTION: Wide\n[[file:m.png]]\n\n#+NAME: noCaption\n[[file:n.png]]\n",
130 "#+MACRO: greet Hello, $1!\n{{{greet(World)}}} on {{{date}}}? {{{title}}} and {{{results(=x=)}}}.\n",
131 "#+begin_src emacs-lisp :exports code\n(+ 1 2)\n#+end_src\n\n#+RESULTS:\n: 3\n\nafter\n",
132 " Indented paragraph\n second line\n deeper\n\n- item first line\n continued\n more\n",
133 "* Low levels\n** two\n*** three\n**** four a\n**** four b\nbody\n***** five\n**** [bracket] four c\n* next\n",
134 "#+OPTIONS: H:1 num:nil\n* one\n** two a\n** two b\n*** three\n",
135 "#+EXCLUDE_TAGS: secret\n* A\n** B :secret:\n** C\n",
136 "#+OPTIONS: timestamp:nil -:nil\nNo special... strings -- \\- here.\n",
137 "Text with a statistics [2/3] cookie and 100% sure.\n",
138 "* Section with <<target in heading>> and *bold* =code= ~x_y~ _u_\n",
139 "- a\n\n- b\n para two\n\n para three\n- c\n - d\n\n - e\nafter list\n",
140 "| | a |\n|---+---|\n| 1 |\n| 2 | 3 | 4 |\n|---+---|\n",
141 "Entities \\ast \\nbsp \\_ \\to \\rarr \\deg{}C \\copy \\pi\\pi and \\alpha \\beta.\n",
142 "#+TITLE: one\n#+TITLE: two\n#+AUTHOR:\nBody.\n",
143 "H_2O x^{-1} a_{b_c} 10^10 e^{i\\pi} f_{\\alpha}\n",
144 "Mixed $a$ text $b $ and $5 and $c$, $d$.\n",
145 "Text @@latex:\\textbf{raw}@@ and @@tex:x@@ and @@LaTeX:y@@.\n",
146 "- a\n #+begin_quote\n q\n #+end_quote\n tail\n",
147 "#+NAME: src1\n#+begin_src sh\nls\n#+end_src\n\nSee [[src1]].\n\n#+NAME: quoted\n#+begin_quote\nq\n#+end_quote\n\n[[quoted][the quote]]\n",
148 "*** starts deep\n* then shallow\n",
149 "#+LANGUAGE: de\n* Teil\nText.\n",
150 "#+LANGUAGE: xx-yy\nText.\n",
151 "#+ATTR_LATEX: :caption \\caption{Raw}\n| a |\n",
152 "Fixed:\n: one\n:\n: three\n",
153 "Text.[fn:1]\n* Footnotes\n[fn:1] Note.\n",
154 "| a | =b\\\\|c= |\n\nThe {{{title}}} macro and ={{{title}}}= as written.\n",
155 "#+begin_src emacs-lisp :exports none\n(hidden)\n#+end_src\n\n#+RESULTS:\n: gone\n\nafter\n\n#+RESULTS: orphan\n: kept\n",
156 "Plain LaTeX's own words and TeXbook.\n",
157 ]
158
159 @Test(.enabled(if: oracle))
160 func matchesEmacs() throws {
161 var cases = try Self.corpus.map { LaTeXOracle.Case(text: try String(contentsOf: Self.folder.appendingPathComponent("\($0).org"), encoding: .utf8)) }
162 cases += Self.snippets.map { LaTeXOracle.Case(text: $0) }
163 let names = Self.corpus + Self.snippets.indices.map { "snippet \($0)" }
164 try compare(cases, names: names)
165 }
166
167 @Test(.enabled(if: oracle))
168 func bodyOnlyAndSubtreesMatchEmacs() throws {
169 let doc = "#+TITLE: Doc\n#+OPTIONS: toc:nil\nIntro.\n* One\nFirst.\n** Sub\n:PROPERTIES:\n:EXPORT_TITLE: Exported title\n:END:\nSub body *b*.\n*** Deeper\nx\n* Two\nSecond.\n"
170 let sub = (doc as NSString).range(of: "** Sub").location
171 let one = (doc as NSString).range(of: "First.").location
172 let cases = [
173 LaTeXOracle.Case(text: doc, bodyOnly: true),
174 LaTeXOracle.Case(text: try String(contentsOf: Self.folder.appendingPathComponent("blocks.org"), encoding: .utf8), bodyOnly: true),
175 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(sub, in: doc)),
176 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(one, in: doc)),
177 LaTeXOracle.Case(text: doc, bodyOnly: true, subtree: EmacsOracle.point(sub, in: doc)),
178 ]
179 try compare(cases, names: ["body", "blocks body", "subtree", "subtree from body", "subtree body"])
180 }
181
182 private func compare(_ cases: [LaTeXOracle.Case], names: [String]) throws {
183 let emacs = try LaTeXOracle.export(cases)
184 for (index, c) in cases.enumerated() {
185 let ours = LaTeXOracle.native(c)
186 if ours.hasPrefix("ERROR: ") {
187 Issue.record("\(names[index]) unsupported: \(ours)\n--- org\n\(c.text)")
188 continue
189 }
190 if let dump = ProcessInfo.processInfo.environment["LATEX_DUMP"], LaTeXOracle.normalized(ours) != LaTeXOracle.normalized(emacs[index]) {
191 let name = names[index].replacingOccurrences(of: " ", with: "_")
192 try? LaTeXOracle.normalized(ours).write(toFile: dump + "/" + name + ".ours", atomically: true, encoding: .utf8)
193 try? LaTeXOracle.normalized(emacs[index]).write(toFile: dump + "/" + name + ".emacs", atomically: true, encoding: .utf8)
194 try? c.text.write(toFile: dump + "/" + name + ".org", atomically: true, encoding: .utf8)
195 }
196 #expect(LaTeXOracle.normalized(ours) == LaTeXOracle.normalized(emacs[index]),
197 "\(names[index])\n--- org\n\(c.text)\n--- ours\n\(ours)\n--- emacs\n\(emacs[index])")
198 }
199 }
200
201 /// What Emacs exports differently or refuses is refused, naming it.
202 @Test func refusesWhatItCannotMatch() {
203 func reason(_ org: String) -> String? {
204 do {
205 _ = try LaTeXExport.document(org)
206 return nil
207 } catch let error as LaTeXExport.Unsupported {
208 return error.reason
209 } catch {
210 return "\(error)"
211 }
212 }
213 #expect(reason("#+LATEX_CLASS: beamer\nx\n") == "Unknown LaTeX class `beamer'")
214 #expect(reason("See [[id:nowhere]].\n")?.hasPrefix("Unable to resolve link") == true)
215 #expect(reason("See [[nowhere]].\n")?.hasPrefix("Unable to resolve link") == true)
216 #expect(reason("Ref[fn:9].\n") == "Definition not found for footnote 9")
217 #expect(reason("#+OPTIONS: \\n:t\nx\n") == "#+OPTIONS: \\n:t")
218 #expect(reason("#+ATTR_LATEX: :mode math\n| a | b |\n") == "#+ATTR_LATEX: :mode math")
219 #expect(reason("#+LATEX_HEADER: \\usepackage[AUTO]{babel}\nx\n") != nil)
220 #expect(reason("#+begin_src sh :exports results\necho\n#+end_src\n") == ":exports results")
221 #expect(reason("[cite:@key]\n") == "Citations")
222 }
223
224 @Test func labelsStayTheSame() throws {
225 let org = "* A\n* B\nSee [[*A]].\n"
226 let first = try LaTeXExport.document(org, now: Date(timeIntervalSince1970: 0))
227 let second = try LaTeXExport.document(org, now: Date(timeIntervalSince1970: 0))
228 #expect(first == second)
229 #expect(first.contains("\\label{sec:org") && first.contains("\\ref{sec:org"))
230 }
231}