Native LaTeX export matching ox-latex !412

merged merged by cmc on 2026-11-20 18:39 UTC · krz/orgstar:parity-latex into main

26 files changed, +2889 −60

Layout: unified · split

README.org +2 −2
@@ -36,8 +36,8 @@ Emacs tomorrow and nothing has been reformatted.
3636- *Tables.* Aligned as you type, with =#+TBLFM= formulas.
3737- *Code blocks.* Run source blocks and tangle them into files, as =org-babel-tangle=
3838 does.
39- *Export.* HTML, Markdown, PDF, Word, RTF and iCalendar built in; PDF through LaTeX, ODT
40 and more through Emacs when it is installed (download version only).
39- *Export.* HTML, Markdown, PDF, Word, RTF, iCalendar and LaTeX built in; PDF through LaTeX,
40 ODT and more through Emacs when it is installed (download version only).
4141- *Search.* Across file names, headings and text, plus Spotlight and Quick Look
4242 previews of =.org= files.
4343
Sources/OrgApp/AppStoreCommands.swift +1 −1
@@ -4,7 +4,7 @@ import Foundation
44/// Emacs, and attaching by link, which the sandbox doesn't allow.
55public enum AppStoreCommands {
66 public static let hidden: Set<String> = [
7 "app.export.pdf", "app.export.odt", "app.export.latex", "app.export.text",
7 "app.export.pdf", "app.export.odt", "app.export.text",
88 "app.attach.link", "app.attach.symlink",
99 ]
1010
Sources/OrgApp/CommandTitles.swift +1 −1
@@ -88,7 +88,7 @@ enum CommandTitles {
8888 String(localized: "Export Table to File…", comment: "Command title"),
8989 String(localized: "Export to HTML", comment: "Command title"),
9090 String(localized: "Export to HTML and Open", comment: "Command title"),
91 String(localized: "Export to LaTeX with Emacs", comment: "Command title"),
91 String(localized: "Export to LaTeX", comment: "Command title"),
9292 String(localized: "Export to Markdown", comment: "Command title"),
9393 String(localized: "Export to ODT with Emacs", comment: "Command title"),
9494 String(localized: "Export to PDF", comment: "Command title"),
Sources/OrgApp/Publish.swift +5 −5
@@ -40,7 +40,7 @@ public struct PublishProject: Sendable, Equatable {
4040
4141 public init(name: String) { self.name = name }
4242
43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-publish-attachment"]
43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-latex-publish-to-latex", "org-publish-attachment"]
4444}
4545
4646public enum Publish {
@@ -252,10 +252,10 @@ public enum Publish {
252252
253253 /// `org-publish-projects`: each project's sitemap, when it has one, then its files, through
254254 /// its publishing functions. A file whose output is newer than it is skipped unless `force`.
255 /// `export` turns an Org file's text into the HTML or Markdown to write.
255 /// `export` turns an Org file's text into the HTML, Markdown or LaTeX to write.
256256 public static func publish(
257257 _ chosen: [PublishProject], all: [PublishProject], force: Bool = false, only: String? = nil,
258 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) -> String
258 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
259259 ) throws -> Report {
260260 var report = Report()
261261 let fm = FileManager.default
@@ -290,7 +290,7 @@ public enum Publish {
290290 if directory((file as NSString).deletingLastPathComponent) == outputDirectory { return nil }
291291 return outputDirectory + (file as NSString).lastPathComponent
292292 }
293 let ext = function == "org-md-publish-to-md" ? "md" : "html"
293 let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex"][function] ?? "html"
294294 guard let text = read(file) else { throw Failure(description: "Can't read \(file)") }
295295 return ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent),
296296 name: ExportScope.fileName(text), extension: ext).path
@@ -299,7 +299,7 @@ public enum Publish {
299299 /// Copies an attachment to `output`, or writes what `function` exports from `file`.
300300 private static func write(
301301 _ file: String, to output: String, function: String, bodyOnly: Bool,
302 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) -> String
302 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
303303 ) throws {
304304 let fm = FileManager.default
305305 if function == "org-publish-attachment" {
Sources/OrgCore/Export/ExportOptions.swift +21 −3
@@ -33,6 +33,18 @@ public struct ExportOptions: Sendable, Equatable {
3333 public var selectTags = ["export"]
3434 /// `#+HTML_HEAD` and `#+HTML_HEAD_EXTRA` lines, in order.
3535 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] = [:]
3648
3749 /// `org-export-with-*` defaults.
3850 public static let org = ExportOptions(toc: 3, num: 3)
@@ -45,22 +57,28 @@ public struct ExportOptions: Sendable, Equatable {
4557 return options
4658 }()
4759
48 /// `defaults` with the document's `#+OPTIONS`, `#+EXCLUDE_TAGS`, `#+SELECT_TAGS` and
49 /// `#+HTML_HEAD` applied.
60 /// `defaults` with the document's `#+OPTIONS`, `#+EXCLUDE_TAGS`, `#+SELECT_TAGS`,
61 /// `#+HTML_HEAD` and `#+LATEX_*` applied.
5062 public static func parse(_ text: String, defaults: ExportOptions = .org) -> ExportOptions {
5163 var options = defaults
5264 var tocSet: String?
5365 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]*$/#) {
5567 let value = String(m.2)
5668 switch m.1.uppercased() {
5769 case "EXCLUDE_TAGS": options.excludeTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
5870 case "SELECT_TAGS": options.selectTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
5971 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 }
6077 default:
6178 for item in value.matches(of: /(\S+?):(\S+)/) {
6279 let key = String(item.1)
6380 let v = String(item.2)
81 options.items[key] = v
6482 let on = v != "nil"
6583 switch key {
6684 case "toc": tocSet = v
Sources/OrgCore/Export/ExportScope.swift +21 −2
@@ -10,6 +10,10 @@ public enum ExportScope {
1010 ("EXPORT_TITLE", "TITLE"), ("EXPORT_AUTHOR", "AUTHOR"), ("EXPORT_DATE", "DATE"), ("EXPORT_EMAIL", "EMAIL"),
1111 ("EXPORT_OPTIONS", "OPTIONS"), ("EXPORT_SELECT_TAGS", "SELECT_TAGS"), ("EXPORT_EXCLUDE_TAGS", "EXCLUDE_TAGS"),
1212 ("EXPORT_HTML_HEAD", "HTML_HEAD"), ("EXPORT_HTML_HEAD_EXTRA", "HTML_HEAD_EXTRA"),
13 ("EXPORT_SUBTITLE", "SUBTITLE"), ("EXPORT_KEYWORDS", "KEYWORDS"), ("EXPORT_DESCRIPTION", "DESCRIPTION"), ("EXPORT_LANGUAGE", "LANGUAGE"),
14 ("EXPORT_LATEX_CLASS", "LATEX_CLASS"), ("EXPORT_LATEX_CLASS_OPTIONS", "LATEX_CLASS_OPTIONS"), ("EXPORT_LATEX_HEADER", "LATEX_HEADER"),
15 ("EXPORT_LATEX_HEADER_EXTRA", "LATEX_HEADER_EXTRA"), ("EXPORT_LATEX_COMPILER", "LATEX_COMPILER"),
16 ("EXPORT_LATEX_CLASS_PRE", "LATEX_CLASS_PRE"), ("EXPORT_LATEX_FOOTNOTE_COMMAND", "LATEX_FOOTNOTE_COMMAND"), ("EXPORT_CITE_EXPORT", "CITE_EXPORT"),
1317 ]
1418
1519 /// The subtree containing `offset` as a document of its own: the file's keyword lines, then
@@ -28,8 +32,23 @@ public enum ExportScope {
2832 body = body.replacing(#/^(?:[ \t]*(?:SCHEDULED|DEADLINE|CLOSED):[^\n]*\n)?(?:[ \t]*:PROPERTIES:[ \t]*\n(?:[^\n]*\n)*?[ \t]*:END:[ \t]*(?:\n|$))?/#, with: "", maxReplacements: 1)
2933 body = ExportPreprocess.shift(body, to: 1)
3034
31 var lines = preamble(tree)
32 let property = { (key: String) in heading.properties.last { $0.key.uppercased() == key }?.value }
35 // `org-entry-get`: the last `KEY` value, then each `KEY+` value, joined with spaces;
36 // "nil" is no value.
37 let property = { (key: String) -> String? in
38 let matching = heading.properties.filter { $0.key.uppercased() == key }
39 let base = matching.last { !$0.additive }?.value
40 let values = [base == "nil" ? nil : base] + matching.filter(\.additive).map(\.value)
41 guard values.contains(where: { $0 != nil }) else { return nil }
42 let value = values.compactMap { $0 }.joined(separator: " ")
43 return value == "nil" ? nil : value
44 }
45 // What the subtree sets replaces the file's keywords; `EXPORT_OPTIONS` only the items
46 // it names.
47 let replaced = Set(overrides.filter { $0.property == "EXPORT_TITLE" || ($0.property != "EXPORT_OPTIONS" && property($0.property) != nil) }.map(\.keyword))
48 var lines = preamble(tree).filter { line in
49 guard let m = line.firstMatch(of: #/^#\+([^:\s]+):/#) else { return true }
50 return !replaced.contains(m.1.uppercased())
51 }
3352 lines.append("#+TITLE: " + (property("EXPORT_TITLE") ?? Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces)))
3453 for (key, keyword) in overrides where key != "EXPORT_TITLE" {
3554 if let value = property(key) { lines.append("#+\(keyword): \(value)") }
Sources/OrgCore/Export/LaTeXExport.swift added +1846
@@ -0,0 +1,1846 @@
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, CustomStringConvertible {
9 public let reason: String
10 public init(reason: String) { self.reason = reason }
11 public var errorDescription: String? { reason }
12 public var description: String { reason }
13 }
14
15 /// `org-latex-classes`: each class's header and its sectioning, numbered and not.
16 static let classes: [String: (header: String, sections: [(String, String)])] = {
17 let part = ("\\part{%s}", "\\part*{%s}")
18 let chapter = ("\\chapter{%s}", "\\chapter*{%s}")
19 let section = ("\\section{%s}", "\\section*{%s}")
20 let subsection = ("\\subsection{%s}", "\\subsection*{%s}")
21 let subsubsection = ("\\subsubsection{%s}", "\\subsubsection*{%s}")
22 return [
23 "article": ("\\documentclass[11pt]{article}", [section, subsection, subsubsection, ("\\paragraph{%s}", "\\paragraph*{%s}"), ("\\subparagraph{%s}", "\\subparagraph*{%s}")]),
24 "report": ("\\documentclass[11pt]{report}", [part, chapter, section, subsection, subsubsection]),
25 "book": ("\\documentclass[11pt]{book}", [part, chapter, section, subsection, subsubsection]),
26 ]
27 }()
28
29 /// `org-latex-default-packages-alist`: options, package and the compilers it is for.
30 static let packages: [(String, String, [String])] = [
31 ("", "amsmath", ["lualatex", "xelatex"]), ("", "fontspec", ["lualatex", "xelatex"]),
32 ("utf8", "inputenc", ["pdflatex"]), ("T1", "fontenc", ["pdflatex"]),
33 ("", "graphicx", []), ("", "longtable", []), ("", "wrapfig", []), ("", "rotating", []), ("normalem", "ulem", []),
34 ("", "amsmath", ["pdflatex"]), ("", "amssymb", ["pdflatex"]), ("", "capt-of", []), ("", "hyperref", []),
35 ]
36
37 static let compilers = ["pdflatex", "xelatex", "lualatex"]
38
39 /// A `.tex` document, or with `bodyOnly` what goes between `\begin{document}` and
40 /// `\end{document}` without the title and contents. `author` stands for `user-full-name`,
41 /// `language` for `org-export-default-language`, `now` for the `% Created` line. `file` adds
42 /// the final newline `org-export-to-file` writes.
43 public static func document(
44 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
45 author: String = "", language: String = "en", timeZone: TimeZone = .current, file: Bool = false
46 ) throws -> String {
47 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
48 let included = ExportPreprocess.includes(text, directory: directory)
49 // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays.
50 let marker = "\u{E000}"
51 var literal = included
52 if included.contains("{{{") {
53 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") }
54 let ns = included as NSString
55 let kept = OrgParser.parse(included, defaults: settings).root.descendants()
56 .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range)
57 var out = ""
58 var at = 0
59 for range in kept.sorted(by: { $0.lowerBound < $1.lowerBound }) where range.lowerBound >= at {
60 out += ns.substring(with: NSRange(location: at, length: range.lowerBound - at))
61 out += ns.substring(with: NSRange(location: range.lowerBound, length: range.count)).replacingOccurrences(of: "{{{", with: marker + "{{")
62 at = range.upperBound
63 }
64 literal = out + ns.substring(from: at)
65 }
66 let text = ExportPreprocess.macros(literal, path: path, now: now, setup: settings.setupKeywords).replacingOccurrences(of: marker, with: "{")
67 let tree = OrgParser.parse(text, defaults: settings)
68 let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
69 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
70 let renderer = try LaTeXRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language)
71 let body = try renderer.body()
72 let output = bodyOnly ? body : try renderer.template(body, author: author, now: now, timeZone: timeZone)
73 return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
74 }
75}
76
77final class LaTeXRenderer {
78 typealias Unsupported = LaTeXExport.Unsupported
79
80 let tree: OrgTree
81 let source: NSString
82 let settings: OrgSettings
83 let options: ExportOptions
84 /// Keyword values by name, in order.
85 let keywords: [String: [String]]
86 let language: String
87 let className: String
88 /// `num` and `toc` as written: nil for t.
89 let num: Int?
90 let numbered: Bool
91 let toc: Int?
92 let withTOC: Bool
93 let timeStampFile: Bool
94 private var selected: Set<Int>?
95 /// Added to heading levels.
96 private var levelOffset = 0
97 private var exportSource: ExportSource
98 private let model: DocumentModel
99
100 init(tree: OrgTree, text: String, settings: OrgSettings, keywords lines: [String], language: String) throws {
101 self.tree = tree
102 source = text as NSString
103 self.settings = settings
104 exportSource = ExportSource(tree: tree, text: text)
105 model = DocumentModel(tree: tree)
106 var keywords: [String: [String]] = [:]
107 for line in lines {
108 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { continue }
109 keywords[m.1.uppercased(), default: []].append(m.2.map(String.init) ?? "")
110 }
111 self.keywords = keywords
112 options = ExportOptions.parse(lines.joined(separator: "\n"))
113 self.language = keywords["LANGUAGE"]?.last ?? language
114 className = options.latexClass ?? "article"
115 guard LaTeXExport.classes[className] != nil else { throw Unsupported(reason: "Unknown LaTeX class `\(className)'") }
116
117 // `#+OPTIONS` this export follows; any other item only at its default.
118 let defaults = ["\\n": "nil", ":": "t", "*": "t", "e": "t", "f": "t", "|": "t", "p": "nil", "c": "nil", "prop": "nil",
119 "stat": "t", "tasks": "t", "inline": "t", "arch": "headline", "email": "nil", "creator": "nil",
120 "broken-links": "nil", "'": "nil", "<": "t", "d": "(not \"LOGBOOK\")", "latex-use-sans": "nil", "expand-links": "t"]
121 for (key, value) in options.items {
122 if let standard = defaults[key], standard != value { throw Unsupported(reason: "#+OPTIONS: \(key):\(value)") }
123 }
124 let items = options.items
125 func depth(_ key: String) throws -> (Bool, Int?) {
126 guard let v = items[key] else { return (true, nil) }
127 if v == "nil" { return (false, nil) }
128 if v == "t" { return (true, nil) }
129 guard let n = Int(v) else { throw Unsupported(reason: "#+OPTIONS: \(key):\(v)") }
130 return (true, n)
131 }
132 (numbered, num) = try depth("num")
133 (withTOC, toc) = try depth("toc")
134 timeStampFile = items["timestamp"] != "nil"
135 if let tex = items["tex"], tex != "t", tex != "nil" { throw Unsupported(reason: "#+OPTIONS: tex:\(tex)") }
136 for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "LATEX_CLASS_PRE", "LATEX_FOOTNOTE_COMMAND", "CALL", "EXPORT_LATEX_CLASS"] where keywords[key] != nil {
137 throw Unsupported(reason: "#+\(key)")
138 }
139 for line in options.latexHeader + options.latexHeaderExtra + (options.latexClassOptions.map { [$0] } ?? [])
140 where line.contains("{babel}") || line.contains("{polyglossia}") || line.contains("\\babelprovide") || line.contains("[AUTO]") {
141 throw Unsupported(reason: "Babel or Polyglossia in the LaTeX header")
142 }
143 // Radio links: links that are only words.
144 if tree.root.descendants().contains(where: { $0.kind == .link && !$0.tokens.contains { $0.kind == .linkPath } && !$0.text.hasPrefix("<") && !$0.text.contains(":") }) {
145 throw Unsupported(reason: "Radio targets")
146 }
147 let kinds = Set(tree.root.descendants().map(\.kind))
148 for (kind, name) in [(SyntaxKind.radioTarget, "Radio targets"), (.citation, "Citations"), (.inlineTask, "Inline tasks"),
149 (.inlineSourceBlock, "Inline source blocks"), (.inlineBabelCall, "Inline calls"), (.tableEl, "table.el tables"),
150 (.diarySexp, "Diary sexps")] where kinds.contains(kind) {
151 throw Unsupported(reason: name)
152 }
153 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
154 // `:headline-offset`: the shallowest exported heading is level 1.
155 let options = options
156 let selected = selected
157 let top = tree.root.children.compactMap { $0.kind == .section ? $0.firstChild(.heading) : nil }
158 .filter { HTMLRenderer.sectionExport($0, options: options, selected: selected) != .nothing }
159 levelOffset = 1 - (top.compactMap { $0.tokens.first { $0.kind == .stars }?.text.count }.min() ?? 1)
160 try countFootnotes()
161 }
162
163 // MARK: - Template
164
165 /// `org-latex-template`.
166 func template(_ body: String, author: String, now: Date, timeZone: TimeZone) throws -> String {
167 var out = ""
168 if timeStampFile {
169 let formatter = DateFormatter()
170 formatter.locale = Locale(identifier: "en_US_POSIX")
171 formatter.timeZone = timeZone
172 formatter.dateFormat = "yyyy-MM-dd EEE HH:mm"
173 out += "% Created \(formatter.string(from: now))\n"
174 }
175 let compiler = options.latexCompiler ?? "pdflatex"
176 if LaTeXExport.compilers.contains(compiler) { out += "% Intended LaTeX compiler: \(compiler)\n" }
177 out += preamble(compiler: compiler)
178 if numbered, let num { out += "\\setcounter{secnumdepth}{\(num)}\n" }
179 var authorText: String? = try keywords["AUTHOR"].map { try parsed($0) } ?? (author.isEmpty ? nil : try inlineString(author))
180 if authorText?.isEmpty == true { authorText = nil }
181 if options.author, let authorText { out += "\\author{\(authorText)}\n" }
182 // The default, `\today`, is a LaTeX fragment, which `tex:nil` takes out.
183 let date = try keywords["DATE"].map { try parsed($0) } ?? (options.tex ? "\\today" : "")
184 out += "\\date{\(options.date ? date : "")}\n"
185 let title = try keywords["TITLE"].map { try parsed($0) } ?? ""
186 // An empty `#+SUBTITLE` parses to nil, which ox-latex leaves out.
187 let subtitle = try keywords["SUBTITLE"].flatMap({ $0 == [""] ? nil : $0 }).map { "\\\\\\medskip\n\\large " + (try parsed($0)) } ?? ""
188 out += "\\title{\(title)\(subtitle)}\n"
189 let lang = Self.languageNames[self.language] ?? self.language
190 out += "\\hypersetup{\n pdfauthor={\(options.author ? authorText ?? "" : "")},\n pdftitle={\(options.title ? title : "")},\n"
191 out += " pdfkeywords={\(try keywords["KEYWORDS"].map { try parsed($0) } ?? "")},\n"
192 out += " pdfsubject={\(try keywords["DESCRIPTION"].map { try parsed($0) } ?? "")},\n pdfcreator={},\n pdflang={\(Self.capitalize(lang))}}\n"
193 out += "\\begin{document}\n\n"
194 if options.title, !title.isEmpty { out += "\\maketitle\n" }
195 if withTOC {
196 if let toc { out += "\\setcounter{tocdepth}{\(toc)}\n" }
197 out += "\\tableofcontents\n\n"
198 }
199 return out + body + "\\end{document}"
200 }
201
202 /// A keyword parsed as Org text, its lines joined with spaces.
203 private func parsed(_ values: [String]) throws -> String {
204 if values.count > 1, values.contains("") { throw Unsupported(reason: "Repeated keywords with an empty value") }
205 return try inlineString(values.joined(separator: " "))
206 }
207
208 /// `org-latex-make-preamble` with the class, its options and the header lines.
209 private func preamble(compiler: String) -> String {
210 var header = LaTeXExport.classes[className]!.header
211 if let classOptions = options.latexClassOptions {
212 header = header.replacingOccurrences(of: "[11pt]", with: classOptions)
213 }
214 let known = LaTeXExport.compilers.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame }
215 let packages = LaTeXExport.packages.filter { !known || $0.2.isEmpty || $0.2.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame } }
216 .map { $0.0.isEmpty ? "\\usepackage{\($0.1)}" : "\\usepackage[\($0.0)]{\($0.1)}" }
217 var out = header + "\n\n" + packages.joined(separator: "\n")
218 let extra = [options.latexHeader, options.latexHeaderExtra].filter { !$0.isEmpty }.map { Self.normalize($0.joined(separator: "\n")) }.joined()
219 if extra.contains(where: { !$0.isWhitespace }) { out += "\n" + extra }
220 return Self.normalize(out)
221 }
222
223 /// `:lang-name` in `org-latex-language-alist`.
224 static let languageNames: [String: String] = [
225 "af": "Afrikaans", "am": "Amharic", "ar": "Arabic", "ast": "Asturian", "bg": "Bulgarian", "bn": "Bengali", "bo": "Tibetan",
226 "br": "Breton", "ca": "Catalan", "cop": "Coptic", "cs": "Czech", "cy": "Welsh", "da": "Danish", "de": "German", "de-de": "German",
227 "de-at": "German", "dsb": "Lower Sorbian", "dv": "Dhivehi", "el": "Greek", "el-polyton": "Polytonic Greek", "grc": "Ancient Greek",
228 "en": "English", "en-au": "English", "en-ca": "English", "en-gb": "English", "en-nz": "English", "en-us": "English",
229 "eo": "Esperanto", "es": "Spanish", "es-mx": "Spanish", "et": "Estonian", "eu": "Basque", "fa": "Persian", "fi": "Finnish",
230 "fr": "French", "fr-ca": "French", "fur": "Friulian", "ga": "Irish Gaelic", "gd": "Scottish Gaelic", "gl": "Galician",
231 "he": "Hebrew", "hi": "Hindi", "hr": "Croatian", "hsb": "Upper Sorbian", "hu": "Magyar", "hy": "Armenian", "ia": "Interlingua",
232 "id": "Indonesian", "is": "Icelandic", "it": "Italian", "kn": "Kannada", "la": "Latin", "la-classic": "Classic Latin",
233 "la-medieval": "Medieval Latin", "la-ecclesiastic": "Ecclesiastic Latin", "lo": "Lao", "lt": "Lithuanian", "lv": "Latvian",
234 "ml": "Malayalam", "mr": "Marathi", "ms": "Malay", "nb": "Norwegian Bokmål", "nl": "Dutch", "nn": "Norwegian Nynorsk",
235 "no": "Norwegian", "oc": "Occitan", "pl": "Polish", "pms": "Piedmontese", "pt": "Portuges", "pt-br": "Portuges", "rm": "Romansh",
236 "ro": "Romanian", "ru": "Russian", "sa": "Sanskrit", "sk": "Slovak", "sl": "Slovene", "sq": "Albanian", "sr": "Serbian",
237 "sr-cyrl": "Serbian", "sr-latn": "Serbian", "sv": "Swedish", "syr": "Syriac", "ta": "Tamil", "te": "Telugu", "th": "Thai",
238 "tk": "Turkmen", "tr": "Turkish", "uk": "Ukrainian", "ur": "Urdu", "vi": "Vietnamese", "zh": "Chinese Simplified",
239 "zh-cn": "Chinese Simplified", "zh-tw": "Chinese Traditional",
240 ]
241
242 /// Emacs's `capitalize`: each word's first letter up, the rest down.
243 static func capitalize(_ s: String) -> String {
244 var out = ""
245 var inWord = false
246 for c in s {
247 let word = c.isLetter || c.isNumber
248 out += word ? (inWord ? c.lowercased() : c.uppercased()) : String(c)
249 inWord = word
250 }
251 return out
252 }
253
254 // MARK: - Strings
255
256 /// `org-element-normalize-string`: one final newline, none for the empty string.
257 static func normalize(_ s: String) -> String {
258 guard !s.isEmpty else { return "" }
259 var end = s.endIndex
260 var cut = s.endIndex
261 while end > s.startIndex {
262 let before = s.index(before: end)
263 if s[before] == " " || s[before] == "\t" {
264 end = before
265 } else if s[before] == "\n" {
266 end = before
267 cut = before
268 } else {
269 break
270 }
271 }
272 return String(s[..<cut]) + "\n"
273 }
274
275 /// `org-trim`.
276 static func trim(_ s: String) -> String { s.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r\u{0C}\u{0B}")) }
277
278 /// `org-latex--protect-text`.
279 static func protect(_ s: String) -> String {
280 var out = ""
281 for c in s {
282 if "\\{}$%&_#~^".contains(c) { out += "\\" }
283 out.append(c)
284 }
285 return out
286 }
287
288 /// `org-latex--protect-texttt`.
289 static func texttt(_ s: String) -> String {
290 var out = ""
291 var i = s.startIndex
292 while i < s.endIndex {
293 let rest = s[i...]
294 if rest.hasPrefix("--") || rest.hasPrefix("<<") || rest.hasPrefix(">>") {
295 out += "\(s[i]){}\(s[i]){}"
296 i = s.index(i, offsetBy: 2)
297 continue
298 }
299 switch s[i] {
300 case "\\": out += "\\textbackslash{}"
301 case "~": out += "\\textasciitilde{}"
302 case "^": out += "\\textasciicircum{}"
303 case "{", "}", "$", "%", "&", "_", "#": out += "\\\(s[i])"
304 default: out.append(s[i])
305 }
306 i = s.index(after: i)
307 }
308 return "\\texttt{\(out)}"
309 }
310
311 /// `org-remove-indentation`: the common indentation of the non-blank lines removed.
312 static func removeIndentation(_ s: String) throws -> String {
313 let lines = s.components(separatedBy: "\n")
314 let indents = lines.filter { $0.contains { $0 != " " && $0 != "\t" } }.map { $0.prefix { $0 == " " || $0 == "\t" } }
315 guard let common = indents.map(\.count).min(), common > 0 else { return s }
316 if indents.contains(where: { $0.contains("\t") }) { throw Unsupported(reason: "Tabs in indented code") }
317 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }.joined(separator: "\n")
318 }
319
320 // MARK: - Labels
321
322 private var references: [String: String] = [:]
323 private var usedReferences: Set<String> = []
324
325 /// `org-export-get-reference`: a label for `key`, made from it so it stays the same between
326 /// exports of the same document.
327 func reference(_ key: String) -> String {
328 if let existing = references[key] { return existing }
329 var hash: UInt32 = 2_166_136_261
330 for byte in key.utf8 { hash = (hash ^ UInt32(byte)) &* 16_777_619 }
331 var value = hash & 0xFFFFFFF
332 var label = String(format: "org%07x", value)
333 while usedReferences.contains(label) {
334 value = (value &+ 1) & 0xFFFFFFF
335 label = String(format: "org%07x", value)
336 }
337 usedReferences.insert(label)
338 references[key] = label
339 return label
340 }
341
342 // MARK: - Document
343
344 /// The transcoded document, `org-element-normalize-string`'d.
345 func body() throws -> String {
346 var nodes = tree.root.children
347 // With a select tag, the text before the first heading isn't exported.
348 if selected != nil { nodes.removeAll { $0.kind == .zerothSection } }
349 var out = ""
350 for node in nodes {
351 if node.kind == .zerothSection {
352 out += Self.normalize(try elements(node.children, end: node.range.upperBound))
353 } else if node.kind == .section {
354 out += try section(node) ?? ""
355 }
356 }
357 return Self.normalize(out)
358 }
359
360 /// Blank lines at the end of `source[from..<to]`.
361 func blankLines(from: Int, to: Int) -> Int {
362 guard to > from else { return 0 }
363 let source = currentSource ?? self.source
364 let lines = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)).components(separatedBy: "\n").dropLast()
365 return lines.reversed().prefix { $0.allSatisfy { $0 == " " || $0 == "\t" } }.count
366 }
367
368 /// Affiliated keywords of the element being transcoded.
369 struct Affiliated {
370 var caption: [String] = []
371 var name: String?
372 var attr: [String] = []
373 /// `#+RESULTS`' value, when it has the keyword.
374 var results: String?
375
376 /// `org-export-read-attribute :attr_latex`: values by key, nil for `nil` or nothing.
377 func attribute(_ key: String) -> String?? {
378 guard !attr.isEmpty else { return .none }
379 var s = attr.joined(separator: " ")
380 var pairs: [(String, String?)] = []
381 var pending: String?
382 let re = #/(?:^|[ \t]+)(:[-a-zA-Z0-9_]+)(?:[ \t]+|$)/#
383 while let m = s.firstMatch(of: re) {
384 if let pending { pairs.append((pending, Self.value(String(s[..<m.range.lowerBound])))) }
385 pending = String(m.1)
386 s = String(s[m.range.upperBound...])
387 }
388 if let pending { pairs.append((pending, Self.value(s))) }
389 guard let pair = pairs.first(where: { $0.0 == ":" + key }) else { return .none }
390 return .some(pair.1)
391 }
392
393 static func value(_ s: String) -> String? {
394 if s.isEmpty || s == "nil" { return nil }
395 if let m = s.wholeMatch(of: /"("+)?"/) { return m.1.map(String.init) ?? "" }
396 return s
397 }
398
399 /// The attribute's value, nil when absent or nil.
400 func value(_ key: String) -> String? { attribute(key) ?? nil }
401 func has(_ key: String) -> Bool { attribute(key) != nil }
402 }
403
404 /// `elements`, each `org-element-normalize-string`'d and followed by its blank lines, as
405 /// `org-export-data` joins a greater element's contents.
406 func elements(_ nodes: [SyntaxNode], end: Int) throws -> String {
407 var out = ""
408 var affiliated = Affiliated()
409 // The element before and its blank lines, which a comment after it may add to; they
410 // show only when it wrote something.
411 var pendingBlank = 0
412 var previous: SyntaxNode?
413 var previousWrote = false
414 var afterSrc = false
415 for (index, node) in nodes.enumerated() {
416 let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
417 if node.kind == .affiliatedKeyword {
418 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
419 guard let m = line.firstMatch(of: /^#\+([A-Za-z_]+)(\[[^\]]*\])?:[ \t]*(.*)$/) else { continue }
420 let key = m.1.uppercased()
421 if m.2 != nil, key != "CAPTION", key != "RESULTS" { throw Unsupported(reason: "#+\(key)[…]") }
422 switch key {
423 case "CAPTION":
424 if m.2 != nil { throw Unsupported(reason: "Short captions") }
425 affiliated.caption.append(String(m.3))
426 case "NAME": affiliated.name = String(m.3)
427 case "ATTR_LATEX": affiliated.attr.append(String(m.3))
428 case "RESULTS": affiliated.results = String(m.3)
429 default: break
430 }
431 continue
432 }
433 defer { affiliated = Affiliated() }
434 // `org-babel-exp-process-buffer`: a src block's results go, and with `:exports none`
435 // the block too, as if they had never been there.
436 if node.kind == .block, blockType(node) == "src" {
437 let exports = exportSource.exports(at: node.range.lowerBound) ?? "code"
438 if exports != "code", exports != "none" { throw Unsupported(reason: ":exports \(exports)") }
439 afterSrc = true
440 if exports == "none" { continue }
441 } else if let results = affiliated.results {
442 if afterSrc {
443 afterSrc = false
444 continue
445 }
446 if results.isEmpty { throw Unsupported(reason: "#+RESULTS without a source block") }
447 if affiliated.name == nil { affiliated.name = results }
448 } else {
449 afterSrc = false
450 }
451 if node.kind == .comment || (node.kind == .block && blockType(node) == "comment") {
452 // `org-export--skip-p`: the element before keeps at least one blank line.
453 if previous != nil {
454 let blank = max(pendingBlank, blankLines(from: node.range.lowerBound, to: next), 1)
455 if previousWrote { out += String(repeating: "\n", count: blank - pendingBlank) }
456 pendingBlank = blank
457 }
458 continue
459 }
460 guard let result = try element(node, affiliated: affiliated, previous: previous, previousBlank: pendingBlank) else {
461 if !pruned(node) {
462 previous = node
463 previousWrote = false
464 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
465 }
466 continue
467 }
468 previous = node
469 previousWrote = true
470 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
471 var text = Self.normalize(result) + String(repeating: "\n", count: pendingBlank)
472 if node.kind == .paragraph { text = Self.cleanLineBreaks(text) }
473 out += text
474 }
475 return out
476 }
477
478 /// Elements `org-export--prune-tree` takes out of the tree.
479 private func pruned(_ node: SyntaxNode) -> Bool {
480 switch node.kind {
481 case .planning, .propertyDrawer, .clock, .footnoteDefinition: return true
482 case .drawer: return drawerName(node).uppercased() == "LOGBOOK"
483 case .latexEnvironment: return !options.tex
484 default: return false
485 }
486 }
487
488 private func drawerName(_ node: SyntaxNode) -> String {
489 node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1) } ?? ""
490 }
491
492 /// `org-latex-clean-invalid-line-breaks`.
493 static func cleanLineBreaks(_ s: String) -> String {
494 s.replacing(#/(?m)(\\end\{[A-Za-z0-9*]+\}|^)[ \t]*\\\\[ \t]*$/#) { String($0.1) }
495 }
496
497 // MARK: - Headlines
498
499 /// A section's heading and contents, nil when not exported.
500 private func section(_ node: SyntaxNode) throws -> String? {
501 guard let heading = node.firstChild(.heading) else { return nil }
502 // `org-footnote-section`'s heading isn't exported.
503 if heading.firstChild(.title)?.text == "Footnotes" { return nil }
504 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
505 if export == .nothing { return nil }
506 let children = node.children.filter { $0.kind != .heading }
507 let body = children.filter { $0.kind != .section }
508 let subsections = children.filter { $0.kind == .section }
509 var contents: String?
510 if export == .all {
511 let out = Self.normalize(try elements(body, end: subsections.first?.range.lowerBound ?? node.range.upperBound))
512 contents = Self.normalize(out + (try subsections.compactMap { try section($0) }.joined()))
513 }
514 let first = children.first?.range.lowerBound ?? node.range.upperBound
515 let preBlank = children.isEmpty ? 0 : blankLines(from: heading.range.lowerBound, to: first)
516 return Self.normalize(try headline(heading, section: node, contents: contents, preBlank: preBlank))
517 }
518
519 /// `org-latex-headline`.
520 private func headline(_ heading: SyntaxNode, section: SyntaxNode, contents: String?, preBlank: Int) throws -> String {
521 let tokens = heading.tokens
522 let level = (tokens.first { $0.kind == .stars }?.text.count ?? 1) + levelOffset
523 if let index = model.headings.firstIndex(where: { $0.headingRange.lowerBound == heading.range.lowerBound }) {
524 let keys = model.headings[index].properties.map { $0.key.uppercased() }
525 if keys.contains("UNNUMBERED") || keys.contains("ALT_TITLE") { throw Unsupported(reason: "UNNUMBERED and ALT_TITLE properties") }
526 }
527 let isNumbered = numbered && (num.map { level <= $0 } ?? true)
528 let titleNode = heading.firstChild(.title)
529 if titleNode?.descendants().contains(where: { $0.kind == .footnoteReference }) == true { throw Unsupported(reason: "Footnotes in headings") }
530 let text = try titleNode.map { try Self.trim(inline($0, sectionTitle: true)) } ?? ""
531 var full = ""
532 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
533 full += "{\\bfseries\\sffamily \(plainText(todo))} "
534 }
535 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text,
536 let letter = priority.firstMatch(of: /\[#(.+)\]/)?.1 {
537 full += "\\framebox{\\#\(letter)} "
538 }
539 full += text
540 // The title for the table of contents, without the tags unless `tags` is t.
541 let tocTitle = (options.items["tags"] ?? "t") == "t" ? nil : full
542 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
543 let shown = tags.split(separator: ":").map(String.init)
544 if !shown.isEmpty { full += "\\hfill{}\\textsc{\(shown.map(Self.protect).joined(separator: ":"))}" }
545 }
546 let label = "\\label{sec:\(reference("heading@\(heading.range.lowerBound)"))}\n"
547 let pre = String(repeating: "\n", count: preBlank)
548 let sections = LaTeXExport.classes[className]!.sections
549 if level > options.headlineLevels || level > sections.count {
550 let siblings = exportedSiblings(section)
551 let first = siblings.first == section.range.lowerBound
552 let last = siblings.last == section.range.lowerBound
553 let list = isNumbered ? "enumerate" : "itemize"
554 var out = first ? "\\begin{\(list)}\n" : ""
555 out += "\\item" + (full.firstMatch(of: /^[ \t]*\[/) != nil ? "\\relax" : "") + " " + full + "\n" + label + pre + (contents ?? "")
556 if last {
557 while let c = out.last, c == " " || c == "\t" || c == "\n" { out.removeLast() }
558 out += "\n\\end{\(list)}"
559 }
560 return out
561 }
562 var format = isNumbered ? sections[level - 1].0 : sections[level - 1].1
563 // A numbered section's title in the table of contents, when it differs.
564 if isNumbered, let tocTitle, tocTitle != full, let brace = format.firstIndex(of: "{") {
565 // Emacs puts it in a `format` string, where `%` is a directive.
566 if tocTitle.contains("%") { throw Unsupported(reason: "% in a heading with tags not in the table of contents") }
567 let optional = tocTitle.replacingOccurrences(of: "[", with: "(").replacingOccurrences(of: "]", with: ")")
568 format.insert(contentsOf: "[\(optional)]", at: brace)
569 }
570 return format.replacingOccurrences(of: "%s", with: full) + "\n" + label + pre + (contents ?? "")
571 }
572
573 /// The headline sections exported beside `section` at its level, by start: a low-level
574 /// headline opens its list when it is the first and closes it when it is the last.
575 private func exportedSiblings(_ section: SyntaxNode) -> [Int] {
576 guard let parent = section.parent else { return [section.range.lowerBound] }
577 return parent.children.filter { child in
578 guard child.kind == .section, let heading = child.firstChild(.heading) else { return false }
579 return HTMLRenderer.sectionExport(heading, options: options, selected: selected) != .nothing
580 }.map(\.range.lowerBound)
581 }
582
583 // MARK: - Elements
584
585 private func blockType(_ node: SyntaxNode) -> String {
586 node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/).map { $0.1.lowercased() } ?? ""
587 }
588
589 /// One element's transcoding, nil for none.
590 private func element(_ node: SyntaxNode, affiliated: Affiliated, previous: SyntaxNode?, previousBlank: Int) throws -> String? {
591 switch node.kind {
592 case .paragraph:
593 return try paragraph(node, affiliated: affiliated)
594 case .plainList:
595 return try list(node, affiliated: affiliated)
596 case .table:
597 return try table(node, affiliated: affiliated)
598 case .block:
599 return try block(node, affiliated: affiliated)
600 case .horizontalRule:
601 var out = previous != nil && previousBlank == 0 ? "\n" : ""
602 out += try wrapLabel(affiliated, "\\noindent\\rule{\(affiliated.value("width") ?? "\\textwidth")}{\(affiliated.value("thickness") ?? "0.5pt")}")
603 return out
604 case .fixedWidth:
605 let value = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }
606 .map { $0.replacingOccurrences(of: "^[ \\t]*: ?", with: "", options: .regularExpression) }.joined(separator: "\n")
607 return try wrapLabel(affiliated, "\\begin{verbatim}\n\(try Self.removeIndentation(value))\n\\end{verbatim}")
608 case .latexEnvironment:
609 guard options.tex else { return nil }
610 if affiliated.name != nil || !affiliated.caption.isEmpty { throw Unsupported(reason: "Named or captioned LaTeX environments") }
611 var value = node.text
612 while value.hasSuffix("\n") { value.removeLast() }
613 return try Self.removeIndentation(value) + "\n"
614 case .keyword:
615 return try keyword(node)
616 case .drawer:
617 if drawerName(node).uppercased() == "LOGBOOK" { return nil }
618 // `org-latex-format-drawer-default-function` gives nil for no contents.
619 guard hasContents(node.children) else { return nil }
620 return try wrapLabel(affiliated, Self.normalize(try elements(node.children, end: node.range.upperBound)))
621 case .dynamicBlock:
622 let lines = node.text.components(separatedBy: "\n")
623 guard let contents = try blockContents(lines.dropFirst().dropLast(2).joined(separator: "\n")) else { return nil }
624 return try wrapLabel(affiliated, Self.normalize(contents))
625 case .planning, .propertyDrawer, .clock, .footnoteDefinition, .nodeProperty:
626 return nil
627 default:
628 throw Unsupported(reason: "\(node.kind)")
629 }
630 }
631
632 /// `org-latex--wrap-label`.
633 private func wrapLabel(_ affiliated: Affiliated, _ output: String) throws -> String {
634 guard let name = affiliated.name, output.contains(where: { !$0.isWhitespace }) else { return output }
635 return "\\phantomsection\n\\label{\(reference("name:" + name))}\n" + output
636 }
637
638 /// Org text parsed and transcoded as elements.
639 func blocks(_ text: String) throws -> String {
640 let tree = OrgParser.parse(text, defaults: settings)
641 let saved = exportSource
642 exportSource = ExportSource(tree: tree, text: text)
643 defer { exportSource = saved }
644 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
645 if nodes.contains(where: { $0.kind == .section }) { throw Unsupported(reason: "Headings inside blocks") }
646 let saveSource = currentSource
647 currentSource = text as NSString
648 defer { currentSource = saveSource }
649 return try elements(nodes, end: (text as NSString).length)
650 }
651
652 /// `blocks`, or nil when `text` has no element the export keeps, where Emacs passes nil
653 /// contents.
654 func blockContents(_ text: String) throws -> String? {
655 let tree = OrgParser.parse(text, defaults: settings)
656 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
657 let saved = exportSource
658 exportSource = ExportSource(tree: tree, text: text)
659 defer { exportSource = saved }
660 guard hasContents(nodes) else { return nil }
661 return try blocks(text)
662 }
663
664 /// Whether `nodes` hold an element the export keeps.
665 private func hasContents(_ nodes: [SyntaxNode]) -> Bool {
666 nodes.indices.contains { index in
667 let node = nodes[index]
668 switch node.kind {
669 case .comment: return false
670 case .affiliatedKeyword:
671 // Org parses affiliated keywords with no element right after them as keywords.
672 var last = index
673 while last + 1 < nodes.count, nodes[last + 1].kind == .affiliatedKeyword,
674 nodes[last].range.upperBound == nodes[last + 1].range.lowerBound { last += 1 }
675 return last + 1 == nodes.count || nodes[last].range.upperBound != nodes[last + 1].range.lowerBound
676 case .block:
677 let type = blockType(node)
678 if type == "comment" { return false }
679 if type == "src", exportSource.exports(at: node.range.lowerBound) == "none" { return false }
680 return !isResults(node)
681 default: return !pruned(node)
682 }
683 }
684 }
685
686 /// The text blank lines are counted in, when it isn't the document's.
687 private var currentSource: NSString?
688
689 private func keyword(_ node: SyntaxNode) throws -> String? {
690 let line = node.text.trimmingCharacters(in: .newlines)
691 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { return nil }
692 let value = m.2.map(String.init) ?? ""
693 switch m.1.uppercased() {
694 case "LATEX": return value
695 case "INDEX": return "\\index{\(value)}"
696 case "TOC":
697 if value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil { throw Unsupported(reason: "#+TOC: local") }
698 if value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil {
699 let depth = value.firstMatch(of: /\b([0-9]+)\b/).map { "\\setcounter{tocdepth}{\($0.1)}\n" } ?? ""
700 return depth + "\\tableofcontents"
701 }
702 if value.range(of: "\\btables\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\listoftables" }
703 if value.range(of: "\\blistings\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\lstlistoflistings" }
704 return nil
705 default: return nil
706 }
707 }
708
709 // MARK: Paragraphs
710
711 private func paragraph(_ node: SyntaxNode, affiliated: Affiliated, ignoreFirst: Bool = false) throws -> String {
712 var items = Self.normalizeIndentation(try inlineItems(node), ignoreFirst: ignoreFirst)
713 if let image = soleImage(items) {
714 items = []
715 return try inlineImage(image, affiliated: affiliated, alone: true)
716 }
717 if items.contains(where: { if case .object(let n, _) = $0, n.kind == .link, isImage(n) { return true } else { return false } }) {
718 currentAffiliated = affiliated
719 defer { currentAffiliated = nil }
720 return Self.removeBlankLines(try transcode(items))
721 }
722 if !affiliated.caption.isEmpty { throw Unsupported(reason: "Captioned paragraphs") }
723 return Self.removeBlankLines(try transcode(items))
724 }
725
726 private var currentAffiliated: Affiliated?
727
728 /// `org-remove-blank-lines`.
729 static func removeBlankLines(_ s: String) -> String {
730 s.replacing(#/\n(?:[ \t]*\n)+/#, with: "\n")
731 }
732
733 // MARK: Lists
734
735 private func isOrderedBullet(_ item: SyntaxNode) -> Bool {
736 let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
737 return bullet.first.map { $0.isASCII && ($0.isLetter || $0.isNumber) } ?? false
738 }
739
740 /// `org-latex-plain-list`, its type from the first item.
741 private func list(_ node: SyntaxNode, affiliated: Affiliated, orderedDepth: Int = 0) throws -> String {
742 let items = node.children.filter { $0.kind == .item }
743 guard let first = items.first else { return "" }
744 let ordered = isOrderedBullet(first)
745 let description = !ordered && first.firstChild(.itemTag) != nil
746 let type = affiliated.value("environment") ?? (ordered ? "enumerate" : description ? "description" : "itemize")
747 let depth = orderedDepth + (ordered ? 1 : 0)
748 var contents = ""
749 for (index, item) in items.enumerated() {
750 let next = index + 1 < items.count ? items[index + 1].range.lowerBound : node.range.upperBound
751 let text = try self.item(item, ordered: ordered, depth: depth)
752 contents += Self.normalize(text) + String(repeating: "\n", count: blankLines(from: item.range.lowerBound, to: next))
753 }
754 return try wrapLabel(affiliated, "\\begin{\(type)}\(affiliated.value("options") ?? "")\n\(Self.normalize(contents))\\end{\(type)}")
755 }
756
757 /// `org-latex-item`.
758 private func item(_ item: SyntaxNode, ordered: Bool, depth: Int) throws -> String {
759 var counter = ""
760 if let value = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+)/) {
761 guard ordered, depth < 5, let n = Int(value.1) else { throw Unsupported(reason: "Counters outside ordered lists") }
762 counter = "\\setcounter{enum\(["i", "ii", "iii", "iv"][depth - 1])}{\(n - 1)}\n"
763 } else if item.tokens.contains(where: { $0.kind == .counter }) {
764 throw Unsupported(reason: "Alphabetical counters")
765 }
766 let checkbox: String? = item.tokens.first { $0.kind == .checkbox }.map {
767 switch $0.text.uppercased() {
768 case "[X]": "$\\boxtimes$"
769 case "[-]": "$\\boxminus$"
770 default: "$\\square$"
771 }
772 }
773 var tag: String?
774 if let tagNode = item.firstChild(.itemTag) {
775 if tagNode.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in item tags") }
776 tag = try transcode(Self.merge(try inlineItems(tagNode)))
777 }
778 let children = item.children.filter { $0.kind != .itemTag }
779 var contents = ""
780 var previous: SyntaxNode?
781 for (index, child) in children.enumerated() {
782 let next = index + 1 < children.count ? children[index + 1].range.lowerBound : item.range.upperBound
783 var result: String?
784 if child.kind == .paragraph, previous == nil, index == 0 {
785 // The first paragraph's first line follows the bullet: its indentation doesn't count.
786 let bulletLine = source.lineRange(for: NSRange(location: item.range.lowerBound, length: 0))
787 let ignore = child.range.lowerBound < NSMaxRange(bulletLine)
788 result = try paragraph(child, affiliated: Affiliated(), ignoreFirst: ignore)
789 } else if child.kind == .plainList {
790 result = try list(child, affiliated: Affiliated(), orderedDepth: depth)
791 } else {
792 // Elements with affiliated keywords go through `elements`.
793 result = try elements([child], end: next)
794 if result == "" { result = nil }
795 if let r = result {
796 contents += r
797 previous = child
798 continue
799 }
800 }
801 guard let result else { continue }
802 previous = child
803 var text = Self.normalize(result) + String(repeating: "\n", count: blankLines(from: child.range.lowerBound, to: next))
804 if child.kind == .paragraph { text = Self.cleanLineBreaks(text) }
805 contents += text
806 }
807 if children.contains(where: { $0.kind == .affiliatedKeyword }) { throw Unsupported(reason: "Affiliated keywords in list items") }
808 contents = Self.normalize(contents)
809 var out = counter + "\\item"
810 if let checkbox, let tag {
811 out += ordered ? "{\(checkbox) \(tag)} " : "[{\(checkbox) \(tag)}] "
812 } else if let label = checkbox ?? tag {
813 out += ordered ? "{\(label)} " : "[{\(label)}] "
814 } else if contents.firstMatch(of: /^[ \t]*\[/) != nil, !Self.startsWithLaTeXSnippet(children.first) {
815 out += "\\relax "
816 } else {
817 out += " "
818 }
819 return out + Self.trim(contents)
820 }
821
822 /// Whether `node` is a paragraph whose first object is a `@@latex:…@@` snippet.
823 static func startsWithLaTeXSnippet(_ node: SyntaxNode?) -> Bool {
824 guard let node, node.kind == .paragraph else { return false }
825 for element in node.elements {
826 switch element {
827 case .token(let token):
828 if token.text.contains(where: { !$0.isWhitespace }) { return false }
829 case .node(let n):
830 return n.kind == .exportSnippet && n.text.hasPrefix("@@latex:")
831 }
832 }
833 return false
834 }
835
836 // MARK: Tables
837
838 /// `org-table-number-regexp`.
839 static let numberPattern = try! NSRegularExpression(pattern: "^(?:[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$", options: .caseInsensitive)
840
841 private func table(_ node: SyntaxNode, affiliated: Affiliated) throws -> String {
842 let rows = node.children.filter { $0.kind == .tableRow }
843 if node.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in tables") }
844 let mode = affiliated.value("mode") ?? "table"
845 guard mode == "table" else { throw Unsupported(reason: "#+ATTR_LATEX: :mode \(mode)") }
846 let environment = affiliated.value("environment") ?? "tabular"
847 if ["longtable", "longtabu", "tabbing"].contains(environment) { throw Unsupported(reason: "#+ATTR_LATEX: :environment \(environment)") }
848 let booktabs = affiliated.has("booktabs") ? affiliated.value("booktabs") != nil : false
849 if booktabs { throw Unsupported(reason: "Booktabs tables") }
850 // Cells as transcoded, rules as nil.
851 var cells: [[String]?] = []
852 for row in rows {
853 let rowCells = row.children.filter { $0.kind == .tableCell }
854 if rowCells.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
855 cells.append(nil)
856 continue
857 }
858 if rowCells.isEmpty { continue }
859 cells.append(try rowCells.map { try transcode(Self.merge(try inlineItems($0, trimmed: true))) })
860 }
861 let data = cells.compactMap { $0 }
862 if Self.hasSpecialRows(data.map { $0 }, raw: rows) { throw Unsupported(reason: "Tables with alignment cookies or special columns") }
863 let columns = data.first?.count ?? 0
864 var align = ""
865 for c in 0..<columns {
866 var numbers = 0, total = 0
867 var previousNumber = false
868 for row in data {
869 let value = c < row.count ? row[c] : ""
870 total += 1
871 let isNumber = Self.numberPattern.firstMatch(in: value, range: NSRange(location: 0, length: (value as NSString).length)) != nil
872 if isNumber || (value.isEmpty && previousNumber) {
873 previousNumber = true
874 numbers += 1
875 } else {
876 previousNumber = false
877 }
878 }
879 align += total > 0 && Double(numbers) / Double(total) >= 0.5 ? "r" : "l"
880 }
881 let alignment = affiliated.value("align") ?? align
882 var contents = ""
883 for row in cells {
884 guard let row else {
885 contents += "\\hline\n"
886 continue
887 }
888 contents += Self.normalize(row.joined(separator: " & ") + "\\\\\n")
889 }
890 contents = Self.normalize(contents)
891 var width = ""
892 if let w = affiliated.value("width"), !["tabular", "longtable"].contains(environment) {
893 if ["tabu", "longtabu"].contains(environment) { throw Unsupported(reason: "tabu tables") }
894 width = "{\(w)}"
895 }
896 let opt = affiliated.value("options").map { "[\($0)]" } ?? ""
897 let table = "\\begin{\(environment)}\(opt)\(width){\(alignment)}\n\(contents)\\end{\(environment)}"
898 let caption = try captionLabel(affiliated, type: "table", prefix: "tab:")
899 return decorate(table, affiliated: affiliated, caption: caption, above: true)
900 }
901
902 /// Whether a table has rows of alignment cookies or a column of row marks.
903 static func hasSpecialRows(_ data: [[String]], raw: [SyntaxNode]) -> Bool {
904 let cookie = /^<[lrc]?[0-9]*>$/
905 for row in raw {
906 let cells = row.children.filter { $0.kind == .tableCell }.map { $0.text.trimmingCharacters(in: .whitespaces) }
907 guard !cells.isEmpty else { continue }
908 if cells.allSatisfy({ $0.isEmpty || $0.wholeMatch(of: cookie) != nil }), cells.contains(where: { !$0.isEmpty }) { return true }
909 }
910 let marks: Set<String> = ["", "#", "!", "$", "*", "^", "_", "/"]
911 let first = raw.compactMap { $0.children.first { $0.kind == .tableCell }?.text.trimmingCharacters(in: .whitespaces) }
912 return !first.isEmpty && first.allSatisfy(marks.contains) && first.contains { !$0.isEmpty }
913 }
914
915 /// `org-latex--decorate-table`.
916 private func decorate(_ table: String, affiliated: Affiliated, caption: String, above: Bool) -> String {
917 let floatEnvironment: String?
918 let float = affiliated.attribute("float")
919 switch float {
920 case .some(nil): floatEnvironment = nil
921 case .some(.some(let f)) where f == "sidewaystable" || f == "sideways": floatEnvironment = "sidewaystable"
922 case .some(.some("multicolumn")): floatEnvironment = "table*"
923 case .some(.some("t")): floatEnvironment = "table"
924 case .some(.some(let f)): floatEnvironment = f
925 case .none: floatEnvironment = caption.contains(where: { !$0.isWhitespace }) ? "table" : nil
926 }
927 let placement = affiliated.value("placement") ?? "[htbp]"
928 let center = affiliated.has("center") ? affiliated.value("center") != nil : true
929 let font = affiliated.value("font").map { $0 + "\n" }
930 let captionText: String? = caption.isEmpty ? nil : caption
931 var out = ""
932 if let floatEnvironment {
933 out = "\\begin{\(floatEnvironment)}\(placement)\n" + (above ? caption : "") + (center ? "\\centering\n" : "") + (font ?? "")
934 } else if captionText != nil {
935 out = (center ? "\\begin{center}\n" : "") + (above ? caption : "") + (font.map { center ? $0 : "{" + $0 } ?? "")
936 } else if center {
937 out = "\\begin{center}\n" + (font ?? "")
938 } else if let font {
939 out = "{" + font
940 }
941 out += table
942 if let floatEnvironment {
943 out += (above ? "" : "\n" + caption) + "\n\\end{\(floatEnvironment)}"
944 } else if captionText != nil {
945 out += (above ? "" : "\n" + caption) + (center ? "\n\\end{center}" : "") + (font != nil && !center ? "}" : "")
946 } else if center {
947 out += "\n\\end{center}"
948 } else if font != nil {
949 out += "}"
950 }
951 return out
952 }
953
954 /// `org-latex--caption/label-string` for a float.
955 private func captionLabel(_ affiliated: Affiliated, type: String, prefix: String, srcBlock: Bool = false) throws -> String {
956 let nonfloat = (affiliated.attribute("float") == .some(nil) && !affiliated.caption.isEmpty) || (srcBlock && affiliated.value("float") == nil)
957 let label = affiliated.name.map { "\\label{\(prefix)\(reference("name:" + $0))}\n" } ?? ""
958 if let fromAttr = affiliated.value("caption"), fromAttr.contains(where: { !$0.isWhitespace }) { return fromAttr + "\n" }
959 guard !affiliated.caption.isEmpty else { return label }
960 let main = try inlineString(affiliated.caption.joined(separator: " "))
961 let trimmedLabel = Self.trim(label)
962 return nonfloat ? "\\captionof{\(type)}{\(trimmedLabel)\(main)}\n" : "\\caption{\(trimmedLabel)\(main)}\n"
963 }
964
965 // MARK: Blocks
966
967 private func block(_ node: SyntaxNode, affiliated: Affiliated) throws -> String? {
968 var lines = node.text.components(separatedBy: "\n")
969 if lines.last == "" { lines.removeLast() }
970 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
971 let type = m.1.lowercased()
972 let parameters = String(m.2)
973 let body = Array(lines.dropFirst().dropLast())
974 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
975 let text = unescaped.joined(separator: "\n")
976 switch type {
977 case "src":
978 guard text.contains(where: { !$0.isWhitespace }) else { return nil }
979 if affiliated.has("float") { throw Unsupported(reason: "Floating source blocks") }
980 let code = try formatCode(lines)
981 let verbatim = "\\begin{verbatim}\n\(code)\\end{verbatim}"
982 guard !affiliated.caption.isEmpty else { return verbatim }
983 return verbatim + "\n" + (try captionLabel(affiliated, type: "figure", prefix: "lst:", srcBlock: true))
984 case "example":
985 guard text.contains(where: { !$0.isWhitespace }) else { return nil }
986 let environment = affiliated.value("environment") ?? "verbatim"
987 return try wrapLabel(affiliated, "\\begin{\(environment)}\n\(try formatCode(lines))\\end{\(environment)}")
988 case "quote", "center":
989 // Emacs formats nil contents as `nil`.
990 var contents: String?
991 if let first = body.first, first.allSatisfy(\.isWhitespace) {
992 // Org parses a blank first line as a paragraph of that line, which runs on to
993 // the next blank line or element when it holds spaces.
994 let blanks = body.prefix { $0.allSatisfy(\.isWhitespace) }.count
995 if !first.isEmpty, blanks == 1, blanks < body.count { throw Unsupported(reason: "A line of spaces opening a \(type) block") }
996 let paragraph = first.isEmpty ? "\n\n" : first + "\n"
997 let rest = unescaped.dropFirst(blanks).joined(separator: "\n")
998 contents = paragraph + String(repeating: "\n", count: blanks - 1) + (rest.isEmpty ? "" : try blockContents(rest) ?? "")
999 } else if !body.isEmpty {
1000 contents = try blockContents(text)
1001 }
1002 let inner = contents.map(Self.normalize) ?? "nil"
1003 if type == "center" { return try wrapLabel(affiliated, "\\begin{center}\n\(inner)\\end{center}") }
1004 let environment = affiliated.value("environment") ?? "quote"
1005 return try wrapLabel(affiliated, "\\begin{\(environment)}\(affiliated.value("options") ?? "")\n\(inner)\\end{\(environment)}")
1006 case "verse":
1007 if !affiliated.attr.isEmpty { throw Unsupported(reason: "#+ATTR_LATEX on verse blocks") }
1008 return try wrapLabel(affiliated, try verse(unescaped))
1009 case "export":
1010 let backend = parameters.split(separator: " ").first.map { $0.uppercased() } ?? ""
1011 guard backend == "LATEX" || backend == "TEX" else { return nil }
1012 return try Self.removeIndentation(text + "\n")
1013 case "comment":
1014 return nil
1015 default:
1016 let caption = try captionLabel(affiliated, type: "figure", prefix: "")
1017 if !caption.isEmpty { throw Unsupported(reason: "Captioned special blocks") }
1018 return "\\begin{\(m.1)}\(affiliated.value("options") ?? "")\n" + Self.normalize(try blocks(text)) + "\\end{\(m.1)}"
1019 }
1020 }
1021
1022 /// `org-export-format-code-default` for a src or example block's lines.
1023 private func formatCode(_ lines: [String]) throws -> String {
1024 guard let parsed = Coderef.block(lines) else { return "" }
1025 let blockLoc = try blockLoc(lines, numbered: parsed.switches.numberLines != nil)
1026 var value = parsed.body.joined(separator: "\n")
1027 if !value.isEmpty { value += "\n" }
1028 let preserve = lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b.*\s-i\b/) != nil
1029 var code = preserve ? value : try Self.removeIndentation(value)
1030 if code.hasSuffix("\n") { code.removeLast() }
1031 let (lines, refs) = Coderef.unravel(code.components(separatedBy: "\n"), format: parsed.switches.labelFormat)
1032 let loc = parsed.switches.numberLines == nil ? nil : blockLoc
1033 guard loc != nil || (parsed.switches.retainLabels && !refs.isEmpty) else { return lines.joined(separator: "\n") + "\n" }
1034 let width = loc.map { String($0 + lines.count).count } ?? 0
1035 let numberWidth = loc == nil ? 0 : width + 2
1036 let maxWidth = (lines.map(\.count).max() ?? 0) + numberWidth
1037 return lines.enumerated().map { index, line in
1038 var out = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1) " } ?? ""
1039 out += line
1040 if parsed.switches.retainLabels, let ref = refs[index + 1] {
1041 out += String(repeating: " ", count: maxWidth + 6 - out.count) + "(\(ref))"
1042 }
1043 return out
1044 }.joined(separator: "\n") + "\n"
1045 }
1046
1047 /// The src and example blocks the export writes, in order, as their lines: none under a
1048 /// section left out, with `:exports none`, or a src block's results.
1049 private lazy var exportedBlocks: [[String]] = {
1050 let source = ExportSource(tree: tree, text: self.source as String)
1051 return tree.root.descendants().filter { $0.kind == .block }.compactMap { node in
1052 var lines = node.text.components(separatedBy: "\n")
1053 if lines.last == "" { lines.removeLast() }
1054 guard Coderef.block(lines) != nil, !Self.excluded(node, by: self), !isResults(node) else { return nil }
1055 if blockType(node) == "src", source.exports(at: node.range.lowerBound) == "none" { return nil }
1056 return lines
1057 }
1058 }()
1059
1060 /// Whether `node` is the results of the src block before it, which the export removes.
1061 private func isResults(_ node: SyntaxNode) -> Bool {
1062 guard let siblings = node.parent?.children, let index = siblings.firstIndex(where: { $0.range == node.range }) else { return false }
1063 let keywords = siblings[..<index].reversed().prefix { $0.kind == .affiliatedKeyword }
1064 guard keywords.contains(where: { $0.text.firstMatch(of: /^[ \t]*#\+(?i:results)[\[:]/) != nil }) else { return false }
1065 let before = index - keywords.count - 1
1066 return before >= 0 && siblings[before].kind == .block && blockType(siblings[before]) == "src"
1067 }
1068
1069 /// Each src and example block's `org-export-get-loc`, by the block's text, in order.
1070 private lazy var blockLocs: [String: [Int?]] = {
1071 let blocks = exportedBlocks
1072 var locs: [String: [Int?]] = [:]
1073 for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) {
1074 locs[lines.joined(separator: "\n"), default: []].append(loc)
1075 }
1076 return locs
1077 }()
1078
1079 /// `org-export-get-loc` of the block with `lines`, the next of those with the same text.
1080 private func blockLoc(_ lines: [String], numbered: Bool) throws -> Int? {
1081 let key = lines.joined(separator: "\n")
1082 guard let queue = blockLocs[key], !queue.isEmpty else {
1083 if numbered { throw Unsupported(reason: "Numbered blocks inside other blocks") }
1084 return nil
1085 }
1086 blockLocs[key] = Array(queue.dropFirst())
1087 return queue[0]
1088 }
1089
1090 /// `org-latex-verse-block` and the verse rules of `org-latex-plain-text`.
1091 private func verse(_ lines: [String]) throws -> String {
1092 let text = lines.joined(separator: "\n") + "\n"
1093 // The contents are objects: paragraphs and the blank lines between them.
1094 let tree = OrgParser.parse(text, defaults: settings)
1095 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1096 guard nodes.allSatisfy({ $0.kind == .paragraph }), let firstNode = nodes.first else { throw Unsupported(reason: "Verse blocks with more than text") }
1097 let ns = text as NSString
1098 var raw: [Inline] = [.text(ns.substring(to: firstNode.range.lowerBound))]
1099 for (index, node) in nodes.enumerated() {
1100 raw += try inlineItems(node)
1101 let end = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : ns.length
1102 raw.append(.text(ns.substring(with: NSRange(location: node.range.upperBound, length: end - node.range.upperBound))))
1103 }
1104 inVerse = true
1105 defer { inVerse = false }
1106 let items = Self.normalizeIndentation(Self.merge(raw), ignoreFirst: false)
1107 var contents = try transcode(items)
1108 while let c = contents.last, c.isWhitespace { contents.removeLast() }
1109 return Self.cleanLineBreaks("\\begin{verse}\n" + contents + "\n\\end{verse}")
1110 }
1111
1112 private var inVerse = false
1113
1114 // MARK: - Objects
1115
1116 /// Inline content: text runs and objects with their own contents.
1117 indirect enum Inline {
1118 case text(String)
1119 case object(SyntaxNode, [Inline])
1120 }
1121
1122 /// The contents of `node` as `Inline`s, markers left out, a line break's newline taken in.
1123 func inlineItems(_ node: SyntaxNode, trimmed: Bool = false) throws -> [Inline] {
1124 var items: [Inline] = []
1125 var skipNewline = false
1126 for element in node.elements {
1127 switch element {
1128 case .token(let token):
1129 switch token.kind {
1130 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1131 continue
1132 default:
1133 var text = token.text
1134 if skipNewline {
1135 let rest = text.drop { $0 == " " || $0 == "\t" }
1136 if rest.hasPrefix("\n") { text = String(rest.dropFirst()); skipNewline = false } else if !rest.isEmpty { skipNewline = false } else { text = "" }
1137 }
1138 if !text.isEmpty { items.append(.text(text)) }
1139 }
1140 case .node(let child):
1141 skipNewline = false
1142 switch child.kind {
1143 case .bold, .italic, .underline, .strikeThrough, .linkDescription:
1144 items.append(.object(child, try inlineItems(child)))
1145 case .link:
1146 items.append(.object(child, try child.firstChild(.linkDescription).map { try inlineItems($0) } ?? []))
1147 case .superscript, .subscript:
1148 let text = child.text
1149 let braced = text.dropFirst().hasPrefix("{")
1150 if options.scripts == .off || (options.scripts == .braces && !braced) {
1151 items.append(.text(text))
1152 } else if braced {
1153 items.append(.object(child, try inlineItems(child)))
1154 } else {
1155 items.append(.object(child, [.text(String(text.dropFirst()))]))
1156 }
1157 case .lineBreak where trimmed:
1158 // A table cell has no line ends.
1159 items.append(.text(child.text))
1160 case .lineBreak:
1161 items.append(.object(child, []))
1162 skipNewline = true
1163 default:
1164 items.append(.object(child, []))
1165 }
1166 }
1167 }
1168 if trimmed {
1169 if case .text(let t) = items.first { items[0] = .text(String(t.drop { $0 == " " || $0 == "\t" })) }
1170 if case .text(let t) = items.last { items[items.count - 1] = .text(String(t.reversed().drop { $0 == " " || $0 == "\t" }.reversed())) }
1171 }
1172 return Self.merge(items)
1173 }
1174
1175 /// Adjacent text runs joined.
1176 static func merge(_ items: [Inline]) -> [Inline] {
1177 var out: [Inline] = []
1178 for item in items {
1179 if case .text(let t) = item, case .text(let previous)? = out.last {
1180 out[out.count - 1] = .text(previous + t)
1181 } else if case .text(let t) = item, t.isEmpty {
1182 continue
1183 } else {
1184 out.append(item)
1185 }
1186 }
1187 return out
1188 }
1189
1190 /// `org-element-normalize-contents`: the common indentation of the lines taken away.
1191 static func normalizeIndentation(_ items: [Inline], ignoreFirst: Bool) -> [Inline] {
1192 var minimum = Int.max
1193 var zero = false
1194 func scan(_ items: [Inline], _ firstFlag: inout Bool) {
1195 for item in items {
1196 if zero { return }
1197 if firstFlag {
1198 firstFlag = false
1199 guard case .text(let t) = item, let m = t.firstMatch(of: /^([ \t]+)([^ \t\n]|\n|$)/) else { zero = true; return }
1200 if m.2 != "\n" { minimum = min(minimum, width(m.1)) }
1201 }
1202 switch item {
1203 case .text(let t):
1204 // Every line start, a blank line's next line included.
1205 var rest = t[...]
1206 while let newline = rest.firstIndex(of: "\n") {
1207 let after = rest[rest.index(after: newline)...]
1208 let indent = after.prefix { $0 == " " || $0 == "\t" }
1209 let next = after.dropFirst(indent.count).first
1210 if indent.isEmpty {
1211 if next != nil, next != "\n" { zero = true; return }
1212 } else if next != "\n" {
1213 minimum = min(minimum, width(indent))
1214 }
1215 rest = after
1216 }
1217 case .object(let node, let children):
1218 if node.kind == .lineBreak {
1219 firstFlag = true
1220 } else if [.bold, .italic, .underline, .strikeThrough, .link, .linkDescription, .superscript, .subscript].contains(node.kind) {
1221 scan(children, &firstFlag)
1222 }
1223 }
1224 }
1225 }
1226 var first = !ignoreFirst
1227 scan(items, &first)
1228 guard !zero, minimum != Int.max, minimum > 0 else { return items }
1229 func strip(_ items: [Inline], _ firstFlag: inout Bool) -> [Inline] {
1230 items.map { item in
1231 switch item {
1232 case .text(var t):
1233 if firstFlag {
1234 firstFlag = false
1235 t = dedent(t, atStart: true, by: minimum)
1236 } else {
1237 t = dedent(t, atStart: false, by: minimum)
1238 }
1239 return .text(t)
1240 case .object(let node, let children):
1241 if firstFlag { firstFlag = false }
1242 if node.kind == .lineBreak { firstFlag = true; return item }
1243 var flag = false
1244 return .object(node, strip(children, &flag))
1245 }
1246 }
1247 }
1248 var flag = !ignoreFirst
1249 return strip(items, &flag)
1250 }
1251
1252 static func width(_ s: Substring) -> Int { s.reduce(0) { $0 + ($1 == "\t" ? 8 : 1) } }
1253
1254 /// Indentation after each newline (and at the start) less `by` columns; blank lines lose theirs.
1255 static func dedent(_ t: String, atStart: Bool, by: Int) -> String {
1256 var lines = t.components(separatedBy: "\n")
1257 for i in lines.indices where i > 0 || atStart {
1258 let indent = lines[i].prefix { $0 == " " || $0 == "\t" }
1259 guard !indent.isEmpty else { continue }
1260 let rest = lines[i].dropFirst(indent.count)
1261 if rest.isEmpty && i < lines.count - 1 {
1262 lines[i] = ""
1263 } else if rest.isEmpty {
1264 lines[i] = String(repeating: " ", count: max(0, width(indent) - by))
1265 } else {
1266 lines[i] = String(repeating: " ", count: max(0, width(indent) - by)) + rest
1267 }
1268 }
1269 return lines.joined(separator: "\n")
1270 }
1271
1272 /// One line of Org text transcoded, for keywords and captions.
1273 func inlineString(_ text: String) throws -> String {
1274 let tree = OrgParser.parse(text, defaults: settings)
1275 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1276 let saved = exportSource
1277 exportSource = ExportSource(tree: tree, text: text)
1278 defer { exportSource = saved }
1279 return Self.trim(try transcode(try inlineItems(paragraph)))
1280 }
1281
1282 /// `node`'s contents transcoded, as a heading's title is.
1283 private func inline(_ node: SyntaxNode, sectionTitle: Bool) throws -> String {
1284 let saved = inTitle
1285 inTitle = sectionTitle
1286 defer { inTitle = saved }
1287 return try transcode(try inlineItems(node))
1288 }
1289
1290 private var inTitle = false
1291
1292 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`),
1293 /// objects that export nothing taking their blanks with them unless they are needed.
1294 func transcode(_ items: [Inline]) throws -> String {
1295 var out = ""
1296 var index = 0
1297 var dropBlanks = false
1298 // An object's post-blank, which Emacs writes as spaces.
1299 var afterObject = false
1300 while index < items.count {
1301 let item = items[index]
1302 switch item {
1303 case .text(var t):
1304 if dropBlanks {
1305 t = String(t.drop { $0 == " " || $0 == "\t" })
1306 } else if afterObject {
1307 let blanks = t.prefix { $0 == " " || $0 == "\t" }
1308 t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count)
1309 }
1310 dropBlanks = false
1311 afterObject = false
1312 out += plainText(t)
1313 index += 1
1314 case .object(let node, let children):
1315 dropBlanks = false
1316 afterObject = true
1317 if let math = mathValue(node) {
1318 var values = [math]
1319 var next = index + 1
1320 while next < items.count, case .object(let n, _) = items[next], let v = mathValue(n) {
1321 values.append(v)
1322 next += 1
1323 }
1324 let joined = Self.trim(values.joined(separator: " "))
1325 if !joined.isEmpty { out += "\\(\(joined)\\)" }
1326 index = next
1327 continue
1328 }
1329 if var result = try object(node, children) {
1330 // `org-timestamp-translate` keeps the blanks after the timestamp.
1331 if node.kind == .timestamp, index + 1 < items.count, case .text(let t) = items[index + 1] {
1332 result = result.dropLast() + String(repeating: " ", count: t.prefix { $0 == " " || $0 == "\t" }.count) + "}"
1333 }
1334 out += result
1335 } else {
1336 // `org-export--keep-spaces`: blanks after a dropped object stay only
1337 // between text that has none.
1338 let previousBlank: Bool
1339 if index == 0 {
1340 previousBlank = true
1341 } else if case .text(let t) = items[index - 1] {
1342 previousBlank = t.last.map { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ?? false
1343 } else {
1344 previousBlank = false
1345 }
1346 dropBlanks = previousBlank
1347 }
1348 index += 1
1349 }
1350 }
1351 return out
1352 }
1353
1354 /// The LaTeX inside `\(…\)` for an object a math block takes, nil for others.
1355 private func mathValue(_ node: SyntaxNode) -> String? {
1356 switch node.kind {
1357 case .entity:
1358 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1359 guard let (latex, math) = OrgEntities.latex[name], math else { return nil }
1360 return latex
1361 case .latexFragment:
1362 guard options.tex else { return nil }
1363 let value = node.text
1364 if value.hasPrefix("\\(") { return String(value.dropFirst(2).dropLast(2)) }
1365 if value.hasPrefix("$"), !value.hasPrefix("$$") { return String(value.dropFirst().dropLast()) }
1366 return nil
1367 default:
1368 return nil
1369 }
1370 }
1371
1372 private func object(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1373 switch node.kind {
1374 case .bold: return "\\textbf{\(try transcode(children))}"
1375 case .italic: return "\\emph{\(try transcode(children))}"
1376 case .underline: return inTitle ? "\\underline{\(try transcode(children))}" : "\\uline{\(try transcode(children))}"
1377 case .strikeThrough: return "\\sout{\(try transcode(children))}"
1378 case .verbatim, .code:
1379 return Self.texttt(String(node.text.dropFirst().dropLast()))
1380 case .link: return try link(node, children)
1381 case .linkDescription: return try transcode(children)
1382 case .timestamp: return try timestamp(node.text)
1383 case .footnoteReference: return try footnote(node)
1384 case .entity:
1385 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1386 guard let (latex, _) = OrgEntities.latex[name] else { throw Unsupported(reason: "Unknown entity \(node.text)") }
1387 return latex
1388 case .superscript: return "\\textsuperscript{\(try transcode(children))}"
1389 case .subscript: return "\\textsubscript{\(try transcode(children))}"
1390 case .lineBreak: return "\\\\\n"
1391 case .latexFragment: return options.tex ? node.text : nil
1392 case .statisticsCookie: return node.text.replacingOccurrences(of: "%", with: "\\%")
1393 case .exportSnippet:
1394 let backend = node.tokens.first?.text.dropFirst(2).dropLast() ?? ""
1395 guard backend == "latex" else { return nil }
1396 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1397 case .target:
1398 let name = String(node.text.dropFirst(2).dropLast(2))
1399 return "\\label{\(reference("target:" + name))}"
1400 case .macro:
1401 guard case .some(let value) = exportSource.resultsMacro(node) else { return nil }
1402 return try value.map(inlineString)
1403 default:
1404 throw Unsupported(reason: "\(node.kind)")
1405 }
1406 }
1407
1408 // MARK: Plain text
1409
1410 /// `org-latex-plain-text`.
1411 func plainText(_ text: String) -> String {
1412 let special = options.specialStrings
1413 var out = ""
1414 let chars = Array(text)
1415 var i = 0
1416 while i < chars.count {
1417 let c = chars[i]
1418 switch c {
1419 case "%", "$", "#", "&", "{", "}", "_":
1420 out += "\\" + String(c)
1421 case "~": out += "\\textasciitilde{}"
1422 case "^": out += "\\^{}"
1423 case "\\":
1424 if special {
1425 if i + 1 < chars.count {
1426 if chars[i + 1] == "-" {
1427 out += "\\"
1428 } else {
1429 out += "$\\backslash$" + String(chars[i + 1])
1430 i += 1
1431 }
1432 } else {
1433 out += "$\\backslash$"
1434 }
1435 } else {
1436 out += "$\\backslash$"
1437 }
1438 default:
1439 out.append(c)
1440 }
1441 i += 1
1442 }
1443 out = Self.texLogos(out)
1444 if special { out = out.replacingOccurrences(of: "...", with: "\\ldots{}") }
1445 out = out.replacing(#/(?m)^(\s*)\[/#) { $0.1 + "{[}" }
1446 if inVerse {
1447 out = out.replacing(#/(?:[ \t]*\\\\)?[ \t]*\n/#, with: "\\\\\n")
1448 out = out.replacing(#/(\\\\\n)(?:(?m:^)[ \t]*\\\\\n)+/#, with: "\n\n")
1449 out = out.replacing(#/(?m)^[ \t]+/#) { "\\hspace*{\($0.output.count)\\fontdimen2\\font}" }
1450 }
1451 return out
1452 }
1453
1454 /// `LaTeX` and `TeX` as words, as their commands.
1455 static func texLogos(_ s: String) -> String {
1456 guard s.contains("TeX") else { return s }
1457 let chars = Array(s)
1458 var out = ""
1459 var i = 0
1460 // Word constituents in Org's syntax table, the apostrophe among them.
1461 func isWord(_ c: Character) -> Bool { c.isLetter || c.isNumber || c == "'" }
1462 outer: while i < chars.count {
1463 if i == 0 || !isWord(chars[i - 1]) {
1464 for word in ["LaTeX", "TeX"] {
1465 let w = Array(word)
1466 if i + w.count <= chars.count, Array(chars[i..<(i + w.count)]) == w, i + w.count == chars.count || !isWord(chars[i + w.count]) {
1467 out += "\\" + word + "{}"
1468 i += w.count
1469 continue outer
1470 }
1471 }
1472 }
1473 out.append(chars[i])
1474 i += 1
1475 }
1476 return out
1477 }
1478
1479 // MARK: Timestamps
1480
1481 /// `org-latex-timestamp`: `org-element-timestamp-interpreter`'s text in `\textit`, with the
1482 /// blanks after the timestamp.
1483 private func timestamp(_ text: String) throws -> String? {
1484 guard let stamp = Timestamp.parse(text) else { throw Unsupported(reason: "Timestamp \(text)") }
1485 let open = stamp.active ? "<" : "["
1486 let close = stamp.active ? ">" : "]"
1487 func date(_ p: Timestamp.Point, time: Bool) -> String {
1488 var components = DateComponents(year: p.year, month: p.month, day: p.day)
1489 components.calendar = Calendar(identifier: .gregorian)
1490 let weekday = components.calendar!.date(from: components).map { components.calendar!.component(.weekday, from: $0) } ?? 1
1491 let name = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][weekday - 1]
1492 var s = String(format: "%04d-%02d-%02d ", p.year, p.month, p.day) + name
1493 if time, let h = p.hour, let m = p.minute { s += String(format: " %02d:%02d", h, m) }
1494 return s
1495 }
1496 var suffix = ""
1497 if let r = stamp.repeater {
1498 suffix += " " + r.kind.rawValue + "\(r.interval.value)\(r.interval.unit.rawValue)"
1499 if let d = r.habitDeadline { suffix += "/\(d.value)\(d.unit.rawValue)" }
1500 }
1501 if let w = stamp.warning { suffix += " " + (w.firstOccurrenceOnly ? "--" : "-") + "\(w.interval.value)\(w.interval.unit.rawValue)" }
1502 var out = open + date(stamp.start, time: true)
1503 let dateRange = text.contains(">--<") || text.contains("]--[")
1504 if let end = stamp.end {
1505 if dateRange {
1506 out += suffix + close + "--" + open + date(end, time: true) + suffix + close
1507 } else {
1508 if let h = end.hour, let m = end.minute, h != stamp.start.hour || m != stamp.start.minute {
1509 out += String(format: "-%02d:%02d", h, m)
1510 }
1511 out += suffix + close
1512 }
1513 } else {
1514 out += suffix + close
1515 }
1516 guard options.items["<"] ?? "t" == "t" else { return nil }
1517 return "\\textit{\(plainText(out))}"
1518 }
1519
1520 // MARK: Links
1521
1522 private func linkTarget(_ node: SyntaxNode) -> (type: String, path: String) {
1523 var raw = node.tokens.first { $0.kind == .linkPath }?.text ?? node.text
1524 if node.tokens.first(where: { $0.kind == .linkPath }) == nil, raw.hasPrefix("<"), raw.hasSuffix(">") {
1525 raw = String(raw.dropFirst().dropLast())
1526 }
1527 if raw.hasPrefix("#") { return ("custom-id", String(raw.dropFirst())) }
1528 if raw.hasPrefix("(") && raw.hasSuffix(")") { return ("coderef", String(raw.dropFirst().dropLast())) }
1529 if raw.hasPrefix("./") || raw.hasPrefix("../") || raw.hasPrefix("/") || raw.hasPrefix("~") { return ("file", raw) }
1530 if let m = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/), Self.linkTypes.contains(m.1.lowercased()) {
1531 let type = m.1.lowercased()
1532 var path = String(m.2)
1533 if type == "file", path.hasPrefix("//") == false, let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
1534 return (type, path)
1535 }
1536 return ("fuzzy", raw)
1537 }
1538
1539 /// `org-link-parameters` under `emacs -Q` with ox-latex loaded.
1540 static let linkTypes: Set<String> = ["attachment", "id", "file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
1541
1542 private func isImage(_ node: SyntaxNode) -> Bool {
1543 guard node.kind == .link, node.firstChild(.linkDescription) == nil else { return false }
1544 let (type, path) = linkTarget(node)
1545 guard type == "file" || type == "https" else { return false }
1546 let ext = (path as NSString).pathExtension.lowercased()
1547 let image = type == "file" ? ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"] : ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"]
1548 return image.contains(ext) && path.lowercased().hasSuffix("." + ext)
1549 }
1550
1551 /// The image link of a paragraph holding only it and blanks.
1552 private func soleImage(_ items: [Inline]) -> SyntaxNode? {
1553 var image: SyntaxNode?
1554 for item in items {
1555 switch item {
1556 case .text(let t): if t.contains(where: { !$0.isWhitespace }) { return nil }
1557 case .object(let node, _):
1558 guard image == nil, isImage(node) else { return nil }
1559 image = node
1560 }
1561 }
1562 return image
1563 }
1564
1565 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1566 let (type, path) = linkTarget(node)
1567 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
1568 if description == "" { description = nil }
1569 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1570 throw Unsupported(reason: "Links in link descriptions")
1571 }
1572 if let d = node.firstChild(.linkDescription)?.text, d.firstMatch(of: /^(?:[A-Za-z]+:\S+|<[^>]+>)$/) != nil {
1573 throw Unsupported(reason: "Images as link descriptions")
1574 }
1575 if isImage(node) { return try inlineImage(node, affiliated: currentAffiliated ?? Affiliated(), alone: false) }
1576 switch type {
1577 case "custom-id", "fuzzy", "id":
1578 let label: String
1579 let numberedHeading: Bool
1580 var title: String?
1581 if type == "fuzzy", !path.hasPrefix("*"), let found = target(path).map({ reference("target:" + $0) }) ?? namedElement(path) {
1582 return description.map { "\\hyperref[\(found)]{\($0)}" } ?? "\\ref{\(found)}"
1583 }
1584 guard let heading = try resolveHeading(type: type, path: path) else {
1585 throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"")
1586 }
1587 label = "sec:" + reference("heading@\(heading.headingRange.lowerBound)")
1588 numberedHeading = numbered && (num.map { heading.level + levelOffset <= $0 } ?? true)
1589 if description == nil, numberedHeading { return "\\ref{\(label)}" }
1590 if description == nil {
1591 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1592 title = try node?.firstChild(.title).map { try Self.trim(inline($0, sectionTitle: false)) } ?? ""
1593 }
1594 return "\\hyperref[\(label)]{\(description ?? title ?? "")}"
1595 case "coderef":
1596 guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
1597 // `org-export-get-coderef-format` on the transcoded description, then `format`.
1598 var format = description ?? "%s"
1599 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
1600 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
1601 case "file":
1602 if path.hasPrefix("~") { throw Unsupported(reason: "File links under ~") }
1603 let uri = path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path
1604 let protected = Self.protect(uri)
1605 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}"
1606 case "http", "https", "ftp", "mailto", "news":
1607 let protected = Self.protect(type + ":" + path)
1608 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}"
1609 default:
1610 throw Unsupported(reason: "\(type): links")
1611 }
1612 }
1613
1614 /// Words of a fuzzy link or a title, as `org-export-search-cells` compares them.
1615 static func words(_ s: String) -> [String] {
1616 s.uppercased().split(whereSeparator: \.isWhitespace).map(String.init)
1617 }
1618
1619 /// The `<<target>>` a fuzzy link names.
1620 private func target(_ path: String) -> String? {
1621 let search = Self.words(path)
1622 return tree.root.descendants().first { $0.kind == .target && Self.words(String($0.text.dropFirst(2).dropLast(2))) == search && !Self.excluded($0, by: self) }
1623 .map { String($0.text.dropFirst(2).dropLast(2)) }
1624 }
1625
1626 /// The label of the element whose `#+NAME` a fuzzy link names, as the element writes it.
1627 private func namedElement(_ path: String) -> String? {
1628 let search = path.split(whereSeparator: \.isWhitespace).map(String.init)
1629 for node in tree.root.descendants() where node.kind == .affiliatedKeyword && !Self.excluded(node, by: self) {
1630 guard let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { continue }
1631 let name = String(m.1)
1632 let words = name.split(whereSeparator: \.isWhitespace).map(String.init)
1633 guard words == search || words == search.map({ $0.uppercased() }), let parent = node.parent else { continue }
1634 let siblings = parent.children
1635 guard let index = siblings.firstIndex(where: { $0.range == node.range }) else { continue }
1636 let keywords = siblings[index...].prefix { $0.kind == .affiliatedKeyword }
1637 guard let element = siblings[index...].first(where: { $0.kind != .affiliatedKeyword }) else { continue }
1638 let captioned = keywords.contains { $0.text.firstMatch(of: /^[ \t]*#\+(?i:caption)/) != nil }
1639 let prefix: String
1640 switch element.kind {
1641 case .table: prefix = "tab:"
1642 case .block where blockType(element) == "src": prefix = "lst:"
1643 case .paragraph where captioned: prefix = "fig:"
1644 default: prefix = ""
1645 }
1646 return prefix + reference("name:" + name)
1647 }
1648 return nil
1649 }
1650
1651 /// The headings the export writes.
1652 private lazy var exportedHeadings: [HeadingInfo] = {
1653 let starts = Set(tree.root.descendants().filter { node in
1654 node.kind == .heading && HTMLRenderer.sectionExport(node, options: options, selected: selected) != .nothing
1655 && !(node.parent?.parent.map { Self.excluded($0, by: self) } ?? false)
1656 }.map(\.range.lowerBound))
1657 return model.headings.filter { starts.contains($0.headingRange.lowerBound) }
1658 }()
1659
1660 /// The exported heading a link goes to: by `CUSTOM_ID`, `ID` or title.
1661 private func resolveHeading(type: String, path: String) throws -> HeadingInfo? {
1662 let headings = exportedHeadings
1663 switch type {
1664 case "custom-id":
1665 return headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } }
1666 case "id":
1667 return headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } }
1668 default:
1669 let search = Self.words(path.hasPrefix("*") ? String(path.dropFirst()) : path)
1670 return headings.first { heading in
1671 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1672 let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ")
1673 return Self.words(raw) == search
1674 }
1675 }
1676 }
1677
1678 /// `org-latex--inline-image`.
1679 private func inlineImage(_ node: SyntaxNode, affiliated: Affiliated, alone: Bool) throws -> String {
1680 let (type, path) = linkTarget(node)
1681 if type != "file" { throw Unsupported(reason: "Remote images") }
1682 if path.hasPrefix("~") || path.hasPrefix("/") { throw Unsupported(reason: "Images with absolute paths") }
1683 let ext = (path as NSString).pathExtension.lowercased()
1684 let caption = try captionLabel(affiliated, type: "figure", prefix: !affiliated.caption.isEmpty ? "fig:" : "")
1685 enum Float: Equatable { case none, nonfloat, figure, wrap, sideways, multicolumn, env(String) }
1686 var float: Float
1687 let attrFloat = affiliated.attribute("float")
1688 if !alone {
1689 float = .none
1690 } else {
1691 switch attrFloat {
1692 case .some(.some("wrap")): float = .wrap
1693 case .some(.some("sideways")): float = .sideways
1694 case .some(.some("multicolumn")): float = .multicolumn
1695 case .some(.some("t")): float = .figure
1696 case .some(nil): float = .nonfloat
1697 case .some(.some(let f)): float = .env(f)
1698 case .none: float = !affiliated.caption.isEmpty || affiliated.value("caption") != nil ? .figure : .nonfloat
1699 }
1700 }
1701 let placement: String
1702 if let p = affiliated.value("placement") {
1703 placement = p
1704 } else if float == .wrap {
1705 placement = "{l}{0.5\\textwidth}"
1706 } else if float == .figure {
1707 placement = "[htbp]"
1708 } else {
1709 placement = ""
1710 }
1711 let center = affiliated.has("center") ? affiliated.value("center") != nil : true
1712 let scale = float == .wrap ? "" : affiliated.value("scale") ?? ""
1713 let width: String = !scale.isEmpty ? "" : affiliated.value("width") ?? (affiliated.value("height") != nil ? "" : float == .wrap ? "0.48\\textwidth" : ".9\\linewidth")
1714 let height: String = !scale.isEmpty ? "" : affiliated.value("height") ?? ""
1715 var options = affiliated.value("options") ?? ""
1716 if let m = options.wholeMatch(of: /\[(.*)\]/) { options = String(m.1) }
1717 if ext == "tikz" || ext == "pgf" { throw Unsupported(reason: "TikZ images") }
1718 if affiliated.value("comment-include") != nil { throw Unsupported(reason: ":comment-include") }
1719 if !scale.isEmpty {
1720 options += ",scale=" + scale
1721 } else {
1722 if !width.isEmpty { options += ",width=" + width }
1723 if !height.isEmpty { options += ",height=" + height }
1724 }
1725 let optionString = options.isEmpty ? "" : options.hasPrefix(",") ? "[\(options.dropFirst())]" : "[\(options)]"
1726 var imagePath = path
1727 if ext == "svg", imagePath.contains(where: { !$0.isASCII }) { imagePath = "\\detokenize{\(imagePath)}" }
1728 var code = "\\includegraphics\(optionString){\(imagePath)}"
1729 if ext == "svg" {
1730 code = "\\includesvg" + code.dropFirst("\\includegraphics".count)
1731 code = code.replacingOccurrences(of: ".svg}", with: "}")
1732 }
1733 let above = false
1734 switch float {
1735 case .env(let env):
1736 return "\\begin{\(env)}\(placement)\n\(above ? caption : "")\(center ? "\\centering" : "")\n\(code)\n\(above ? "" : caption)\\end{\(env)}"
1737 case .wrap:
1738 return "\\begin{wrapfigure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{wrapfigure}"
1739 case .sideways:
1740 return "\\begin{sidewaysfigure}\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{sidewaysfigure}"
1741 case .multicolumn:
1742 return "\\begin{figure*}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure*}"
1743 case .figure:
1744 return "\\begin{figure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure}"
1745 case .none, .nonfloat:
1746 if center { return "\\begin{center}\n\(code)\n\(caption)\\end{center}" }
1747 return code
1748 }
1749 }
1750
1751 // MARK: Footnotes
1752
1753 private var footnoteReferences: [String: Int] = [:]
1754 private var footnotesSeen: Set<String> = []
1755 private var definitions: [String: String] = [:]
1756 private var anonymous = 0
1757
1758 /// Footnote definitions, and how many references each label has.
1759 private func countFootnotes() throws {
1760 for node in tree.root.descendants() {
1761 if node.kind == .footnoteDefinition, let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
1762 // A definition goes on to the next one, a heading or two blank lines.
1763 if let parent = node.parent, let index = parent.children.firstIndex(where: { $0.range == node.range }), index + 1 < parent.children.count {
1764 let next = parent.children[index + 1]
1765 if next.kind != .footnoteDefinition, next.kind != .section, blankLines(from: node.range.lowerBound, to: next.range.lowerBound) < 2 {
1766 throw Unsupported(reason: "Footnote definitions of several paragraphs")
1767 }
1768 }
1769 definitions[String(m.1)] = String(node.text[m.range.upperBound...])
1770 }
1771 if node.kind == .footnoteReference, let m = node.text.firstMatch(of: /^\[fn:([^:\]]+)/) {
1772 if node.parent.map({ Self.excluded($0, by: self) }) == true { continue }
1773 footnoteReferences[String(m.1), default: 0] += 1
1774 }
1775 }
1776 }
1777
1778 /// Whether `node` is under a section the export leaves out.
1779 private static func excluded(_ node: SyntaxNode, by renderer: LaTeXRenderer) -> Bool {
1780 var current: SyntaxNode? = node
1781 while let n = current {
1782 if n.kind == .section, let heading = n.firstChild(.heading),
1783 HTMLRenderer.sectionExport(heading, options: renderer.options, selected: renderer.selected) != .all { return true }
1784 current = n.parent
1785 }
1786 return false
1787 }
1788
1789 /// `org-latex-footnote-reference`.
1790 private func footnote(_ node: SyntaxNode) throws -> String {
1791 guard let m = node.text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { throw Unsupported(reason: "Footnote \(node.text)") }
1792 let label = String(m.1)
1793 if inFootnote { throw Unsupported(reason: "Footnotes inside footnotes") }
1794 var separator = ""
1795 if let previous = previousSibling(node), previous.kind == .footnoteReference { separator = "\\textsuperscript{,}\\," }
1796 if let inline = m.2 {
1797 if !label.isEmpty {
1798 if footnotesSeen.contains(label) { return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}" }
1799 footnotesSeen.insert(label)
1800 }
1801 inFootnote = true
1802 defer { inFootnote = false }
1803 let content = try inlineString(String(inline))
1804 let labelText = !label.isEmpty && (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : ""
1805 return separator + "\\footnote{\(content)\(labelText)}"
1806 }
1807 guard !label.isEmpty, let definition = definitions[label] else { throw Unsupported(reason: "Definition not found for footnote \(label)") }
1808 if footnotesSeen.contains(label) {
1809 return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}"
1810 }
1811 footnotesSeen.insert(label)
1812 inFootnote = true
1813 defer { inFootnote = false }
1814 let content = Self.trim(try footnoteBody(definition))
1815 let labelText = (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : ""
1816 return separator + "\\footnote{\(content)\(labelText)}"
1817 }
1818
1819 private var inFootnote = false
1820
1821 /// A definition's text transcoded, its first paragraph's first line left as it is.
1822 private func footnoteBody(_ text: String) throws -> String {
1823 let tree = OrgParser.parse(text, defaults: settings)
1824 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1825 if nodes.count == 1, nodes[0].kind == .paragraph {
1826 return try paragraph(nodes[0], affiliated: Affiliated(), ignoreFirst: true)
1827 }
1828 return try blocks(text)
1829 }
1830
1831 /// The object before `node` in its parent, nil after text. Spaces and tabs after an object
1832 /// are its post-blank, not text.
1833 private func previousSibling(_ node: SyntaxNode) -> SyntaxNode? {
1834 guard let parent = node.parent else { return nil }
1835 var previous: SyntaxNode.Element?
1836 for element in parent.elements {
1837 if case .node(let n) = element, n.range == node.range {
1838 if case .node(let p)? = previous { return p }
1839 return nil
1840 }
1841 if case .token(let t) = element, !t.text.isEmpty, t.text.allSatisfy({ $0 == " " || $0 == "\t" }), case .node? = previous { continue }
1842 previous = element
1843 }
1844 return nil
1845 }
1846}
Sources/OrgCore/Links/Coderef.swift +6 −1
@@ -96,7 +96,12 @@ public enum Coderef {
9696 /// `org-export-resolve-coderef`: the label, or its line's number for blocks that number
9797 /// lines instead; nil when no block has it.
9898 public static func resolve(_ ref: String, in tree: OrgTree) -> String? {
99 let parsed = blocks(tree).compactMap(block)
99 resolve(ref, blocks: blocks(tree))
100 }
101
102 /// `resolve` among `blocks`, as their lines.
103 static func resolve(_ ref: String, blocks: [[String]]) -> String? {
104 let parsed = blocks.compactMap(block)
100105 let locs = locs(parsed)
101106 for (block, loc) in zip(parsed, locs) {
102107 let lines = trimmedLines(block.body)
Sources/OrgCore/Semantic/OrgEntities.swift +417
@@ -416,4 +416,421 @@ enum OrgEntities {
416416 "_ ": "                   ",
417417 "_ ": "                    ",
418418 ]
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 ]
419836}
Sources/OrgEditorAppKit/EditorCommands.swift +1 −1
@@ -175,7 +175,7 @@ public enum EditorCommands {
175175 EditorCommand(id: "app.copy-rich-text", title: "Copy as Rich Text", action: .app),
176176 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app),
177177 EditorCommand(id: "app.export.odt", title: "Export to ODT with Emacs", action: .app),
178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX with Emacs", action: .app),
178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX", action: .app),
179179 EditorCommand(id: "app.export.text", title: "Export to Plain Text with Emacs", action: .app),
180180 EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app),
181181 EditorCommand(id: "app.export.icalendar-agenda", title: "Export Agenda Files to iCalendar", action: .app),
Sources/Orgstar/ContentView.swift +35
@@ -628,6 +628,8 @@ struct ContentView: View {
628628 } catch {
629629 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
630630 }
631 case "latex" where exportLaTeX(text, whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults):
632 break
631633 case "print-pdf", "docx", "rtf", "plain-text":
632634 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
633635 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
@@ -689,6 +691,32 @@ struct ContentView: View {
689691 }
690692 }
691693
694 /// Writes `text` as LaTeX, as ox-latex does. False when the native export can't match Emacs
695 /// and Emacs is installed to export instead; otherwise the reason is shown.
696 private func exportLaTeX(_ text: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings) -> Bool {
697 let content: String
698 do {
699 content = try LaTeXExport.document(text, settings: settings, path: url.path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
700 } catch {
701 #if !APPSTORE
702 if EmacsRunner.executable() != nil { return false }
703 #endif
704 commands.show("Can't export to LaTeX: \(error.localizedDescription)")
705 return true
706 }
707 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
708 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "tex")) else { return true }
709 do {
710 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
711 try content.write(to: target, atomically: true, encoding: .utf8)
712 commands.show("Exported to \(target.lastPathComponent)")
713 if open { NSWorkspace.shared.open(target) }
714 } catch {
715 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
716 }
717 return true
718 }
719
692720 /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
693721 /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
694722 private func writable(_ url: URL) -> URL? {
@@ -953,6 +981,13 @@ struct ContentView: View {
953981 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
954982 let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
955983 if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) }
984 if function == "org-latex-publish-to-latex" {
985 do {
986 return try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
987 } catch let error as LaTeXExport.Unsupported {
988 throw LaTeXExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to LaTeX: \(error.reason)")
989 }
990 }
956991 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
957992 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
958993 }
Sources/Orgstar/ExportSheet.swift +2 −1
@@ -25,12 +25,13 @@ struct ExportSheet: View {
2525 static let formats: [(id: String, title: String, ext: String)] = [
2626 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
2727 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("icalendar", "iCalendar", "ics"),
28 ("latex", "LaTeX", "tex"),
2829 ]
2930 #else
3031 static let formats: [(id: String, title: String, ext: String)] = [
3132 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
3233 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
33 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
34 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
3435 ("icalendar", "iCalendar", "ics"),
3536 ]
3637 #endif
Sources/OrgstarMobile/EditorScreen.swift +1
@@ -306,6 +306,7 @@ struct EditorScreen: View {
306306 .onChange(of: session.lastError) { _, error in
307307 if let error { message = error; session.lastError = nil }
308308 }
309 .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
309310 .onAppear(perform: start)
310311 // A pane command moved focus here.
311312 .onChange(of: isFocused) {
Sources/OrgstarMobile/ExportMenu.swift +21 −2
@@ -6,11 +6,12 @@ import OrgPresentation
66import SwiftUI
77import UniformTypeIdentifiers
88
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar, written when the
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, iCalendar or LaTeX, written when the
1010/// share sheet takes it.
1111struct OrgExport: Transferable {
1212 enum Format: CaseIterable {
1313 case html, markdown, pdf, docx, rtf, plainText, icalendar
14 case latex
1415
1516 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked.
1617 @MainActor var locked: Bool { self != .html && self != .markdown && !ProAccess.shared.isUnlocked }
@@ -24,6 +25,7 @@ struct OrgExport: Transferable {
2425 case .rtf: "Rich Text (RTF)"
2526 case .plainText: "Plain Text"
2627 case .icalendar: "iCalendar"
28 case .latex: "LaTeX"
2729 }
2830 }
2931
@@ -36,6 +38,7 @@ struct OrgExport: Transferable {
3638 case .rtf: "rtf"
3739 case .plainText: "txt"
3840 case .icalendar: "ics"
41 case .latex: "tex"
3942 }
4043 }
4144 }
@@ -57,6 +60,10 @@ struct OrgExport: Transferable {
5760 .lastPathComponent
5861 }
5962
63 /// Posted with the message, for the screen's message line, when the LaTeX export refuses
64 /// the file: the share sheet shows no reason.
65 static let refused = Notification.Name("OrgExportRefused")
66
6067 static var transferRepresentation: some TransferRepresentation {
6168 FileRepresentation(exportedContentType: .html) { try await $0.write() }
6269 .exportingCondition { $0.format == .html }
@@ -72,6 +79,8 @@ struct OrgExport: Transferable {
7279 .exportingCondition { $0.format == .plainText }
7380 FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
7481 .exportingCondition { $0.format == .icalendar }
82 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
83 .exportingCondition { $0.format == .latex }
7584 }
7685
7786 private func write() async throws -> SentTransferredFile {
@@ -87,6 +96,16 @@ struct OrgExport: Transferable {
8796 .write(to: url, atomically: true, encoding: .utf8)
8897 case .markdown:
8998 try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
99 case .latex:
100 let content: String
101 do {
102 content = try LaTeXExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true)
103 } catch let error as LaTeXExport.Unsupported {
104 let message = "Can't export to LaTeX: \(error.reason)"
105 await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
106 throw error
107 }
108 try content.write(to: url, atomically: true, encoding: .utf8)
90109 case .icalendar:
91110 try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
92111 subtree: subtree, destination: url)
@@ -107,7 +126,7 @@ struct OrgExport: Transferable {
107126 }
108127}
109128
110/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar: to another app, or saved with
129/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, iCalendar or LaTeX: to another app, or saved with
111130/// Save to Files; or copying it as rich text.
112131struct ExportMenu: View {
113132 let path: String
Sources/OrgstarMobile/ReaderScreen.swift +1
@@ -121,6 +121,7 @@ struct ReaderScreen: View {
121121 .onChange(of: pane?.path) { loadFolds() }
122122 .onChange(of: pane?.editVersion) { loadFolds() }
123123 .onChange(of: model.settingsVersion) { loadFolds() }
124 .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
124125 }
125126
126127 // MARK: - Content
Tests/OrgAppTests/PublishTests.swift +59
@@ -136,6 +136,65 @@ struct PublishTests {
136136 #expect(Self.listing(ourFolder) == Self.listing(emacsFolder))
137137 }
138138
139 /// `org-latex-publish-to-latex`: the same `.tex` files as Emacs writes, the `% Created`
140 /// line and the labels aside.
141 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
142 func publishesLaTeXLikeOrg() throws {
143 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-tex-\(UUID().uuidString)").resolvingSymlinksInPath()
144 defer { try? FileManager.default.removeItem(at: folder) }
145 let sources = ["a.org": "#+TITLE: A\n* One\nText with a [[https://orgmode.org][link]].\n", "sub/b.org": "#+OPTIONS: toc:nil\n- item\n- [X] done\n"]
146 for (path, text) in sources {
147 let url = folder.appendingPathComponent("src/" + path)
148 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
149 try text.write(to: url, atomically: true, encoding: .utf8)
150 }
151 let form = """
152 (progn
153 (require 'ox-publish) (require 'ox-latex)
154 (setq user-full-name "A. Writer"
155 org-publish-timestamp-directory "\(folder.path)/ts/"
156 org-publish-project-alist '(("tex" :base-directory "\(folder.path)/src" :publishing-directory "\(folder.path)/emacs"
157 :recursive t :publishing-function org-latex-publish-to-latex)))
158 (org-publish "tex" t))
159 """
160 let process = Process()
161 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
162 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
163 process.standardOutput = FileHandle.nullDevice
164 process.standardError = FileHandle.nullDevice
165 try process.run()
166 process.waitUntilExit()
167
168 let toml = """
169 [[publish]]
170 name = "tex"
171 base-directory = "\(folder.path)/src"
172 publishing-directory = "\(folder.path)/ours"
173 recursive = true
174 publishing-function = "org-latex-publish-to-latex"
175 """
176 let loaded = Publish.projects(fromConfig: toml, root: nil)
177 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
178 let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
179 let report = try Publish.publish(loaded.projects, all: loaded.projects, force: true, read: read) { _, text, path, bodyOnly in
180 try LaTeXExport.document(text, path: path, bodyOnly: bodyOnly, author: "A. Writer", file: true)
181 }
182 #expect(report.published.count == 2)
183 func normalized(_ s: String) -> String {
184 var labels: [String: String] = [:]
185 return s.replacing(#/(?m)^% Created .*\n/#, with: "").replacing(#/org[0-9a-f]{7}/#) { m in
186 let key = String(m.output)
187 if labels[key] == nil { labels[key] = "org\(labels.count + 1)" }
188 return labels[key]!
189 }
190 }
191 for path in ["a.tex", "sub/b.tex"] {
192 let theirs = try String(contentsOf: folder.appendingPathComponent("emacs/" + path), encoding: .utf8)
193 let ours = try String(contentsOf: folder.appendingPathComponent("ours/" + path), encoding: .utf8)
194 #expect(normalized(ours) == normalized(theirs), "\(path)\nours:\n\(ours)\nemacs:\n\(theirs)")
195 }
196 }
197
139198 @Test func skipsUpToDateFilesAndFindsProjects() throws {
140199 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)").resolvingSymlinksInPath()
141200 defer { try? FileManager.default.removeItem(at: folder) }
Tests/OrgCoreTests/ExportOptionsTests.swift +21
@@ -13,6 +13,27 @@ struct ExportOptionsTests {
1313 #expect(ExportOptions.parse("#+OPTIONS: H:2 toc:t\n").toc == 2)
1414 }
1515
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
1637 @Test func pagesFollowOptions() {
1738 let org = """
1839 #+TITLE: Doc
Tests/OrgCoreTests/ExportScopeTests.swift +2 −3
@@ -26,12 +26,11 @@ struct ExportScopeTests {
2626 static var project: Int { (file as NSString).range(of: "Body of").location }
2727
2828 /// 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.
3031 @Test func subtreeIsADocumentOfItsOwn() throws {
3132 let text = try #require(ExportScope.subtree(Self.file, at: Self.project))
3233 #expect(text == """
33 #+TITLE: Whole file
34 #+AUTHOR: Ann
3534 #+OPTIONS: toc:nil num:nil
3635 #+TITLE: Project
3736 #+AUTHOR: Bob
Tests/OrgCoreTests/LaTeXExportTests.swift added +362
@@ -0,0 +1,362 @@
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 "#+begin_example\nplain\n#+end_example\n\n#+begin_src sh -n\none\ntwo\n#+end_src\n\n#+begin_example\nplain\n#+end_example\n\n#+begin_src sh +n\nthree\n#+end_src\n",
158 "* Deep lists\n** two\n*** three\n**** four a\n**** COMMENT skipped\n**** four b :noexport:\n**** four c\n",
159 "| NaN | a |\n| INF | b |\n| 2X | c |\n| -inf | d |\n",
160 "#+OPTIONS: tags:not-in-toc\n* TODO [#A] One [x] :a:b:\n* Two\n* Three :c:\n** Four :d:\n*** Five :e:\n**** Six :f:\n",
161 "#+OPTIONS: tags:not-in-toc num:nil pri:t\n* [#B] One :a:\n",
162 "* A :noexport:\n#+begin_src sh -n\na\nb\n#+end_src\n* B\n#+begin_src sh +n\nc\n#+end_src\n",
163 "#+begin_src sh -n :exports none\na\nb\n#+end_src\n\n#+begin_src sh +n\nc\n#+end_src\n",
164 "#+begin_src sh -n :exports code\na\n#+end_src\n\n#+RESULTS:\n#+begin_example\nr\ns\n#+end_example\n\n#+begin_src sh +n\nc\n#+end_src\n",
165 "* COMMENT A\n#+begin_src sh -n\na (ref:x)\n#+end_src\n* B\n#+begin_src sh -n -r\nb\nc (ref:x)\n#+end_src\nSee [[(x)]].\n",
166 "A[fn:1] [fn:2] b[fn:1]\t[fn:2] c[fn:1]\n [fn:2] d.\n\n[fn:1] One.\n\n[fn:2] Two.\n",
167 "- @@latex:[x]@@ foo\n- @@LaTeX:[x]@@ foo\n- @@tex:[x]@@ foo\n- @@latex:[x]@@ foo\n- x\n\n [a] b\n",
168 "#+begin_foo\n#+end_foo\n\n:DR:\n:END:\n\nb\n",
169 "a\n\n:DR:\n# c\n:END:\n\nb\n",
170 "a\n\n:DR:\n\n:END:\n\nb\n",
171 "a\n\n#+BEGIN: x\n#+END:\n\nb\n",
172 "a\n\n#+begin_quote\n#+end_quote\n\nb\n",
173 "a\n\n#+begin_quote\n\n#+end_quote\n\nb\n",
174 "a\n\n#+begin_quote\n# c\n#+end_quote\n\nb\n",
175 "a\n\n#+begin_center\n#+end_center\n\nb\n",
176 "#+NAME: n\n#+begin_quote\n#+end_quote\n",
177 "#+begin_center\n# c\n\n#+end_center\n\n#+begin_quote\n#+begin_src sh :exports none\nx\n#+end_src\n#+end_quote\n\n#+begin_quote\n#+FOO: t\n#+end_quote\n\n:DR:\n#+begin_comment\nc\n#+end_comment\n:END:\n\n:DR:\n#+begin_src sh\n#+end_src\n:END:\n\nend\n",
178 "a\n:DR:\n:END:\n\nb\n\na\n#+begin_src sh\n#+end_src\n\nb\n\na\n:DR:\n:END:\nb\n\na\n#+BEGIN: x\n#+END:\n\nb\n",
179 "*b*\tx =v=\t\ty \\alpha\tz [[https://a.b]]\tw x^2\tq $m$\tr <2024-01-15 Mon>\tt *b*\t\n",
180 "a @@html:x@@\tb a@@html:x@@\tb [fn::n]\t[fn::m] c\n",
181 "a\n\n:DR:\n#+CAPTION: x\n:END:\n\nb\n",
182 "a\n\n:DR:\n#+NAME: x\n:END:\n\nb\n",
183 "a\n\n:DR:\n#+NAME: x\n\n:END:\n\nb\n",
184 "a\n\n:DR:\n#+CAPTION: x\n#+NAME: y\n:END:\n\nb\n",
185 "a\n\n#+BEGIN: foo\n#+CAPTION: x\n#+END:\n\nb\n",
186 "a\n\n#+begin_quote\n#+CAPTION: x\n#+end_quote\n\nb\n",
187 "a\n\n#+begin_quote\n\n \nfoo\n#+end_quote\n",
188 "a\n\n#+begin_quote\n\nfoo\n#+end_quote\n",
189 "a\n\n#+begin_quote\n \n\nfoo\n#+end_quote\n",
190 "a\n\n#+begin_quote\n\n\nfoo\n#+end_quote\n",
191 "a\n\n#+begin_quote\n\n# c\n#+end_quote\n",
192 "a\n\n#+begin_center\n\n#+CAPTION: x\n#+end_center\n",
193 "#+begin_quote\n \n#+end_quote\n\n#+begin_center\n \n#+end_center\n\n#+begin_quote\n \n \n#+end_quote\n\n#+begin_quote\n\n \n#+end_quote\n\n#+begin_center\n \t \n\n#+end_center\n",
194 "#+TITLE: T\n#+SUBTITLE:\nx\n",
195 ]
196
197 @Test(.enabled(if: oracle))
198 func matchesEmacs() throws {
199 var cases = try Self.corpus.map { LaTeXOracle.Case(text: try String(contentsOf: Self.folder.appendingPathComponent("\($0).org"), encoding: .utf8)) }
200 cases += Self.snippets.map { LaTeXOracle.Case(text: $0) }
201 let names = Self.corpus + Self.snippets.indices.map { "snippet \($0)" }
202 try compare(cases, names: names)
203 }
204
205 @Test(.enabled(if: oracle))
206 func bodyOnlyAndSubtreesMatchEmacs() throws {
207 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"
208 let sub = (doc as NSString).range(of: "** Sub").location
209 let one = (doc as NSString).range(of: "First.").location
210 let cases = [
211 LaTeXOracle.Case(text: doc, bodyOnly: true),
212 LaTeXOracle.Case(text: try String(contentsOf: Self.folder.appendingPathComponent("blocks.org"), encoding: .utf8), bodyOnly: true),
213 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(sub, in: doc)),
214 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(one, in: doc)),
215 LaTeXOracle.Case(text: doc, bodyOnly: true, subtree: EmacsOracle.point(sub, in: doc)),
216 ]
217 try compare(cases, names: ["body", "blocks body", "subtree", "subtree from body", "subtree body"])
218 }
219
220 /// A subtree's `EXPORT_*` properties replace the file's keywords.
221 @Test(.enabled(if: oracle))
222 func subtreePropertiesMatchEmacs() throws {
223 let doc = """
224 #+TITLE: Doc
225 #+SUBTITLE: File sub
226 #+LATEX_CLASS: book
227 #+LATEX_CLASS_OPTIONS: [a4paper]
228 #+LATEX_HEADER: \\usepackage{tikz}
229 #+LATEX_HEADER_EXTRA: \\usepackage{amsthm}
230 #+LATEX_COMPILER: xelatex
231 #+KEYWORDS: k1
232 #+DESCRIPTION: d1
233 #+LANGUAGE: fr
234 #+EXCLUDE_TAGS: drop
235 * Top
236 :PROPERTIES:
237 :EXPORT_LATEX_CLASS: report
238 :EXPORT_LATEX_CLASS_OPTIONS: [12pt]
239 :EXPORT_LATEX_HEADER: \\usepackage{xcolor}
240 :EXPORT_LATEX_HEADER_EXTRA: \\usepackage{listings}
241 :EXPORT_LATEX_COMPILER: lualatex
242 :EXPORT_SUBTITLE: Sub
243 :EXPORT_KEYWORDS: k2
244 :EXPORT_DESCRIPTION: d2
245 :EXPORT_LANGUAGE: de
246 :EXPORT_EXCLUDE_TAGS: gone
247 :END:
248 Body.
249 ** Child
250 x
251 ** Dropped :gone:
252 z
253 ** Kept :drop:
254 w
255 * Other
256 :PROPERTIES:
257 :EXPORT_SUBTITLE: Only sub
258 :END:
259 y
260
261 """
262 let top = (doc as NSString).range(of: "Body.").location
263 let other = (doc as NSString).range(of: "\ny").location + 1
264 let cases = [
265 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(top, in: doc)),
266 LaTeXOracle.Case(text: doc, subtree: EmacsOracle.point(other, in: doc)),
267 ]
268 try compare(cases, names: ["subtree properties", "subtree subtitle"])
269 }
270
271 /// `PROP+` lines add to a subtree property, and an empty or "nil" value is no value.
272 @Test(.enabled(if: oracle))
273 func accumulatedSubtreePropertiesMatchEmacs() throws {
274 let docs = [
275 "#+SUBTITLE: File\n* Top\n:PROPERTIES:\n:EXPORT_LATEX_HEADER: \\usepackage{a}\n:EXPORT_SUBTITLE: s1\n:EXPORT_LATEX_HEADER+: \\usepackage{b}\n:EXPORT_SUBTITLE+: s2\n:EXPORT_SUBTITLE+: s3\n:END:\nx\n",
276 "#+SUBTITLE: File\n* Top\n:PROPERTIES:\n:EXPORT_SUBTITLE+: s2\n:EXPORT_KEYWORDS: k1\n:EXPORT_KEYWORDS: k2\n:END:\nx\n",
277 "#+SUBTITLE: File\n#+KEYWORDS: k\n* Top\n:PROPERTIES:\n:EXPORT_SUBTITLE:\n:EXPORT_KEYWORDS:\n:END:\nx\n",
278 "#+SUBTITLE: File\n* Top\n:PROPERTIES:\n:EXPORT_SUBTITLE: nil\n:EXPORT_TITLE: nil\n:END:\nx\n",
279 "#+SUBTITLE: File\n* Top\n:PROPERTIES:\n:EXPORT_SUBTITLE: nil\n:EXPORT_SUBTITLE+: s\n:END:\nx\n",
280 ]
281 let cases = docs.map { LaTeXOracle.Case(text: $0, subtree: EmacsOracle.point(($0 as NSString).range(of: "\nx\n").location + 1, in: $0)) }
282 try compare(cases, names: docs.indices.map { "accumulated \($0)" })
283 }
284
285 /// Links to what the export leaves out stop both exports.
286 @Test(.enabled(if: oracle))
287 func abortsWhereEmacsAborts() throws {
288 let docs = [
289 "* A :noexport:\n* B\nSee [[*A]].\n",
290 "* A :noexport:\n:PROPERTIES:\n:CUSTOM_ID: a\n:END:\n* B\nSee [[#a]].\n",
291 "* COMMENT A\n* B\nSee [[*A]].\n",
292 "* A :noexport:\n** Inner\n* B\nSee [[*Inner]].\n",
293 "* A :noexport:\nA <<here>> target.\n* B\nSee [[here]].\n",
294 "* A :noexport:\n#+NAME: tbl\n| x |\n* B\nSee [[tbl]].\n",
295 "* A :noexport:\n#+begin_src sh -r\nx (ref:y)\n#+end_src\n* B\nSee [[(y)]].\n",
296 ]
297 let emacs = try LaTeXOracle.export(docs.map { LaTeXOracle.Case(text: $0) })
298 for (doc, theirs) in zip(docs, emacs) {
299 let ours = LaTeXOracle.native(LaTeXOracle.Case(text: doc))
300 #expect(theirs.hasPrefix("ERROR: "), "\(doc)\n--- emacs\n\(theirs)")
301 #expect(ours.hasPrefix("ERROR: Unable to resolve"), "\(doc)\n--- ours\n\(ours)")
302 }
303 }
304
305 private func compare(_ cases: [LaTeXOracle.Case], names: [String]) throws {
306 let emacs = try LaTeXOracle.export(cases)
307 for (index, c) in cases.enumerated() {
308 let ours = LaTeXOracle.native(c)
309 if ours.hasPrefix("ERROR: ") {
310 Issue.record("\(names[index]) unsupported: \(ours)\n--- org\n\(c.text)")
311 continue
312 }
313 if let dump = ProcessInfo.processInfo.environment["LATEX_DUMP"], LaTeXOracle.normalized(ours) != LaTeXOracle.normalized(emacs[index]) {
314 let name = names[index].replacingOccurrences(of: " ", with: "_")
315 try? LaTeXOracle.normalized(ours).write(toFile: dump + "/" + name + ".ours", atomically: true, encoding: .utf8)
316 try? LaTeXOracle.normalized(emacs[index]).write(toFile: dump + "/" + name + ".emacs", atomically: true, encoding: .utf8)
317 try? c.text.write(toFile: dump + "/" + name + ".org", atomically: true, encoding: .utf8)
318 }
319 #expect(LaTeXOracle.normalized(ours) == LaTeXOracle.normalized(emacs[index]),
320 "\(names[index])\n--- org\n\(c.text)\n--- ours\n\(ours)\n--- emacs\n\(emacs[index])")
321 }
322 }
323
324 /// What Emacs exports differently or refuses is refused, naming it.
325 @Test func refusesWhatItCannotMatch() {
326 func reason(_ org: String) -> String? {
327 do {
328 _ = try LaTeXExport.document(org)
329 return nil
330 } catch let error as LaTeXExport.Unsupported {
331 return error.reason
332 } catch {
333 return "\(error)"
334 }
335 }
336 #expect(reason("#+LATEX_CLASS: beamer\nx\n") == "Unknown LaTeX class `beamer'")
337 #expect(reason("See [[id:nowhere]].\n")?.hasPrefix("Unable to resolve link") == true)
338 #expect(reason("See [[nowhere]].\n")?.hasPrefix("Unable to resolve link") == true)
339 #expect(reason("Ref[fn:9].\n") == "Definition not found for footnote 9")
340 #expect(reason("#+OPTIONS: \\n:t\nx\n") == "#+OPTIONS: \\n:t")
341 #expect(reason("#+ATTR_LATEX: :mode math\n| a | b |\n") == "#+ATTR_LATEX: :mode math")
342 #expect(reason("#+LATEX_HEADER: \\usepackage[AUTO]{babel}\nx\n") != nil)
343 #expect(reason("#+begin_src sh :exports results\necho\n#+end_src\n") == ":exports results")
344 #expect(reason("[cite:@key]\n") == "Citations")
345 for body in [" \n#+CAPTION: x\n", " \n#+FOO: x\n", " \n# c\n", " \nfoo\n", " \n#+CAPTION: x\n\nfoo\n", " \n x\n"] {
346 #expect(reason("#+begin_quote\n\(body)#+end_quote\n") == "A line of spaces opening a quote block")
347 }
348 #expect(reason("#+TITLE: T\n#+SUBTITLE: a\n#+SUBTITLE:\nx\n") == "Repeated keywords with an empty value")
349 #expect(reason("#+OPTIONS: tex:verbatim\nMath \\(a_1\\).\n") == "#+OPTIONS: tex:verbatim")
350 let pre = "* Top\n:PROPERTIES:\n:EXPORT_LATEX_CLASS_PRE: \\x\n:END:\nBody.\n"
351 #expect(ExportScope.subtree(pre, at: 0).flatMap(reason) == "#+LATEX_CLASS_PRE")
352 #expect(reason("#+OPTIONS: tags:not-in-toc\n* 100% done :a:\n")?.hasPrefix("% in a heading") == true)
353 }
354
355 @Test func labelsStayTheSame() throws {
356 let org = "* A\n* B\nSee [[*A]].\n"
357 let first = try LaTeXExport.document(org, now: Date(timeIntervalSince1970: 0))
358 let second = try LaTeXExport.document(org, now: Date(timeIntervalSince1970: 0))
359 #expect(first == second)
360 #expect(first.contains("\\label{sec:org") && first.contains("\\ref{sec:org"))
361 }
362}
Tests/OrgEditorAppKitTests/AppStoreCommandsTests.swift +6
@@ -9,6 +9,12 @@ struct AppStoreCommandsTests {
99 #expect(AppStoreCommands.hidden.isSubset(of: ids))
1010 }
1111
12 /// LaTeX export is native, so the sandboxed build has it.
13 @Test func latexExportIsShown() {
14 #expect(!AppStoreCommands.hidden.contains("app.export.latex"))
15 #expect(EditorCommands.all.first { $0.id == "app.export.latex" }?.title == "Export to LaTeX")
16 }
17
1218 @Test func pdfKeysExportThroughWebKit() throws {
1319 let replacement = try #require(AppStoreCommands.replacement(for: "app.export.pdf"))
1420 #expect(replacement == "app.export.print-pdf")
docs/manual/guide/03-keys.org +1 −1
@@ -994,7 +994,7 @@ When a key appears in several rows, it runs the command whose condition holds at
994994| Export to Plain Text (=app.export.plain-text=) | — | — | — | Exports the text without styles, without Emacs. |
995995| Copy as Rich Text (=app.copy-rich-text=) | — | — | — | Copies the selection, or the file, as HTML, RTF and plain text. |
996996| Export to PDF with Emacs (=app.export.pdf=) | =C-c C-e l p= | — | =SPC m e l p= (N) | Exports to PDF through Emacs (=org-latex-export-to-pdf=). |
997| Export to LaTeX with Emacs (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX through Emacs (=org-latex-export-to-latex=). |
997| Export to LaTeX (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX without Emacs, as =org-latex-export-to-latex= does. |
998998| Export to ODT with Emacs (=app.export.odt=) | =C-c C-e o o= | — | — | Exports to ODT through Emacs (=org-odt-export-to-odt=). |
999999| Export to Plain Text with Emacs (=app.export.text=) | =C-c C-e t u= | — | — | Exports to plain text through Emacs (=org-ascii-export-to-ascii=). |
10001000| Export to iCalendar (=app.export.icalendar=) | =C-c C-e c f= | — | — | Exports to an =.ics= calendar (=org-icalendar-export-to-ics=). |
docs/manual/guide/12-export.org +29 −11
@@ -1,6 +1,6 @@
11#+TITLE: Export
2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF, plain text and iCalendar, and to LaTeX, ODT and ASCII through Emacs; copying as rich text.
3#+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF, plain text and iCalendar itself, and the Mac download version hands LaTeX, ODT, ASCII and LaTeX-made PDF to Emacs.
2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF, plain text, iCalendar and LaTeX, and to ODT and ASCII through Emacs; copying as rich text.
3#+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF, plain text, iCalendar and LaTeX itself, and the Mac download version hands ODT, ASCII and LaTeX-made PDF to Emacs.
44
55* Exporting a file
66
@@ -18,7 +18,7 @@ Export works on the file in the current editor, using its text as it is now, sav
1818| RTF | Export to RTF | — | — | no |
1919| Plain text | Export to Plain Text | — | — | no |
2020| PDF through LaTeX | Export to PDF with Emacs | =C-c C-e l p= | =SPC m e l p=, =C-c C-e l p= | yes |
21| LaTeX | Export to LaTeX with Emacs | =C-c C-e l l= | =C-c C-e l l= | yes |
21| LaTeX | Export to LaTeX | =C-c C-e l l= | =C-c C-e l l= | no |
2222| ODT | Export to ODT with Emacs | =C-c C-e o o= | =C-c C-e o o= | yes |
2323| ASCII text | Export to Plain Text with Emacs | =C-c C-e t u= | =C-c C-e t u= | yes |
2424| iCalendar | Export to iCalendar | =C-c C-e c f= | =C-c C-e c f= | no |
@@ -29,13 +29,13 @@ The keys follow Emacs's export dispatcher (=org-export-dispatch=). =C-c C-e= on
2929
3030All fourteen commands are in File ▸ Export and in the command palette. They write the export beside the Org file, with the same name and the format's extension: =.html=, =.md=, =.pdf=, =.docx=, =.rtf=, =.tex=, =.odt=, =.txt= or =.ics=. The two agenda-file commands are the exceptions; see [[*iCalendar export][iCalendar export]]. =#+EXPORT_FILE_NAME:= names it instead, as in Org: relative to the Org file's folder (or absolute, or starting with =~=), with its extension replaced by the format's, so =#+EXPORT_FILE_NAME: out/report= writes =out/report.html=. A file already there is replaced. The message area shows "Exported to /name/".
3131
32The [[file:../install.org][Mac App Store version]] has the ten commands that don't need Emacs; File ▸ Export, the export dialog and the command palette leave out the other four, and a key bound to Export to PDF with Emacs runs Export to PDF. When the export file, or an =#+INCLUDE:= or =#+SETUPFILE:=, is outside your folders, orgstar first asks for access to its folder; for the export file, Save Elsewhere… instead picks another place. See [[file:../install.org][Install]].
32The [[file:../install.org][Mac App Store version]] has the eleven commands that don't need Emacs; File ▸ Export, the export dialog and the command palette leave out the other three, and a key bound to Export to PDF with Emacs runs Export to PDF. When the export file, or an =#+INCLUDE:= or =#+SETUPFILE:=, is outside your folders, orgstar first asks for access to its folder; for the export file, Save Elsewhere… instead picks another place. See [[file:../install.org][Install]].
3333
3434** The export dialog
3535
3636*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has:
3737
38- *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT (Emacs), LaTeX (Emacs), Plain text, ASCII (Emacs) or iCalendar.
38- *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT (Emacs), LaTeX, Plain text, ASCII (Emacs) or iCalendar. The App Store version lists LaTeX last.
3939- *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. iCalendar is the exception: there the subtree's heading is an entry like any other. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading.
4040- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF, Word, RTF, plain text, ODT and iCalendar.
4141- *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension.
@@ -46,7 +46,7 @@ The dialog remembers the format and the *Open after export* setting. The PDF set
4646
4747** On iOS
4848
49The Export menu offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text and iCalendar, and Copy as Rich Text. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac. LaTeX, ODT, ASCII and PDF through LaTeX are not available on iOS, nor are the agenda-file iCalendar exports.
49The Export menu offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, iCalendar and LaTeX, and Copy as Rich Text. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac, except that LaTeX has no =\author= unless the file has =#+AUTHOR:=. ODT, ASCII and PDF through LaTeX are not available on iOS, nor are the agenda-file iCalendar exports.
5050
5151* HTML export
5252
@@ -217,6 +217,25 @@ Export to PDF makes the HTML export into a PDF, laid out and split into pages by
217217
218218For typeset output with LaTeX's classes and packages, use Export to PDF with Emacs instead (see /Exporting through Emacs/).
219219
220* LaTeX export
221
222Export to LaTeX writes the =.tex= file that Emacs's =org-latex-export-to-latex= writes under =emacs -Q= (Org 9.8.7), without Emacs, on the Mac and iOS. It has the same preamble, sectioning, lists, tables, verbatim source blocks, figures, footnotes, links and escaping. Two things differ: the =\label= keys are made from the document, so they stay the same between exports, where Emacs picks new random ones each time; and =\author= is the name of the Mac's user account, which is what =user-full-name= usually is, unless the file has =#+AUTHOR:=.
223
224It reads:
225
226| Keyword | Effect |
227|--------------------------+--------------------------------------------------------------------------|
228| =#+LATEX_CLASS:= | =article= (the default), =report= or =book=, with Org's default sectioning |
229| =#+LATEX_CLASS_OPTIONS:= | Replaces =[11pt]= in =\documentclass= |
230| =#+LATEX_HEADER:= | Lines added after the packages |
231| =#+LATEX_HEADER_EXTRA:= | Lines added after those |
232| =#+LATEX_COMPILER:= | =pdflatex= (the default), =xelatex= or =lualatex=: the packages for that engine |
233| =#+ATTR_LATEX:= | On tables (=:environment=, =:align=, =:width=, =:float=, =:placement=, =:center=, =:font=, =:caption=, =:options=), images (=:width=, =:height=, =:scale=, =:options=, =:float=, =:placement=, =:center=), lists, quote, example and special blocks |
234
235=#+TITLE=, =#+SUBTITLE=, =#+AUTHOR=, =#+DATE=, =#+KEYWORDS=, =#+DESCRIPTION=, =#+LANGUAGE= and =#+OPTIONS= work as in Emacs, as do the tags and =COMMENT= that leave headings out (see /Which headings are exported/). Body-only and subtree export are in the export dialog. In a subtree export, the heading's =EXPORT_LATEX_CLASS=, =EXPORT_LATEX_CLASS_OPTIONS=, =EXPORT_LATEX_HEADER=, =EXPORT_LATEX_HEADER_EXTRA=, =EXPORT_LATEX_COMPILER=, =EXPORT_SUBTITLE=, =EXPORT_KEYWORDS=, =EXPORT_DESCRIPTION= and =EXPORT_LANGUAGE= properties replace the file's keywords. As in Emacs, a =PROPERTY+= line adds its value to the property's, after a space.
236
237A file with something this export doesn't handle stops with "Can't export to LaTeX: " and what it was, rather than giving a =.tex= that differs from Emacs's: a LaTeX class other than the three, Babel or Polyglossia in the header, citations, radio targets, inline tasks, table.el tables, inline source blocks and calls, =#+CALL=, source blocks exported with their results, footnote definitions of several paragraphs, footnotes in headings, tables or item tags, =:mode math= and long tables, =UNNUMBERED= and =ALT_TITLE=, =tex:verbatim=, a quote or center block whose first line holds only spaces and whose second line is not blank, a keyword such as =#+SUBTITLE= repeated with an empty value, and =#+OPTIONS= items other than =toc=, =num=, =H=, =tags=, =todo=, =pri=, =^=, =tex=, =title=, =author=, =date=, =-= and =timestamp= set to something other than Org's default. A link Emacs can't resolve stops the export in both, including a link to a heading, target or named element the export leaves out. On iOS the share sheet stops and the message shows at the bottom of the screen. Publishing to LaTeX stops with the file's name in the message. In the download version, when Emacs is installed, such a file is exported by Emacs instead (see /Exporting through Emacs/).
238
220239* Word, RTF and plain text
221240
222241Export to Word, Export to RTF and Export to Plain Text make the HTML export into a document of that kind, as the system reads HTML: headings, emphasis, links, colored keywords and code, lists, and tables. Word files (=.docx=) are written by orgstar itself, so tables come through as Word tables; RTF keeps them too on the Mac. On iOS, where the system's HTML reader keeps no tables, Word's tables are made from the HTML export's tables, with header cells bold and the cells' text without its styles; RTF and plain text there have the cells' text but no table. Plain text is the same text without its styles: list bullets and table cells are kept, separated by tabs. Fonts are Helvetica Neue for text and Menlo for code, and the colors are the light ones.
@@ -272,7 +291,7 @@ Differences from Org: diary sexps (=%%(…)= lines and =<%%(…)>= timestamps) a
272291
273292* Publishing
274293
275Publishing (=org-publish=) exports a folder of Org files to a folder of HTML or Markdown files, copies other files beside them, and can write a sitemap. Projects are =[[publish]]= tables in =config.toml=, as =org-publish-project-alist= entries are in Emacs:
294Publishing (=org-publish=) exports a folder of Org files to a folder of HTML, Markdown or LaTeX files, copies other files beside them, and can write a sitemap. Projects are =[[publish]]= tables in =config.toml=, as =org-publish-project-alist= entries are in Emacs:
276295
277296#+BEGIN_SRC toml
278297[[publish]]
@@ -305,7 +324,7 @@ components = "notes static"
305324| =recursive= | Files in subfolders too | =false= |
306325| =exclude= | An Emacs regexp on the file's path under =base-directory=; matching files are left out | |
307326| =include= | More files, relative to =base-directory=, separated by spaces | |
308| =publishing-function= | =org-html-publish-to-html=, =org-md-publish-to-md= or =org-publish-attachment= (copied as they are), several separated by spaces | =org-html-publish-to-html= |
327| =publishing-function= | =org-html-publish-to-html=, =org-md-publish-to-md=, =org-latex-publish-to-latex= or =org-publish-attachment= (copied as they are), several separated by spaces | =org-html-publish-to-html= |
309328| =body-only= | The export's body only | =false= |
310329| =auto-sitemap= | Write a sitemap into =base-directory= and publish it with the rest | =false= |
311330| =sitemap-filename= | The sitemap's name | ="sitemap.org"= |
@@ -331,16 +350,15 @@ A file whose published copy is newer than it is skipped, as Org skips files that
331350
332351* Exporting through Emacs
333352
334On the Mac, PDF, LaTeX, ODT and plain text exports are done by Emacs, with the =ox= functions Emacs's dispatcher uses:
353On the Mac, PDF, ODT and plain text exports are done by Emacs, with the =ox= functions Emacs's dispatcher uses:
335354
336355| Format | Function |
337356|------------+-----------------------------|
338357| PDF | =org-latex-export-to-pdf= |
339| LaTeX | =org-latex-export-to-latex= |
340358| ODT | =org-odt-export-to-odt= |
341359| Plain text | =org-ascii-export-to-ascii= |
342360
343The [[file:../install.org][Mac App Store version]] doesn't run Emacs and has none of these exports.
361LaTeX goes to Emacs (=org-latex-export-to-latex=) only for a file orgstar's own LaTeX export can't write as Emacs would; see /LaTeX export/. The [[file:../install.org][Mac App Store version]] doesn't run Emacs and has none of these exports.
344362
345363orgstar runs =emacs -Q --batch= in the Org file's folder. It opens the file, replaces its contents with the editor's current text without saving, and calls the function. Emacs writes the result beside the file, as it would itself; with a destination chosen in the export dialog, orgstar then moves it there. The message area shows "Exporting with Emacs…" and then "Exported to /name/".
346364
docs/manual/guide/14-ios.org +3 −3
@@ -329,9 +329,9 @@ The app icon's badge counts the entries in the agenda's Overdue section that are
329329
330330* Export
331331
332Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text and iCalendar, and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does.
332Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, iCalendar and LaTeX, and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does. For a file the LaTeX export can't write as Emacs would, the share sheet stops and "Can't export to LaTeX: " and the reason show at the bottom of the screen.
333333
334PDF export follows =pdf-margin=, =pdf-font= and =pdf-page-numbers= in =config.toml=, and Word files get heading styles and the file's images, as on the Mac. ODT, LaTeX, ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]].
334PDF export follows =pdf-margin=, =pdf-font= and =pdf-page-numbers= in =config.toml=, and Word files get heading styles and the file's images, as on the Mac. ODT, ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]].
335335
336336* Code blocks and tables
337337
@@ -436,7 +436,7 @@ Quick Look in the Files app shows org files as the HTML export renders them.
436436* What the Mac has that iOS doesn't
437437
438438- In the download version: running code blocks in languages other than Emacs Lisp and JavaScript, Emacs Lisp beyond orgstar's interpreter, JavaScript that needs node, and tables that need Emacs.
439- Publishing, and in the download version ODT, LaTeX, ASCII and LaTeX-made PDF export.
439- Publishing, and in the download version ODT, ASCII and LaTeX-made PDF export.
440440- Idle detection while a clock runs.
441441- Import from Emacs of agenda folders.
442442- The Columns inspector, the buffer list and tab bar, and resizing panes by dragging their divider. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]).
docs/manual/guide/15-alongside-emacs.org +2 −2
@@ -120,9 +120,9 @@ Some features run Emacs in batch mode on the Mac. Everything else works without
120120| Emacs Lisp source blocks (=emacs-lisp=, =elisp=) | The block, in =emacs -Q --batch= |
121121| Table formulas outside what orgstar computes itself | =org-table-recalculate= on a copy of the file; the table's new text replaces the old one if the table didn't change meanwhile |
122122| Lisp table formulas that orgstar's Emacs Lisp interpreter can't evaluate | The same; orgstar first asks whether to run Lisp (yes, no, always) |
123| Export to PDF, ODT, LaTeX and plain text | =org-latex-export-to-pdf=, =org-odt-export-to-odt=, =org-latex-export-to-latex= or =org-ascii-export-to-ascii= |
123| Export to PDF, ODT and plain text, and LaTeX orgstar can't write itself | =org-latex-export-to-pdf=, =org-odt-export-to-odt=, =org-ascii-export-to-ascii= or =org-latex-export-to-latex= |
124124
125HTML and Markdown export don't use Emacs. See [[file:11-code-blocks.org][Code blocks]], [[file:10-tables.org][Tables]] and [[file:12-export.org][Export]].
125HTML, Markdown and LaTeX export don't use Emacs. See [[file:11-code-blocks.org][Code blocks]], [[file:10-tables.org][Tables]] and [[file:12-export.org][Export]].
126126
127127** How Emacs is found
128128
docs/manual/install.org +17 −15
@@ -7,7 +7,7 @@
77- macOS 26 or later.
88- Optional, for the download version: GNU Emacs, for the features that hand work to it
99 (Emacs Lisp code blocks that need full Emacs, Lisp table formulas the built-in
10 interpreter can't run, and export to PDF, LaTeX, ODT and other formats). See
10 interpreter can't run, and export to PDF through LaTeX, ODT and ASCII). See
1111 [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]].
1212
1313* The Mac app
@@ -52,19 +52,19 @@ App Store version.
5252
5353** What it does differently
5454
55| Feature | Mac App Store version | Download version |
56|----------------------------+-----------------------------------------------------------------------+-------------------------------------------------------------------------------------------------|
57| Code blocks | Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore | Every language installed; Emacs Lisp in Emacs; JavaScript in node, or JavaScriptCore without it |
58| Sessions, graphics | JavaScript sessions; no graphics | Yes |
59| Tangling | Yes | Yes |
60| Table formulas | Those orgstar computes itself | The rest in Emacs as well |
61| Plots | Drawn with Swift Charts | gnuplot when installed, else Swift Charts |
62| Export | HTML, Markdown, PDF, Word, RTF, plain text, iCalendar; publishing | Also PDF through LaTeX, LaTeX, ODT and ASCII, in Emacs |
63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= |
64| Files outside your folders | After you grant access to their folder | Directly |
65| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked |
66| Updates | The Mac App Store | Built in, or Homebrew |
67| orgstar+ | In-app purchase, shared with iPhone and iPad | License key |
55| Feature | Mac App Store version | Download version |
56|----------------------------+--------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------|
57| Code blocks | Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore | Every language installed; Emacs Lisp in Emacs; JavaScript in node, or JavaScriptCore without it |
58| Sessions, graphics | JavaScript sessions; no graphics | Yes |
59| Tangling | Yes | Yes |
60| Table formulas | Those orgstar computes itself | The rest in Emacs as well |
61| Plots | Drawn with Swift Charts | gnuplot when installed, else Swift Charts |
62| Export | HTML, Markdown, PDF, Word, RTF, plain text, iCalendar, LaTeX; publishing | Also PDF through LaTeX, ODT and ASCII, in Emacs |
63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= |
64| Files outside your folders | After you grant access to their folder | Directly |
65| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked |
66| Updates | The Mac App Store | Built in, or Homebrew |
67| orgstar+ | In-app purchase, shared with iPhone and iPad | License key |
6868
6969A block in another language reports "/language/ blocks don't run in this version of
7070orgstar." An Emacs Lisp block that uses more than the interpreter has reports "This block uses
@@ -72,7 +72,9 @@ Emacs Lisp that runs only in Emacs." A JavaScript block that uses something only
7272reports "This block uses /name/, which runs only in node." A table whose formulas need Emacs reports "This table's
7373formulas can't be calculated here", with the reason, and isn't changed. The Emacs exports are
7474not in the File ▸ Export menu, the export dialog or the command palette; a key bound to
75Export to PDF with Emacs exports to PDF without LaTeX.
75Export to PDF with Emacs exports to PDF without LaTeX. LaTeX export is orgstar's own and is in
76both versions; a file it can't write as Emacs would reports "Can't export to LaTeX", with the
77reason.
7678
7779** Folders and files
7880
l10n/Localizable.xcstrings +6 −6
@@ -11644,37 +11644,37 @@
1164411644 }
1164511645 }
1164611646 },
11647 "Export to LaTeX with Emacs": {
11647 "Export to LaTeX": {
1164811648 "comment": "Command title",
1164911649 "localizations": {
1165011650 "de": {
1165111651 "stringUnit": {
1165211652 "state": "translated",
11653 "value": "Mit Emacs als LaTeX exportieren"
11653 "value": "Als LaTeX exportieren"
1165411654 }
1165511655 },
1165611656 "es": {
1165711657 "stringUnit": {
1165811658 "state": "translated",
11659 "value": "Exportar a LaTeX con Emacs"
11659 "value": "Exportar a LaTeX"
1166011660 }
1166111661 },
1166211662 "fr": {
1166311663 "stringUnit": {
1166411664 "state": "translated",
11665 "value": "Exporter en LaTeX avec Emacs"
11665 "value": "Exporter en LaTeX"
1166611666 }
1166711667 },
1166811668 "ja": {
1166911669 "stringUnit": {
1167011670 "state": "translated",
11671 "value": "EmacsでLaTeXに書き出す"
11671 "value": "LaTeXに書き出す"
1167211672 }
1167311673 },
1167411674 "pt-BR": {
1167511675 "stringUnit": {
1167611676 "state": "translated",
11677 "value": "Exportar para LaTeX com o Emacs"
11677 "value": "Exportar para LaTeX"
1167811678 }
1167911679 }
1168011680 }