| @@ -0,0 +1,1733 @@ |
| 1 | import 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. |
| 7 | public enum LaTeXExport { |
| 8 | public struct Unsupported: Error, LocalizedError, Equatable { |
| 9 | public let reason: String |
| 10 | public var errorDescription: String? { reason } |
| 11 | } |
| 12 | |
| 13 | /// `org-latex-classes`: each class's header and its sectioning, numbered and not. |
| 14 | static let classes: [String: (header: String, sections: [(String, String)])] = { |
| 15 | let part = ("\\part{%s}", "\\part*{%s}") |
| 16 | let chapter = ("\\chapter{%s}", "\\chapter*{%s}") |
| 17 | let section = ("\\section{%s}", "\\section*{%s}") |
| 18 | let subsection = ("\\subsection{%s}", "\\subsection*{%s}") |
| 19 | let subsubsection = ("\\subsubsection{%s}", "\\subsubsection*{%s}") |
| 20 | return [ |
| 21 | "article": ("\\documentclass[11pt]{article}", [section, subsection, subsubsection, ("\\paragraph{%s}", "\\paragraph*{%s}"), ("\\subparagraph{%s}", "\\subparagraph*{%s}")]), |
| 22 | "report": ("\\documentclass[11pt]{report}", [part, chapter, section, subsection, subsubsection]), |
| 23 | "book": ("\\documentclass[11pt]{book}", [part, chapter, section, subsection, subsubsection]), |
| 24 | ] |
| 25 | }() |
| 26 | |
| 27 | /// `org-latex-default-packages-alist`: options, package and the compilers it is for. |
| 28 | static let packages: [(String, String, [String])] = [ |
| 29 | ("", "amsmath", ["lualatex", "xelatex"]), ("", "fontspec", ["lualatex", "xelatex"]), |
| 30 | ("utf8", "inputenc", ["pdflatex"]), ("T1", "fontenc", ["pdflatex"]), |
| 31 | ("", "graphicx", []), ("", "longtable", []), ("", "wrapfig", []), ("", "rotating", []), ("normalem", "ulem", []), |
| 32 | ("", "amsmath", ["pdflatex"]), ("", "amssymb", ["pdflatex"]), ("", "capt-of", []), ("", "hyperref", []), |
| 33 | ] |
| 34 | |
| 35 | static let compilers = ["pdflatex", "xelatex", "lualatex"] |
| 36 | |
| 37 | /// A `.tex` document, or with `bodyOnly` what goes between `\begin{document}` and |
| 38 | /// `\end{document}` without the title and contents. `author` stands for `user-full-name`, |
| 39 | /// `language` for `org-export-default-language`, `now` for the `% Created` line. |
| 40 | public static func document( |
| 41 | _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false, |
| 42 | author: String = "", language: String = "en", timeZone: TimeZone = .current |
| 43 | ) throws -> String { |
| 44 | let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() } |
| 45 | let included = ExportPreprocess.includes(text, directory: directory) |
| 46 | // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays. |
| 47 | let marker = "\u{E000}" |
| 48 | if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") } |
| 49 | var literal = included |
| 50 | if included.contains("{{{") { |
| 51 | let ns = included as NSString |
| 52 | let kept = OrgParser.parse(included, defaults: settings).root.descendants() |
| 53 | .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range) |
| 54 | var out = "" |
| 55 | var at = 0 |
| 56 | for range in kept.sorted(by: { $0.lowerBound < $1.lowerBound }) where range.lowerBound >= at { |
| 57 | out += ns.substring(with: NSRange(location: at, length: range.lowerBound - at)) |
| 58 | out += ns.substring(with: NSRange(location: range.lowerBound, length: range.count)).replacingOccurrences(of: "{{{", with: marker + "{{") |
| 59 | at = range.upperBound |
| 60 | } |
| 61 | literal = out + ns.substring(from: at) |
| 62 | } |
| 63 | let text = ExportPreprocess.macros(literal, path: path, now: now, setup: settings.setupKeywords).replacingOccurrences(of: marker, with: "{") |
| 64 | let tree = OrgParser.parse(text, defaults: settings) |
| 65 | let keywords = settings.setupKeywords.split(separator: "\n").map(String.init) |
| 66 | + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) } |
| 67 | let renderer = try LaTeXRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language) |
| 68 | let body = try renderer.body() |
| 69 | if bodyOnly { return body } |
| 70 | return try renderer.template(body, author: author, now: now, timeZone: timeZone) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | final class LaTeXRenderer { |
| 75 | typealias Unsupported = LaTeXExport.Unsupported |
| 76 | |
| 77 | let tree: OrgTree |
| 78 | let source: NSString |
| 79 | let settings: OrgSettings |
| 80 | let options: ExportOptions |
| 81 | /// Keyword values by name, in order. |
| 82 | let keywords: [String: [String]] |
| 83 | let language: String |
| 84 | let className: String |
| 85 | /// `num` and `toc` as written: nil for t. |
| 86 | let num: Int? |
| 87 | let numbered: Bool |
| 88 | let toc: Int? |
| 89 | let withTOC: Bool |
| 90 | let timeStampFile: Bool |
| 91 | private var selected: Set<Int>? |
| 92 | /// Added to heading levels. |
| 93 | private var levelOffset = 0 |
| 94 | private var exportSource: ExportSource |
| 95 | private let model: DocumentModel |
| 96 | |
| 97 | init(tree: OrgTree, text: String, settings: OrgSettings, keywords lines: [String], language: String) throws { |
| 98 | self.tree = tree |
| 99 | source = text as NSString |
| 100 | self.settings = settings |
| 101 | exportSource = ExportSource(tree: tree, text: text) |
| 102 | model = DocumentModel(tree: tree) |
| 103 | var keywords: [String: [String]] = [:] |
| 104 | for line in lines { |
| 105 | guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { continue } |
| 106 | keywords[m.1.uppercased(), default: []].append(m.2.map(String.init) ?? "") |
| 107 | } |
| 108 | self.keywords = keywords |
| 109 | options = ExportOptions.parse(lines.joined(separator: "\n")) |
| 110 | self.language = keywords["LANGUAGE"]?.last ?? language |
| 111 | className = options.latexClass ?? "article" |
| 112 | guard LaTeXExport.classes[className] != nil else { throw Unsupported(reason: "Unknown LaTeX class `\(className)'") } |
| 113 | |
| 114 | // `#+OPTIONS` this export follows; any other item only at its default. |
| 115 | let defaults = ["\\n": "nil", ":": "t", "*": "t", "e": "t", "f": "t", "|": "t", "p": "nil", "c": "nil", "prop": "nil", |
| 116 | "stat": "t", "tasks": "t", "inline": "t", "arch": "headline", "email": "nil", "creator": "nil", |
| 117 | "broken-links": "nil", "'": "nil", "<": "t", "d": "(not \"LOGBOOK\")", "latex-use-sans": "nil", "expand-links": "t"] |
| 118 | for (key, value) in options.items { |
| 119 | if let standard = defaults[key], standard != value { throw Unsupported(reason: "#+OPTIONS: \(key):\(value)") } |
| 120 | } |
| 121 | let items = options.items |
| 122 | func depth(_ key: String) throws -> (Bool, Int?) { |
| 123 | guard let v = items[key] else { return (true, nil) } |
| 124 | if v == "nil" { return (false, nil) } |
| 125 | if v == "t" { return (true, nil) } |
| 126 | guard let n = Int(v) else { throw Unsupported(reason: "#+OPTIONS: \(key):\(v)") } |
| 127 | return (true, n) |
| 128 | } |
| 129 | (numbered, num) = try depth("num") |
| 130 | (withTOC, toc) = try depth("toc") |
| 131 | timeStampFile = items["timestamp"] != "nil" |
| 132 | for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "LATEX_CLASS_PRE", "LATEX_FOOTNOTE_COMMAND", "CALL", "EXPORT_LATEX_CLASS"] where keywords[key] != nil { |
| 133 | throw Unsupported(reason: "#+\(key)") |
| 134 | } |
| 135 | for line in options.latexHeader + options.latexHeaderExtra + (options.latexClassOptions.map { [$0] } ?? []) |
| 136 | where line.contains("{babel}") || line.contains("{polyglossia}") || line.contains("\\babelprovide") || line.contains("[AUTO]") { |
| 137 | throw Unsupported(reason: "Babel or Polyglossia in the LaTeX header") |
| 138 | } |
| 139 | // Radio links: links that are only words. |
| 140 | if tree.root.descendants().contains(where: { $0.kind == .link && !$0.tokens.contains { $0.kind == .linkPath } && !$0.text.hasPrefix("<") && !$0.text.contains(":") }) { |
| 141 | throw Unsupported(reason: "Radio targets") |
| 142 | } |
| 143 | let kinds = Set(tree.root.descendants().map(\.kind)) |
| 144 | for (kind, name) in [(SyntaxKind.radioTarget, "Radio targets"), (.citation, "Citations"), (.inlineTask, "Inline tasks"), |
| 145 | (.inlineSourceBlock, "Inline source blocks"), (.inlineBabelCall, "Inline calls"), (.tableEl, "table.el tables"), |
| 146 | (.diarySexp, "Diary sexps")] where kinds.contains(kind) { |
| 147 | throw Unsupported(reason: name) |
| 148 | } |
| 149 | selected = HTMLRenderer.selection(tree, tags: options.selectTags) |
| 150 | // `:headline-offset`: the shallowest exported heading is level 1. |
| 151 | let options = options |
| 152 | let selected = selected |
| 153 | let top = tree.root.children.compactMap { $0.kind == .section ? $0.firstChild(.heading) : nil } |
| 154 | .filter { HTMLRenderer.sectionExport($0, options: options, selected: selected) != .nothing } |
| 155 | levelOffset = 1 - (top.compactMap { $0.tokens.first { $0.kind == .stars }?.text.count }.min() ?? 1) |
| 156 | try countFootnotes() |
| 157 | } |
| 158 | |
| 159 | // MARK: - Template |
| 160 | |
| 161 | /// `org-latex-template`. |
| 162 | func template(_ body: String, author: String, now: Date, timeZone: TimeZone) throws -> String { |
| 163 | var out = "" |
| 164 | if timeStampFile { |
| 165 | let formatter = DateFormatter() |
| 166 | formatter.locale = Locale(identifier: "en_US_POSIX") |
| 167 | formatter.timeZone = timeZone |
| 168 | formatter.dateFormat = "yyyy-MM-dd EEE HH:mm" |
| 169 | out += "% Created \(formatter.string(from: now))\n" |
| 170 | } |
| 171 | let compiler = options.latexCompiler ?? "pdflatex" |
| 172 | if LaTeXExport.compilers.contains(compiler) { out += "% Intended LaTeX compiler: \(compiler)\n" } |
| 173 | out += preamble(compiler: compiler) |
| 174 | if numbered, let num { out += "\\setcounter{secnumdepth}{\(num)}\n" } |
| 175 | var authorText: String? = try keywords["AUTHOR"].map { try parsed($0) } ?? (author.isEmpty ? nil : try inlineString(author)) |
| 176 | if authorText?.isEmpty == true { authorText = nil } |
| 177 | if options.author, let authorText { out += "\\author{\(authorText)}\n" } |
| 178 | // The default, `\today`, is a LaTeX fragment, which `tex:nil` takes out. |
| 179 | let date = try keywords["DATE"].map { try parsed($0) } ?? (options.tex ? "\\today" : "") |
| 180 | out += "\\date{\(options.date ? date : "")}\n" |
| 181 | let title = try keywords["TITLE"].map { try parsed($0) } ?? "" |
| 182 | let subtitle = try keywords["SUBTITLE"].map { "\\\\\\medskip\n\\large " + (try parsed($0)) } ?? "" |
| 183 | out += "\\title{\(title)\(subtitle)}\n" |
| 184 | let lang = Self.languageNames[self.language] ?? self.language |
| 185 | out += "\\hypersetup{\n pdfauthor={\(options.author ? authorText ?? "" : "")},\n pdftitle={\(options.title ? title : "")},\n" |
| 186 | out += " pdfkeywords={\(try keywords["KEYWORDS"].map { try parsed($0) } ?? "")},\n" |
| 187 | out += " pdfsubject={\(try keywords["DESCRIPTION"].map { try parsed($0) } ?? "")},\n pdfcreator={},\n pdflang={\(Self.capitalize(lang))}}\n" |
| 188 | out += "\\begin{document}\n\n" |
| 189 | if options.title, !title.isEmpty { out += "\\maketitle\n" } |
| 190 | if withTOC { |
| 191 | if let toc { out += "\\setcounter{tocdepth}{\(toc)}\n" } |
| 192 | out += "\\tableofcontents\n\n" |
| 193 | } |
| 194 | return out + body + "\\end{document}" |
| 195 | } |
| 196 | |
| 197 | /// A keyword parsed as Org text, its lines joined with spaces. |
| 198 | private func parsed(_ values: [String]) throws -> String { |
| 199 | try inlineString(values.joined(separator: " ")) |
| 200 | } |
| 201 | |
| 202 | /// `org-latex-make-preamble` with the class, its options and the header lines. |
| 203 | private func preamble(compiler: String) -> String { |
| 204 | var header = LaTeXExport.classes[className]!.header |
| 205 | if let classOptions = options.latexClassOptions { |
| 206 | header = header.replacingOccurrences(of: "[11pt]", with: classOptions) |
| 207 | } |
| 208 | let known = LaTeXExport.compilers.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame } |
| 209 | let packages = LaTeXExport.packages.filter { !known || $0.2.isEmpty || $0.2.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame } } |
| 210 | .map { $0.0.isEmpty ? "\\usepackage{\($0.1)}" : "\\usepackage[\($0.0)]{\($0.1)}" } |
| 211 | var out = header + "\n\n" + packages.joined(separator: "\n") |
| 212 | let extra = [options.latexHeader, options.latexHeaderExtra].filter { !$0.isEmpty }.map { Self.normalize($0.joined(separator: "\n")) }.joined() |
| 213 | if extra.contains(where: { !$0.isWhitespace }) { out += "\n" + extra } |
| 214 | return Self.normalize(out) |
| 215 | } |
| 216 | |
| 217 | /// `:lang-name` in `org-latex-language-alist`. |
| 218 | static let languageNames: [String: String] = [ |
| 219 | "af": "Afrikaans", "am": "Amharic", "ar": "Arabic", "ast": "Asturian", "bg": "Bulgarian", "bn": "Bengali", "bo": "Tibetan", |
| 220 | "br": "Breton", "ca": "Catalan", "cop": "Coptic", "cs": "Czech", "cy": "Welsh", "da": "Danish", "de": "German", "de-de": "German", |
| 221 | "de-at": "German", "dsb": "Lower Sorbian", "dv": "Dhivehi", "el": "Greek", "el-polyton": "Polytonic Greek", "grc": "Ancient Greek", |
| 222 | "en": "English", "en-au": "English", "en-ca": "English", "en-gb": "English", "en-nz": "English", "en-us": "English", |
| 223 | "eo": "Esperanto", "es": "Spanish", "es-mx": "Spanish", "et": "Estonian", "eu": "Basque", "fa": "Persian", "fi": "Finnish", |
| 224 | "fr": "French", "fr-ca": "French", "fur": "Friulian", "ga": "Irish Gaelic", "gd": "Scottish Gaelic", "gl": "Galician", |
| 225 | "he": "Hebrew", "hi": "Hindi", "hr": "Croatian", "hsb": "Upper Sorbian", "hu": "Magyar", "hy": "Armenian", "ia": "Interlingua", |
| 226 | "id": "Indonesian", "is": "Icelandic", "it": "Italian", "kn": "Kannada", "la": "Latin", "la-classic": "Classic Latin", |
| 227 | "la-medieval": "Medieval Latin", "la-ecclesiastic": "Ecclesiastic Latin", "lo": "Lao", "lt": "Lithuanian", "lv": "Latvian", |
| 228 | "ml": "Malayalam", "mr": "Marathi", "ms": "Malay", "nb": "Norwegian Bokmål", "nl": "Dutch", "nn": "Norwegian Nynorsk", |
| 229 | "no": "Norwegian", "oc": "Occitan", "pl": "Polish", "pms": "Piedmontese", "pt": "Portuges", "pt-br": "Portuges", "rm": "Romansh", |
| 230 | "ro": "Romanian", "ru": "Russian", "sa": "Sanskrit", "sk": "Slovak", "sl": "Slovene", "sq": "Albanian", "sr": "Serbian", |
| 231 | "sr-cyrl": "Serbian", "sr-latn": "Serbian", "sv": "Swedish", "syr": "Syriac", "ta": "Tamil", "te": "Telugu", "th": "Thai", |
| 232 | "tk": "Turkmen", "tr": "Turkish", "uk": "Ukrainian", "ur": "Urdu", "vi": "Vietnamese", "zh": "Chinese Simplified", |
| 233 | "zh-cn": "Chinese Simplified", "zh-tw": "Chinese Traditional", |
| 234 | ] |
| 235 | |
| 236 | /// Emacs's `capitalize`: each word's first letter up, the rest down. |
| 237 | static func capitalize(_ s: String) -> String { |
| 238 | var out = "" |
| 239 | var inWord = false |
| 240 | for c in s { |
| 241 | let word = c.isLetter || c.isNumber |
| 242 | out += word ? (inWord ? c.lowercased() : c.uppercased()) : String(c) |
| 243 | inWord = word |
| 244 | } |
| 245 | return out |
| 246 | } |
| 247 | |
| 248 | // MARK: - Strings |
| 249 | |
| 250 | /// `org-element-normalize-string`: one final newline, none for the empty string. |
| 251 | static func normalize(_ s: String) -> String { |
| 252 | guard !s.isEmpty else { return "" } |
| 253 | var end = s.endIndex |
| 254 | var cut = s.endIndex |
| 255 | while end > s.startIndex { |
| 256 | let before = s.index(before: end) |
| 257 | if s[before] == " " || s[before] == "\t" { |
| 258 | end = before |
| 259 | } else if s[before] == "\n" { |
| 260 | end = before |
| 261 | cut = before |
| 262 | } else { |
| 263 | break |
| 264 | } |
| 265 | } |
| 266 | return String(s[..<cut]) + "\n" |
| 267 | } |
| 268 | |
| 269 | /// `org-trim`. |
| 270 | static func trim(_ s: String) -> String { s.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r\u{0C}\u{0B}")) } |
| 271 | |
| 272 | /// `org-latex--protect-text`. |
| 273 | static func protect(_ s: String) -> String { |
| 274 | var out = "" |
| 275 | for c in s { |
| 276 | if "\\{}$%&_#~^".contains(c) { out += "\\" } |
| 277 | out.append(c) |
| 278 | } |
| 279 | return out |
| 280 | } |
| 281 | |
| 282 | /// `org-latex--protect-texttt`. |
| 283 | static func texttt(_ s: String) -> String { |
| 284 | var out = "" |
| 285 | var i = s.startIndex |
| 286 | while i < s.endIndex { |
| 287 | let rest = s[i...] |
| 288 | if rest.hasPrefix("--") || rest.hasPrefix("<<") || rest.hasPrefix(">>") { |
| 289 | out += "\(s[i]){}\(s[i]){}" |
| 290 | i = s.index(i, offsetBy: 2) |
| 291 | continue |
| 292 | } |
| 293 | switch s[i] { |
| 294 | case "\\": out += "\\textbackslash{}" |
| 295 | case "~": out += "\\textasciitilde{}" |
| 296 | case "^": out += "\\textasciicircum{}" |
| 297 | case "{", "}", "$", "%", "&", "_", "#": out += "\\\(s[i])" |
| 298 | default: out.append(s[i]) |
| 299 | } |
| 300 | i = s.index(after: i) |
| 301 | } |
| 302 | return "\\texttt{\(out)}" |
| 303 | } |
| 304 | |
| 305 | /// `org-remove-indentation`: the common indentation of the non-blank lines removed. |
| 306 | static func removeIndentation(_ s: String) throws -> String { |
| 307 | let lines = s.components(separatedBy: "\n") |
| 308 | let indents = lines.filter { $0.contains { $0 != " " && $0 != "\t" } }.map { $0.prefix { $0 == " " || $0 == "\t" } } |
| 309 | guard let common = indents.map(\.count).min(), common > 0 else { return s } |
| 310 | if indents.contains(where: { $0.contains("\t") }) { throw Unsupported(reason: "Tabs in indented code") } |
| 311 | return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }.joined(separator: "\n") |
| 312 | } |
| 313 | |
| 314 | // MARK: - Labels |
| 315 | |
| 316 | private var references: [String: String] = [:] |
| 317 | private var usedReferences: Set<String> = [] |
| 318 | |
| 319 | /// `org-export-get-reference`: a label for `key`, made from it so it stays the same between |
| 320 | /// exports of the same document. |
| 321 | func reference(_ key: String) -> String { |
| 322 | if let existing = references[key] { return existing } |
| 323 | var hash: UInt32 = 2_166_136_261 |
| 324 | for byte in key.utf8 { hash = (hash ^ UInt32(byte)) &* 16_777_619 } |
| 325 | var value = hash & 0xFFFFFFF |
| 326 | var label = String(format: "org%07x", value) |
| 327 | while usedReferences.contains(label) { |
| 328 | value = (value &+ 1) & 0xFFFFFFF |
| 329 | label = String(format: "org%07x", value) |
| 330 | } |
| 331 | usedReferences.insert(label) |
| 332 | references[key] = label |
| 333 | return label |
| 334 | } |
| 335 | |
| 336 | // MARK: - Document |
| 337 | |
| 338 | /// The transcoded document, `org-element-normalize-string`'d. |
| 339 | func body() throws -> String { |
| 340 | var nodes = tree.root.children |
| 341 | // With a select tag, the text before the first heading isn't exported. |
| 342 | if selected != nil { nodes.removeAll { $0.kind == .zerothSection } } |
| 343 | var out = "" |
| 344 | for node in nodes { |
| 345 | if node.kind == .zerothSection { |
| 346 | out += Self.normalize(try elements(node.children, end: node.range.upperBound)) |
| 347 | } else if node.kind == .section { |
| 348 | out += try section(node) ?? "" |
| 349 | } |
| 350 | } |
| 351 | return Self.normalize(out) |
| 352 | } |
| 353 | |
| 354 | /// Blank lines at the end of `source[from..<to]`. |
| 355 | func blankLines(from: Int, to: Int) -> Int { |
| 356 | guard to > from else { return 0 } |
| 357 | let source = currentSource ?? self.source |
| 358 | let lines = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)).components(separatedBy: "\n").dropLast() |
| 359 | return lines.reversed().prefix { $0.allSatisfy { $0 == " " || $0 == "\t" } }.count |
| 360 | } |
| 361 | |
| 362 | /// Affiliated keywords of the element being transcoded. |
| 363 | struct Affiliated { |
| 364 | var caption: [String] = [] |
| 365 | var name: String? |
| 366 | var attr: [String] = [] |
| 367 | /// `#+RESULTS`' value, when it has the keyword. |
| 368 | var results: String? |
| 369 | |
| 370 | /// `org-export-read-attribute :attr_latex`: values by key, nil for `nil` or nothing. |
| 371 | func attribute(_ key: String) -> String?? { |
| 372 | guard !attr.isEmpty else { return .none } |
| 373 | var s = attr.joined(separator: " ") |
| 374 | var pairs: [(String, String?)] = [] |
| 375 | var pending: String? |
| 376 | let re = #/(?:^|[ \t]+)(:[-a-zA-Z0-9_]+)(?:[ \t]+|$)/# |
| 377 | while let m = s.firstMatch(of: re) { |
| 378 | if let pending { pairs.append((pending, Self.value(String(s[..<m.range.lowerBound])))) } |
| 379 | pending = String(m.1) |
| 380 | s = String(s[m.range.upperBound...]) |
| 381 | } |
| 382 | if let pending { pairs.append((pending, Self.value(s))) } |
| 383 | guard let pair = pairs.first(where: { $0.0 == ":" + key }) else { return .none } |
| 384 | return .some(pair.1) |
| 385 | } |
| 386 | |
| 387 | static func value(_ s: String) -> String? { |
| 388 | if s.isEmpty || s == "nil" { return nil } |
| 389 | if let m = s.wholeMatch(of: /"("+)?"/) { return m.1.map(String.init) ?? "" } |
| 390 | return s |
| 391 | } |
| 392 | |
| 393 | /// The attribute's value, nil when absent or nil. |
| 394 | func value(_ key: String) -> String? { attribute(key) ?? nil } |
| 395 | func has(_ key: String) -> Bool { attribute(key) != nil } |
| 396 | } |
| 397 | |
| 398 | /// `elements`, each `org-element-normalize-string`'d and followed by its blank lines, as |
| 399 | /// `org-export-data` joins a greater element's contents. |
| 400 | func elements(_ nodes: [SyntaxNode], end: Int) throws -> String { |
| 401 | var out = "" |
| 402 | var affiliated = Affiliated() |
| 403 | // The element before and its blank lines, which a comment after it may add to; they |
| 404 | // show only when it wrote something. |
| 405 | var pendingBlank = 0 |
| 406 | var previous: SyntaxNode? |
| 407 | var previousWrote = false |
| 408 | var afterSrc = false |
| 409 | for (index, node) in nodes.enumerated() { |
| 410 | let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end |
| 411 | if node.kind == .affiliatedKeyword { |
| 412 | let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 413 | guard let m = line.firstMatch(of: /^#\+([A-Za-z_]+)(\[[^\]]*\])?:[ \t]*(.*)$/) else { continue } |
| 414 | let key = m.1.uppercased() |
| 415 | if m.2 != nil, key != "CAPTION", key != "RESULTS" { throw Unsupported(reason: "#+\(key)[…]") } |
| 416 | switch key { |
| 417 | case "CAPTION": |
| 418 | if m.2 != nil { throw Unsupported(reason: "Short captions") } |
| 419 | affiliated.caption.append(String(m.3)) |
| 420 | case "NAME": affiliated.name = String(m.3) |
| 421 | case "ATTR_LATEX": affiliated.attr.append(String(m.3)) |
| 422 | case "RESULTS": affiliated.results = String(m.3) |
| 423 | default: break |
| 424 | } |
| 425 | continue |
| 426 | } |
| 427 | defer { affiliated = Affiliated() } |
| 428 | // `org-babel-exp-process-buffer`: a src block's results go, and with `:exports none` |
| 429 | // the block too, as if they had never been there. |
| 430 | if node.kind == .block, blockType(node) == "src" { |
| 431 | let exports = exportSource.exports(at: node.range.lowerBound) ?? "code" |
| 432 | if exports != "code", exports != "none" { throw Unsupported(reason: ":exports \(exports)") } |
| 433 | afterSrc = true |
| 434 | if exports == "none" { continue } |
| 435 | } else if let results = affiliated.results { |
| 436 | if afterSrc { |
| 437 | afterSrc = false |
| 438 | continue |
| 439 | } |
| 440 | if results.isEmpty { throw Unsupported(reason: "#+RESULTS without a source block") } |
| 441 | if affiliated.name == nil { affiliated.name = results } |
| 442 | } else { |
| 443 | afterSrc = false |
| 444 | } |
| 445 | if node.kind == .comment || (node.kind == .block && blockType(node) == "comment") { |
| 446 | // `org-export--skip-p`: the element before keeps at least one blank line. |
| 447 | if previous != nil { |
| 448 | let blank = max(pendingBlank, blankLines(from: node.range.lowerBound, to: next), 1) |
| 449 | if previousWrote { out += String(repeating: "\n", count: blank - pendingBlank) } |
| 450 | pendingBlank = blank |
| 451 | } |
| 452 | continue |
| 453 | } |
| 454 | guard let result = try element(node, affiliated: affiliated, previous: previous, previousBlank: pendingBlank) else { |
| 455 | if !pruned(node) { |
| 456 | previous = node |
| 457 | previousWrote = false |
| 458 | pendingBlank = blankLines(from: node.range.lowerBound, to: next) |
| 459 | } |
| 460 | continue |
| 461 | } |
| 462 | previous = node |
| 463 | previousWrote = true |
| 464 | pendingBlank = blankLines(from: node.range.lowerBound, to: next) |
| 465 | var text = Self.normalize(result) + String(repeating: "\n", count: pendingBlank) |
| 466 | if node.kind == .paragraph { text = Self.cleanLineBreaks(text) } |
| 467 | out += text |
| 468 | } |
| 469 | return out |
| 470 | } |
| 471 | |
| 472 | /// Elements `org-export--prune-tree` takes out of the tree. |
| 473 | private func pruned(_ node: SyntaxNode) -> Bool { |
| 474 | switch node.kind { |
| 475 | case .planning, .propertyDrawer, .clock, .footnoteDefinition: return true |
| 476 | case .drawer: return drawerName(node).uppercased() == "LOGBOOK" |
| 477 | case .latexEnvironment: return !options.tex |
| 478 | default: return false |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | private func drawerName(_ node: SyntaxNode) -> String { |
| 483 | node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1) } ?? "" |
| 484 | } |
| 485 | |
| 486 | /// `org-latex-clean-invalid-line-breaks`. |
| 487 | static func cleanLineBreaks(_ s: String) -> String { |
| 488 | s.replacing(#/(?m)(\\end\{[A-Za-z0-9*]+\}|^)[ \t]*\\\\[ \t]*$/#) { String($0.1) } |
| 489 | } |
| 490 | |
| 491 | // MARK: - Headlines |
| 492 | |
| 493 | /// A section's heading and contents, nil when not exported. |
| 494 | private func section(_ node: SyntaxNode) throws -> String? { |
| 495 | guard let heading = node.firstChild(.heading) else { return nil } |
| 496 | // `org-footnote-section`'s heading isn't exported. |
| 497 | if heading.firstChild(.title)?.text == "Footnotes" { return nil } |
| 498 | let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected) |
| 499 | if export == .nothing { return nil } |
| 500 | let children = node.children.filter { $0.kind != .heading } |
| 501 | let body = children.filter { $0.kind != .section } |
| 502 | let subsections = children.filter { $0.kind == .section } |
| 503 | var contents: String? |
| 504 | if export == .all { |
| 505 | var out = Self.normalize(try elements(body, end: subsections.first?.range.lowerBound ?? node.range.upperBound)) |
| 506 | let exported = try subsections.compactMap { try section($0) } |
| 507 | for (index, sub) in exported.enumerated() { |
| 508 | out += sub |
| 509 | _ = index |
| 510 | } |
| 511 | contents = Self.normalize(out) |
| 512 | } |
| 513 | let first = children.first?.range.lowerBound ?? node.range.upperBound |
| 514 | let preBlank = children.isEmpty ? 0 : blankLines(from: heading.range.lowerBound, to: first) |
| 515 | return Self.normalize(try headline(heading, section: node, contents: contents, preBlank: preBlank)) |
| 516 | } |
| 517 | |
| 518 | /// `org-latex-headline`. |
| 519 | private func headline(_ heading: SyntaxNode, section: SyntaxNode, contents: String?, preBlank: Int) throws -> String { |
| 520 | let tokens = heading.tokens |
| 521 | let level = (tokens.first { $0.kind == .stars }?.text.count ?? 1) + levelOffset |
| 522 | if let index = model.headings.firstIndex(where: { $0.headingRange.lowerBound == heading.range.lowerBound }) { |
| 523 | let keys = model.headings[index].properties.map { $0.key.uppercased() } |
| 524 | if keys.contains("UNNUMBERED") || keys.contains("ALT_TITLE") { throw Unsupported(reason: "UNNUMBERED and ALT_TITLE properties") } |
| 525 | } |
| 526 | let isNumbered = numbered && (num.map { level <= $0 } ?? true) |
| 527 | let titleNode = heading.firstChild(.title) |
| 528 | if titleNode?.descendants().contains(where: { $0.kind == .footnoteReference }) == true { throw Unsupported(reason: "Footnotes in headings") } |
| 529 | let text = try titleNode.map { try Self.trim(inline($0, sectionTitle: true)) } ?? "" |
| 530 | var full = "" |
| 531 | if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text { |
| 532 | full += "{\\bfseries\\sffamily \(plainText(todo))} " |
| 533 | } |
| 534 | if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text, |
| 535 | let letter = priority.firstMatch(of: /\[#(.+)\]/)?.1 { |
| 536 | full += "\\framebox{\\#\(letter)} " |
| 537 | } |
| 538 | full += text |
| 539 | if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text { |
| 540 | let shown = tags.split(separator: ":").map(String.init) |
| 541 | if !shown.isEmpty { full += "\\hfill{}\\textsc{\(shown.map(Self.protect).joined(separator: ":"))}" } |
| 542 | } |
| 543 | let label = "\\label{sec:\(reference("heading@\(heading.range.lowerBound)"))}\n" |
| 544 | let pre = String(repeating: "\n", count: preBlank) |
| 545 | let sections = LaTeXExport.classes[className]!.sections |
| 546 | if level > options.headlineLevels || level > sections.count { |
| 547 | let siblings = exportedSiblings(section) |
| 548 | let first = siblings.first == section.range.lowerBound |
| 549 | let last = siblings.last == section.range.lowerBound |
| 550 | let list = isNumbered ? "enumerate" : "itemize" |
| 551 | var out = first ? "\\begin{\(list)}\n" : "" |
| 552 | out += "\\item" + (full.firstMatch(of: /^[ \t]*\[/) != nil ? "\\relax" : "") + " " + full + "\n" + label + pre + (contents ?? "") |
| 553 | if last { |
| 554 | while let c = out.last, c == " " || c == "\t" || c == "\n" { out.removeLast() } |
| 555 | out += "\n\\end{\(list)}" |
| 556 | } |
| 557 | return out |
| 558 | } |
| 559 | let format = isNumbered ? sections[level - 1].0 : sections[level - 1].1 |
| 560 | return format.replacingOccurrences(of: "%s", with: full) + "\n" + label + pre + (contents ?? "") |
| 561 | } |
| 562 | |
| 563 | /// The headline sections exported beside `section` at its level, by start: a low-level |
| 564 | /// headline opens its list when it is the first and closes it when it is the last. |
| 565 | private func exportedSiblings(_ section: SyntaxNode) -> [Int] { |
| 566 | guard let parent = section.parent else { return [section.range.lowerBound] } |
| 567 | // A section with a body before it means the headline isn't first. |
| 568 | var starts: [Int] = [] |
| 569 | var bodyBefore = false |
| 570 | for child in parent.children where child.kind != .heading { |
| 571 | if child.kind != .section { |
| 572 | if starts.isEmpty { bodyBefore = true } |
| 573 | continue |
| 574 | } |
| 575 | guard let heading = child.firstChild(.heading), HTMLRenderer.sectionExport(heading, options: options, selected: selected) != .nothing else { continue } |
| 576 | starts.append(child.range.lowerBound) |
| 577 | } |
| 578 | _ = bodyBefore |
| 579 | return starts |
| 580 | } |
| 581 | |
| 582 | // MARK: - Elements |
| 583 | |
| 584 | private func blockType(_ node: SyntaxNode) -> String { |
| 585 | node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/).map { $0.1.lowercased() } ?? "" |
| 586 | } |
| 587 | |
| 588 | /// One element's transcoding, nil for none. |
| 589 | private func element(_ node: SyntaxNode, affiliated: Affiliated, previous: SyntaxNode?, previousBlank: Int) throws -> String? { |
| 590 | switch node.kind { |
| 591 | case .paragraph: |
| 592 | return try paragraph(node, affiliated: affiliated) |
| 593 | case .plainList: |
| 594 | return try list(node, affiliated: affiliated) |
| 595 | case .table: |
| 596 | return try table(node, affiliated: affiliated) |
| 597 | case .block: |
| 598 | return try block(node, affiliated: affiliated) |
| 599 | case .horizontalRule: |
| 600 | var out = previous != nil && previousBlank == 0 ? "\n" : "" |
| 601 | out += try wrapLabel(affiliated, "\\noindent\\rule{\(affiliated.value("width") ?? "\\textwidth")}{\(affiliated.value("thickness") ?? "0.5pt")}") |
| 602 | return out |
| 603 | case .fixedWidth: |
| 604 | let value = node.text.components(separatedBy: "\n").filter { !$0.isEmpty } |
| 605 | .map { $0.replacingOccurrences(of: "^[ \\t]*: ?", with: "", options: .regularExpression) }.joined(separator: "\n") |
| 606 | return try wrapLabel(affiliated, "\\begin{verbatim}\n\(try Self.removeIndentation(value))\n\\end{verbatim}") |
| 607 | case .latexEnvironment: |
| 608 | guard options.tex else { return nil } |
| 609 | if affiliated.name != nil || !affiliated.caption.isEmpty { throw Unsupported(reason: "Named or captioned LaTeX environments") } |
| 610 | var value = node.text |
| 611 | while value.hasSuffix("\n") { value.removeLast() } |
| 612 | return try Self.removeIndentation(value) + "\n" |
| 613 | case .keyword: |
| 614 | return try keyword(node) |
| 615 | case .drawer: |
| 616 | if drawerName(node).uppercased() == "LOGBOOK" { return nil } |
| 617 | let inner = node.children |
| 618 | return try wrapLabel(affiliated, Self.normalize(try elements(inner, end: node.range.upperBound))) |
| 619 | case .dynamicBlock: |
| 620 | let lines = node.text.components(separatedBy: "\n") |
| 621 | return try wrapLabel(affiliated, Self.normalize(try blocks(lines.dropFirst().dropLast(2).joined(separator: "\n")))) |
| 622 | case .planning, .propertyDrawer, .clock, .footnoteDefinition, .nodeProperty: |
| 623 | return nil |
| 624 | default: |
| 625 | throw Unsupported(reason: "\(node.kind)") |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | /// `org-latex--wrap-label`. |
| 630 | private func wrapLabel(_ affiliated: Affiliated, _ output: String) throws -> String { |
| 631 | guard let name = affiliated.name, output.contains(where: { !$0.isWhitespace }) else { return output } |
| 632 | return "\\phantomsection\n\\label{\(reference("name:" + name))}\n" + output |
| 633 | } |
| 634 | |
| 635 | /// Org text parsed and transcoded as elements. |
| 636 | func blocks(_ text: String) throws -> String { |
| 637 | let tree = OrgParser.parse(text, defaults: settings) |
| 638 | let saved = exportSource |
| 639 | exportSource = ExportSource(tree: tree, text: text) |
| 640 | defer { exportSource = saved } |
| 641 | let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] } |
| 642 | if nodes.contains(where: { $0.kind == .section }) { throw Unsupported(reason: "Headings inside blocks") } |
| 643 | let saveSource = currentSource |
| 644 | currentSource = text as NSString |
| 645 | defer { currentSource = saveSource } |
| 646 | return try elements(nodes, end: (text as NSString).length) |
| 647 | } |
| 648 | |
| 649 | /// The text blank lines are counted in, when it isn't the document's. |
| 650 | private var currentSource: NSString? |
| 651 | |
| 652 | private func keyword(_ node: SyntaxNode) throws -> String? { |
| 653 | let line = node.text.trimmingCharacters(in: .newlines) |
| 654 | guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { return nil } |
| 655 | let value = m.2.map(String.init) ?? "" |
| 656 | switch m.1.uppercased() { |
| 657 | case "LATEX": return value |
| 658 | case "INDEX": return "\\index{\(value)}" |
| 659 | case "TOC": |
| 660 | if value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil { throw Unsupported(reason: "#+TOC: local") } |
| 661 | if value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil { |
| 662 | let depth = value.firstMatch(of: /\b([0-9]+)\b/).map { "\\setcounter{tocdepth}{\($0.1)}\n" } ?? "" |
| 663 | return depth + "\\tableofcontents" |
| 664 | } |
| 665 | if value.range(of: "\\btables\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\listoftables" } |
| 666 | if value.range(of: "\\blistings\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\lstlistoflistings" } |
| 667 | return nil |
| 668 | default: return nil |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | // MARK: Paragraphs |
| 673 | |
| 674 | private func paragraph(_ node: SyntaxNode, affiliated: Affiliated, ignoreFirst: Bool = false) throws -> String { |
| 675 | var items = Self.normalizeIndentation(try inlineItems(node), ignoreFirst: ignoreFirst) |
| 676 | if let image = soleImage(items) { |
| 677 | items = [] |
| 678 | return try inlineImage(image, affiliated: affiliated, alone: true) |
| 679 | } |
| 680 | if items.contains(where: { if case .object(let n, _) = $0, n.kind == .link, isImage(n) { return true } else { return false } }) { |
| 681 | currentAffiliated = affiliated |
| 682 | defer { currentAffiliated = nil } |
| 683 | return Self.removeBlankLines(try transcode(items)) |
| 684 | } |
| 685 | if !affiliated.caption.isEmpty { throw Unsupported(reason: "Captioned paragraphs") } |
| 686 | return Self.removeBlankLines(try transcode(items)) |
| 687 | } |
| 688 | |
| 689 | private var currentAffiliated: Affiliated? |
| 690 | |
| 691 | /// `org-remove-blank-lines`. |
| 692 | static func removeBlankLines(_ s: String) -> String { |
| 693 | s.replacing(#/\n(?:[ \t]*\n)+/#, with: "\n") |
| 694 | } |
| 695 | |
| 696 | // MARK: Lists |
| 697 | |
| 698 | private func isOrderedBullet(_ item: SyntaxNode) -> Bool { |
| 699 | let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-" |
| 700 | return bullet.first.map { $0.isASCII && ($0.isLetter || $0.isNumber) } ?? false |
| 701 | } |
| 702 | |
| 703 | /// `org-latex-plain-list`, its type from the first item. |
| 704 | private func list(_ node: SyntaxNode, affiliated: Affiliated, orderedDepth: Int = 0) throws -> String { |
| 705 | let items = node.children.filter { $0.kind == .item } |
| 706 | guard let first = items.first else { return "" } |
| 707 | let ordered = isOrderedBullet(first) |
| 708 | let description = !ordered && first.firstChild(.itemTag) != nil |
| 709 | let type = affiliated.value("environment") ?? (ordered ? "enumerate" : description ? "description" : "itemize") |
| 710 | let depth = orderedDepth + (ordered ? 1 : 0) |
| 711 | var contents = "" |
| 712 | for (index, item) in items.enumerated() { |
| 713 | let next = index + 1 < items.count ? items[index + 1].range.lowerBound : node.range.upperBound |
| 714 | let text = try self.item(item, ordered: ordered, depth: depth) |
| 715 | contents += Self.normalize(text) + String(repeating: "\n", count: blankLines(from: item.range.lowerBound, to: next)) |
| 716 | } |
| 717 | return try wrapLabel(affiliated, "\\begin{\(type)}\(affiliated.value("options") ?? "")\n\(Self.normalize(contents))\\end{\(type)}") |
| 718 | } |
| 719 | |
| 720 | private var listDepth = 0 |
| 721 | |
| 722 | /// `org-latex-item`. |
| 723 | private func item(_ item: SyntaxNode, ordered: Bool, depth: Int) throws -> String { |
| 724 | var counter = "" |
| 725 | if let value = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+)/) { |
| 726 | guard ordered, depth < 5, let n = Int(value.1) else { throw Unsupported(reason: "Counters outside ordered lists") } |
| 727 | counter = "\\setcounter{enum\(["i", "ii", "iii", "iv"][depth - 1])}{\(n - 1)}\n" |
| 728 | } else if item.tokens.contains(where: { $0.kind == .counter }) { |
| 729 | throw Unsupported(reason: "Alphabetical counters") |
| 730 | } |
| 731 | let checkbox: String? = item.tokens.first { $0.kind == .checkbox }.map { |
| 732 | switch $0.text.uppercased() { |
| 733 | case "[X]": "$\\boxtimes$" |
| 734 | case "[-]": "$\\boxminus$" |
| 735 | default: "$\\square$" |
| 736 | } |
| 737 | } |
| 738 | var tag: String? |
| 739 | if let tagNode = item.firstChild(.itemTag) { |
| 740 | if tagNode.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in item tags") } |
| 741 | tag = try transcode(Self.merge(try inlineItems(tagNode))) |
| 742 | } |
| 743 | let children = item.children.filter { $0.kind != .itemTag } |
| 744 | var contents = "" |
| 745 | var previous: SyntaxNode? |
| 746 | for (index, child) in children.enumerated() { |
| 747 | let next = index + 1 < children.count ? children[index + 1].range.lowerBound : item.range.upperBound |
| 748 | var result: String? |
| 749 | if child.kind == .paragraph, previous == nil, index == 0 { |
| 750 | // The first paragraph's first line follows the bullet: its indentation doesn't count. |
| 751 | let bulletLine = source.lineRange(for: NSRange(location: item.range.lowerBound, length: 0)) |
| 752 | let ignore = child.range.lowerBound < NSMaxRange(bulletLine) |
| 753 | result = try paragraph(child, affiliated: Affiliated(), ignoreFirst: ignore) |
| 754 | } else if child.kind == .plainList { |
| 755 | result = try list(child, affiliated: Affiliated(), orderedDepth: depth) |
| 756 | } else { |
| 757 | // Elements with affiliated keywords go through `elements`. |
| 758 | result = try elements([child], end: next) |
| 759 | if result == "" { result = nil } |
| 760 | if let r = result { |
| 761 | contents += r |
| 762 | previous = child |
| 763 | continue |
| 764 | } |
| 765 | } |
| 766 | guard let result else { continue } |
| 767 | previous = child |
| 768 | var text = Self.normalize(result) + String(repeating: "\n", count: blankLines(from: child.range.lowerBound, to: next)) |
| 769 | if child.kind == .paragraph { text = Self.cleanLineBreaks(text) } |
| 770 | contents += text |
| 771 | } |
| 772 | if children.contains(where: { $0.kind == .affiliatedKeyword }) { throw Unsupported(reason: "Affiliated keywords in list items") } |
| 773 | contents = Self.normalize(contents) |
| 774 | var out = counter + "\\item" |
| 775 | if let checkbox, let tag { |
| 776 | out += ordered ? "{\(checkbox) \(tag)} " : "[{\(checkbox) \(tag)}] " |
| 777 | } else if let label = checkbox ?? tag { |
| 778 | out += ordered ? "{\(label)} " : "[{\(label)}] " |
| 779 | } else if contents.firstMatch(of: /^[ \t]*\[/) != nil { |
| 780 | out += "\\relax " |
| 781 | } else { |
| 782 | out += " " |
| 783 | } |
| 784 | return out + Self.trim(contents) |
| 785 | } |
| 786 | |
| 787 | // MARK: Tables |
| 788 | |
| 789 | /// `org-table-number-regexp`. |
| 790 | static let numberPattern = try! NSRegularExpression(pattern: "^(?:[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$") |
| 791 | |
| 792 | private func table(_ node: SyntaxNode, affiliated: Affiliated) throws -> String { |
| 793 | let rows = node.children.filter { $0.kind == .tableRow } |
| 794 | if node.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in tables") } |
| 795 | let mode = affiliated.value("mode") ?? "table" |
| 796 | guard mode == "table" else { throw Unsupported(reason: "#+ATTR_LATEX: :mode \(mode)") } |
| 797 | let environment = affiliated.value("environment") ?? "tabular" |
| 798 | if ["longtable", "longtabu", "tabbing"].contains(environment) { throw Unsupported(reason: "#+ATTR_LATEX: :environment \(environment)") } |
| 799 | let booktabs = affiliated.has("booktabs") ? affiliated.value("booktabs") != nil : false |
| 800 | if booktabs { throw Unsupported(reason: "Booktabs tables") } |
| 801 | // Cells as transcoded, rules as nil. |
| 802 | var cells: [[String]?] = [] |
| 803 | for row in rows { |
| 804 | let rowCells = row.children.filter { $0.kind == .tableCell } |
| 805 | if rowCells.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") { |
| 806 | cells.append(nil) |
| 807 | continue |
| 808 | } |
| 809 | if rowCells.isEmpty { continue } |
| 810 | cells.append(try rowCells.map { try transcode(Self.merge(try inlineItems($0, trimmed: true))) }) |
| 811 | } |
| 812 | let data = cells.compactMap { $0 } |
| 813 | if Self.hasSpecialRows(data.map { $0 }, raw: rows) { throw Unsupported(reason: "Tables with alignment cookies or special columns") } |
| 814 | let columns = data.first?.count ?? 0 |
| 815 | var align = "" |
| 816 | for c in 0..<columns { |
| 817 | var numbers = 0, total = 0 |
| 818 | var previousNumber = false |
| 819 | for row in data { |
| 820 | let value = c < row.count ? row[c] : "" |
| 821 | total += 1 |
| 822 | let isNumber = Self.numberPattern.firstMatch(in: value, range: NSRange(location: 0, length: (value as NSString).length)) != nil |
| 823 | if isNumber || (value.isEmpty && previousNumber) { |
| 824 | previousNumber = true |
| 825 | numbers += 1 |
| 826 | } else { |
| 827 | previousNumber = false |
| 828 | } |
| 829 | } |
| 830 | align += total > 0 && Double(numbers) / Double(total) >= 0.5 ? "r" : "l" |
| 831 | } |
| 832 | let alignment = affiliated.value("align") ?? align |
| 833 | var contents = "" |
| 834 | for row in cells { |
| 835 | guard let row else { |
| 836 | contents += "\\hline\n" |
| 837 | continue |
| 838 | } |
| 839 | contents += Self.normalize(row.joined(separator: " & ") + "\\\\\n") |
| 840 | } |
| 841 | contents = Self.normalize(contents) |
| 842 | var width = "" |
| 843 | if let w = affiliated.value("width"), !["tabular", "longtable"].contains(environment) { |
| 844 | if ["tabu", "longtabu"].contains(environment) { throw Unsupported(reason: "tabu tables") } |
| 845 | width = "{\(w)}" |
| 846 | } |
| 847 | let opt = affiliated.value("options").map { "[\($0)]" } ?? "" |
| 848 | let table = "\\begin{\(environment)}\(opt)\(width){\(alignment)}\n\(contents)\\end{\(environment)}" |
| 849 | let caption = try captionLabel(affiliated, type: "table", prefix: "tab:") |
| 850 | return decorate(table, affiliated: affiliated, caption: caption, above: true) |
| 851 | } |
| 852 | |
| 853 | /// Whether a table has rows of alignment cookies or a column of row marks. |
| 854 | static func hasSpecialRows(_ data: [[String]], raw: [SyntaxNode]) -> Bool { |
| 855 | let cookie = /^<[lrc]?[0-9]*>$/ |
| 856 | for row in raw { |
| 857 | let cells = row.children.filter { $0.kind == .tableCell }.map { $0.text.trimmingCharacters(in: .whitespaces) } |
| 858 | guard !cells.isEmpty else { continue } |
| 859 | if cells.allSatisfy({ $0.isEmpty || $0.wholeMatch(of: cookie) != nil }), cells.contains(where: { !$0.isEmpty }) { return true } |
| 860 | } |
| 861 | let marks: Set<String> = ["", "#", "!", "$", "*", "^", "_", "/"] |
| 862 | let first = raw.compactMap { $0.children.first { $0.kind == .tableCell }?.text.trimmingCharacters(in: .whitespaces) } |
| 863 | return !first.isEmpty && first.allSatisfy(marks.contains) && first.contains { !$0.isEmpty } |
| 864 | } |
| 865 | |
| 866 | /// `org-latex--decorate-table`. |
| 867 | private func decorate(_ table: String, affiliated: Affiliated, caption: String, above: Bool) -> String { |
| 868 | let floatEnvironment: String? |
| 869 | let float = affiliated.attribute("float") |
| 870 | switch float { |
| 871 | case .some(nil): floatEnvironment = nil |
| 872 | case .some(.some(let f)) where f == "sidewaystable" || f == "sideways": floatEnvironment = "sidewaystable" |
| 873 | case .some(.some("multicolumn")): floatEnvironment = "table*" |
| 874 | case .some(.some("t")): floatEnvironment = "table" |
| 875 | case .some(.some(let f)): floatEnvironment = f |
| 876 | case .none: floatEnvironment = caption.contains(where: { !$0.isWhitespace }) ? "table" : nil |
| 877 | } |
| 878 | let placement = affiliated.value("placement") ?? "[htbp]" |
| 879 | let center = affiliated.has("center") ? affiliated.value("center") != nil : true |
| 880 | let font = affiliated.value("font").map { $0 + "\n" } |
| 881 | let captionText: String? = caption.isEmpty ? nil : caption |
| 882 | var out = "" |
| 883 | if let floatEnvironment { |
| 884 | out = "\\begin{\(floatEnvironment)}\(placement)\n" + (above ? caption : "") + (center ? "\\centering\n" : "") + (font ?? "") |
| 885 | } else if captionText != nil { |
| 886 | out = (center ? "\\begin{center}\n" : "") + (above ? caption : "") + (font.map { center ? $0 : "{" + $0 } ?? "") |
| 887 | } else if center { |
| 888 | out = "\\begin{center}\n" + (font ?? "") |
| 889 | } else if let font { |
| 890 | out = "{" + font |
| 891 | } |
| 892 | out += table |
| 893 | if let floatEnvironment { |
| 894 | out += (above ? "" : "\n" + caption) + "\n\\end{\(floatEnvironment)}" |
| 895 | } else if captionText != nil { |
| 896 | out += (above ? "" : "\n" + caption) + (center ? "\n\\end{center}" : "") + (font != nil && !center ? "}" : "") |
| 897 | } else if center { |
| 898 | out += "\n\\end{center}" |
| 899 | } else if font != nil { |
| 900 | out += "}" |
| 901 | } |
| 902 | return out |
| 903 | } |
| 904 | |
| 905 | /// `org-latex--caption/label-string` for a float. |
| 906 | private func captionLabel(_ affiliated: Affiliated, type: String, prefix: String, srcBlock: Bool = false) throws -> String { |
| 907 | let nonfloat = (affiliated.attribute("float") == .some(nil) && !affiliated.caption.isEmpty) || (srcBlock && affiliated.value("float") == nil) |
| 908 | let label = affiliated.name.map { "\\label{\(prefix)\(reference("name:" + $0))}\n" } ?? "" |
| 909 | if let fromAttr = affiliated.value("caption"), fromAttr.contains(where: { !$0.isWhitespace }) { return fromAttr + "\n" } |
| 910 | guard !affiliated.caption.isEmpty else { return label } |
| 911 | let main = try inlineString(affiliated.caption.joined(separator: " ")) |
| 912 | let trimmedLabel = Self.trim(label) |
| 913 | return nonfloat ? "\\captionof{\(type)}{\(trimmedLabel)\(main)}\n" : "\\caption{\(trimmedLabel)\(main)}\n" |
| 914 | } |
| 915 | |
| 916 | // MARK: Blocks |
| 917 | |
| 918 | private func block(_ node: SyntaxNode, affiliated: Affiliated) throws -> String? { |
| 919 | var lines = node.text.components(separatedBy: "\n") |
| 920 | if lines.last == "" { lines.removeLast() } |
| 921 | guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil } |
| 922 | let type = m.1.lowercased() |
| 923 | let parameters = String(m.2) |
| 924 | let body = Array(lines.dropFirst().dropLast()) |
| 925 | let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) } |
| 926 | let text = unescaped.joined(separator: "\n") |
| 927 | switch type { |
| 928 | case "src": |
| 929 | guard text.contains(where: { !$0.isWhitespace }) else { return nil } |
| 930 | if affiliated.has("float") { throw Unsupported(reason: "Floating source blocks") } |
| 931 | let code = try formatCode(lines) |
| 932 | let verbatim = "\\begin{verbatim}\n\(code)\\end{verbatim}" |
| 933 | guard !affiliated.caption.isEmpty else { return verbatim } |
| 934 | return verbatim + "\n" + (try captionLabel(affiliated, type: "figure", prefix: "lst:", srcBlock: true)) |
| 935 | case "example": |
| 936 | guard text.contains(where: { !$0.isWhitespace }) else { return nil } |
| 937 | let environment = affiliated.value("environment") ?? "verbatim" |
| 938 | return try wrapLabel(affiliated, "\\begin{\(environment)}\n\(try formatCode(lines))\\end{\(environment)}") |
| 939 | case "quote": |
| 940 | let environment = affiliated.value("environment") ?? "quote" |
| 941 | return try wrapLabel(affiliated, "\\begin{\(environment)}\(affiliated.value("options") ?? "")\n\(Self.normalize(try blocks(text)))\\end{\(environment)}") |
| 942 | case "center": |
| 943 | return try wrapLabel(affiliated, "\\begin{center}\n\(Self.normalize(try blocks(text)))\\end{center}") |
| 944 | case "verse": |
| 945 | if !affiliated.attr.isEmpty { throw Unsupported(reason: "#+ATTR_LATEX on verse blocks") } |
| 946 | return try wrapLabel(affiliated, try verse(unescaped)) |
| 947 | case "export": |
| 948 | let backend = parameters.split(separator: " ").first.map { $0.uppercased() } ?? "" |
| 949 | guard backend == "LATEX" || backend == "TEX" else { return nil } |
| 950 | return try Self.removeIndentation(text + "\n") |
| 951 | case "comment": |
| 952 | return nil |
| 953 | default: |
| 954 | let caption = try captionLabel(affiliated, type: "figure", prefix: "") |
| 955 | if !caption.isEmpty { throw Unsupported(reason: "Captioned special blocks") } |
| 956 | return "\\begin{\(m.1)}\(affiliated.value("options") ?? "")\n" + Self.normalize(try blocks(text)) + "\\end{\(m.1)}" |
| 957 | } |
| 958 | } |
| 959 | |
| 960 | /// `org-export-format-code-default` for a src or example block's lines. |
| 961 | private func formatCode(_ lines: [String]) throws -> String { |
| 962 | guard let parsed = Coderef.block(lines) else { return "" } |
| 963 | var value = parsed.body.joined(separator: "\n") |
| 964 | if !value.isEmpty { value += "\n" } |
| 965 | let preserve = lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b.*\s-i\b/) != nil |
| 966 | var code = preserve ? value : try Self.removeIndentation(value) |
| 967 | if code.hasSuffix("\n") { code.removeLast() } |
| 968 | let (lines, refs) = Coderef.unravel(code.components(separatedBy: "\n"), format: parsed.switches.labelFormat) |
| 969 | let loc = parsed.switches.numberLines == nil ? nil : blockLoc(lines: lines) |
| 970 | guard loc != nil || (parsed.switches.retainLabels && !refs.isEmpty) else { return lines.joined(separator: "\n") + "\n" } |
| 971 | let width = loc.map { String($0 + lines.count).count } ?? 0 |
| 972 | let numberWidth = loc == nil ? 0 : width + 2 |
| 973 | let maxWidth = (lines.map(\.count).max() ?? 0) + numberWidth |
| 974 | return lines.enumerated().map { index, line in |
| 975 | var out = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1) " } ?? "" |
| 976 | out += line |
| 977 | if parsed.switches.retainLabels, let ref = refs[index + 1] { |
| 978 | out += String(repeating: " ", count: maxWidth + 6 - out.count) + "(\(ref))" |
| 979 | } |
| 980 | return out |
| 981 | }.joined(separator: "\n") + "\n" |
| 982 | } |
| 983 | |
| 984 | private var blockLocs: [Int?]? |
| 985 | private var blockIndex = 0 |
| 986 | |
| 987 | /// `org-export-get-loc` of the next numbered block. |
| 988 | private func blockLoc(lines: [String]) -> Int? { |
| 989 | if blockLocs == nil { |
| 990 | let blocks = Coderef.blocks(tree).compactMap(Coderef.block) |
| 991 | blockLocs = Coderef.locs(blocks) |
| 992 | } |
| 993 | _ = lines |
| 994 | defer { blockIndex += 1 } |
| 995 | return blockIndex < blockLocs!.count ? blockLocs![blockIndex] : nil |
| 996 | } |
| 997 | |
| 998 | /// `org-latex-verse-block` and the verse rules of `org-latex-plain-text`. |
| 999 | private func verse(_ lines: [String]) throws -> String { |
| 1000 | let text = lines.joined(separator: "\n") + "\n" |
| 1001 | // The contents are objects: paragraphs and the blank lines between them. |
| 1002 | let tree = OrgParser.parse(text, defaults: settings) |
| 1003 | let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] } |
| 1004 | guard nodes.allSatisfy({ $0.kind == .paragraph }), let firstNode = nodes.first else { throw Unsupported(reason: "Verse blocks with more than text") } |
| 1005 | let ns = text as NSString |
| 1006 | var raw: [Inline] = [.text(ns.substring(to: firstNode.range.lowerBound))] |
| 1007 | for (index, node) in nodes.enumerated() { |
| 1008 | raw += try inlineItems(node) |
| 1009 | let end = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : ns.length |
| 1010 | raw.append(.text(ns.substring(with: NSRange(location: node.range.upperBound, length: end - node.range.upperBound)))) |
| 1011 | } |
| 1012 | inVerse = true |
| 1013 | defer { inVerse = false } |
| 1014 | let items = Self.normalizeIndentation(Self.merge(raw), ignoreFirst: false) |
| 1015 | var contents = try transcode(items) |
| 1016 | while let c = contents.last, c.isWhitespace { contents.removeLast() } |
| 1017 | return Self.cleanLineBreaks("\\begin{verse}\n" + contents + "\n\\end{verse}") |
| 1018 | } |
| 1019 | |
| 1020 | private var inVerse = false |
| 1021 | |
| 1022 | // MARK: - Objects |
| 1023 | |
| 1024 | /// Inline content: text runs and objects with their own contents. |
| 1025 | indirect enum Inline { |
| 1026 | case text(String) |
| 1027 | case object(SyntaxNode, [Inline]) |
| 1028 | } |
| 1029 | |
| 1030 | /// The contents of `node` as `Inline`s, markers left out, a line break's newline taken in. |
| 1031 | func inlineItems(_ node: SyntaxNode, trimmed: Bool = false) throws -> [Inline] { |
| 1032 | var items: [Inline] = [] |
| 1033 | var skipNewline = false |
| 1034 | for element in node.elements { |
| 1035 | switch element { |
| 1036 | case .token(let token): |
| 1037 | switch token.kind { |
| 1038 | case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter: |
| 1039 | continue |
| 1040 | default: |
| 1041 | var text = token.text |
| 1042 | if skipNewline { |
| 1043 | let rest = text.drop { $0 == " " || $0 == "\t" } |
| 1044 | if rest.hasPrefix("\n") { text = String(rest.dropFirst()); skipNewline = false } else if !rest.isEmpty { skipNewline = false } else { text = "" } |
| 1045 | } |
| 1046 | if !text.isEmpty { items.append(.text(text)) } |
| 1047 | } |
| 1048 | case .node(let child): |
| 1049 | skipNewline = false |
| 1050 | switch child.kind { |
| 1051 | case .bold, .italic, .underline, .strikeThrough, .linkDescription: |
| 1052 | items.append(.object(child, try inlineItems(child))) |
| 1053 | case .link: |
| 1054 | items.append(.object(child, try child.firstChild(.linkDescription).map { try inlineItems($0) } ?? [])) |
| 1055 | case .superscript, .subscript: |
| 1056 | let text = child.text |
| 1057 | let braced = text.dropFirst().hasPrefix("{") |
| 1058 | if options.scripts == .off || (options.scripts == .braces && !braced) { |
| 1059 | items.append(.text(text)) |
| 1060 | } else if braced { |
| 1061 | items.append(.object(child, try inlineItems(child))) |
| 1062 | } else { |
| 1063 | items.append(.object(child, [.text(String(text.dropFirst()))])) |
| 1064 | } |
| 1065 | case .lineBreak where trimmed: |
| 1066 | // A table cell has no line ends. |
| 1067 | items.append(.text(child.text)) |
| 1068 | case .lineBreak: |
| 1069 | items.append(.object(child, [])) |
| 1070 | skipNewline = true |
| 1071 | default: |
| 1072 | items.append(.object(child, [])) |
| 1073 | } |
| 1074 | } |
| 1075 | } |
| 1076 | if trimmed { |
| 1077 | if case .text(let t) = items.first { items[0] = .text(String(t.drop { $0 == " " || $0 == "\t" })) } |
| 1078 | if case .text(let t) = items.last { items[items.count - 1] = .text(String(t.reversed().drop { $0 == " " || $0 == "\t" }.reversed())) } |
| 1079 | } |
| 1080 | return Self.merge(items) |
| 1081 | } |
| 1082 | |
| 1083 | /// Adjacent text runs joined. |
| 1084 | static func merge(_ items: [Inline]) -> [Inline] { |
| 1085 | var out: [Inline] = [] |
| 1086 | for item in items { |
| 1087 | if case .text(let t) = item, case .text(let previous)? = out.last { |
| 1088 | out[out.count - 1] = .text(previous + t) |
| 1089 | } else if case .text(let t) = item, t.isEmpty { |
| 1090 | continue |
| 1091 | } else { |
| 1092 | out.append(item) |
| 1093 | } |
| 1094 | } |
| 1095 | return out |
| 1096 | } |
| 1097 | |
| 1098 | /// `org-element-normalize-contents`: the common indentation of the lines taken away. |
| 1099 | static func normalizeIndentation(_ items: [Inline], ignoreFirst: Bool) -> [Inline] { |
| 1100 | var minimum = Int.max |
| 1101 | var zero = false |
| 1102 | func scan(_ items: [Inline], _ firstFlag: inout Bool) { |
| 1103 | for item in items { |
| 1104 | if zero { return } |
| 1105 | if firstFlag { |
| 1106 | firstFlag = false |
| 1107 | guard case .text(let t) = item, let m = t.firstMatch(of: /^([ \t]+)([^ \t\n]|\n|$)/) else { zero = true; return } |
| 1108 | if m.2 != "\n" { minimum = min(minimum, width(m.1)) } |
| 1109 | } |
| 1110 | switch item { |
| 1111 | case .text(let t): |
| 1112 | // Every line start, a blank line's next line included. |
| 1113 | var rest = t[...] |
| 1114 | while let newline = rest.firstIndex(of: "\n") { |
| 1115 | let after = rest[rest.index(after: newline)...] |
| 1116 | let indent = after.prefix { $0 == " " || $0 == "\t" } |
| 1117 | let next = after.dropFirst(indent.count).first |
| 1118 | if indent.isEmpty { |
| 1119 | if next != nil, next != "\n" { zero = true; return } |
| 1120 | } else if next != "\n" { |
| 1121 | minimum = min(minimum, width(indent)) |
| 1122 | } |
| 1123 | rest = after |
| 1124 | } |
| 1125 | case .object(let node, let children): |
| 1126 | if node.kind == .lineBreak { |
| 1127 | firstFlag = true |
| 1128 | } else if [.bold, .italic, .underline, .strikeThrough, .link, .linkDescription, .superscript, .subscript].contains(node.kind) { |
| 1129 | scan(children, &firstFlag) |
| 1130 | } |
| 1131 | } |
| 1132 | } |
| 1133 | } |
| 1134 | var first = !ignoreFirst |
| 1135 | scan(items, &first) |
| 1136 | guard !zero, minimum != Int.max, minimum > 0 else { return items } |
| 1137 | func strip(_ items: [Inline], _ firstFlag: inout Bool) -> [Inline] { |
| 1138 | items.map { item in |
| 1139 | switch item { |
| 1140 | case .text(var t): |
| 1141 | if firstFlag { |
| 1142 | firstFlag = false |
| 1143 | t = dedent(t, atStart: true, by: minimum) |
| 1144 | } else { |
| 1145 | t = dedent(t, atStart: false, by: minimum) |
| 1146 | } |
| 1147 | return .text(t) |
| 1148 | case .object(let node, let children): |
| 1149 | if firstFlag { firstFlag = false } |
| 1150 | if node.kind == .lineBreak { firstFlag = true; return item } |
| 1151 | var flag = false |
| 1152 | return .object(node, strip(children, &flag)) |
| 1153 | } |
| 1154 | } |
| 1155 | } |
| 1156 | var flag = !ignoreFirst |
| 1157 | return strip(items, &flag) |
| 1158 | } |
| 1159 | |
| 1160 | static func width(_ s: Substring) -> Int { s.reduce(0) { $0 + ($1 == "\t" ? 8 : 1) } } |
| 1161 | |
| 1162 | /// Indentation after each newline (and at the start) less `by` columns; blank lines lose theirs. |
| 1163 | static func dedent(_ t: String, atStart: Bool, by: Int) -> String { |
| 1164 | var lines = t.components(separatedBy: "\n") |
| 1165 | for i in lines.indices where i > 0 || atStart { |
| 1166 | let indent = lines[i].prefix { $0 == " " || $0 == "\t" } |
| 1167 | guard !indent.isEmpty else { continue } |
| 1168 | let rest = lines[i].dropFirst(indent.count) |
| 1169 | if rest.isEmpty && i < lines.count - 1 { |
| 1170 | lines[i] = "" |
| 1171 | } else if rest.isEmpty { |
| 1172 | lines[i] = String(repeating: " ", count: max(0, width(indent) - by)) |
| 1173 | } else { |
| 1174 | lines[i] = String(repeating: " ", count: max(0, width(indent) - by)) + rest |
| 1175 | } |
| 1176 | } |
| 1177 | return lines.joined(separator: "\n") |
| 1178 | } |
| 1179 | |
| 1180 | /// One line of Org text transcoded, for keywords and captions. |
| 1181 | func inlineString(_ text: String) throws -> String { |
| 1182 | let tree = OrgParser.parse(text, defaults: settings) |
| 1183 | guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) } |
| 1184 | let saved = exportSource |
| 1185 | exportSource = ExportSource(tree: tree, text: text) |
| 1186 | defer { exportSource = saved } |
| 1187 | return Self.trim(try transcode(try inlineItems(paragraph))) |
| 1188 | } |
| 1189 | |
| 1190 | /// `node`'s contents transcoded, as a heading's title is. |
| 1191 | private func inline(_ node: SyntaxNode, sectionTitle: Bool) throws -> String { |
| 1192 | let saved = inTitle |
| 1193 | inTitle = sectionTitle |
| 1194 | defer { inTitle = saved } |
| 1195 | return try transcode(try inlineItems(node)) |
| 1196 | } |
| 1197 | |
| 1198 | private var inTitle = false |
| 1199 | |
| 1200 | /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`), |
| 1201 | /// objects that export nothing taking their blanks with them unless they are needed. |
| 1202 | func transcode(_ items: [Inline]) throws -> String { |
| 1203 | var out = "" |
| 1204 | var index = 0 |
| 1205 | var dropBlanks = false |
| 1206 | while index < items.count { |
| 1207 | let item = items[index] |
| 1208 | switch item { |
| 1209 | case .text(var t): |
| 1210 | if dropBlanks { t = String(t.drop { $0 == " " || $0 == "\t" }) } |
| 1211 | dropBlanks = false |
| 1212 | out += plainText(t) |
| 1213 | index += 1 |
| 1214 | case .object(let node, let children): |
| 1215 | dropBlanks = false |
| 1216 | if let math = mathValue(node) { |
| 1217 | var values = [math] |
| 1218 | var next = index + 1 |
| 1219 | while next < items.count, case .object(let n, _) = items[next], let v = mathValue(n) { |
| 1220 | values.append(v) |
| 1221 | next += 1 |
| 1222 | } |
| 1223 | let joined = Self.trim(values.joined(separator: " ")) |
| 1224 | if !joined.isEmpty { out += "\\(\(joined)\\)" } |
| 1225 | index = next |
| 1226 | continue |
| 1227 | } |
| 1228 | if var result = try object(node, children) { |
| 1229 | // `org-timestamp-translate` keeps the blanks after the timestamp. |
| 1230 | if node.kind == .timestamp, index + 1 < items.count, case .text(let t) = items[index + 1] { |
| 1231 | result = result.dropLast() + String(t.prefix { $0 == " " || $0 == "\t" }) + "}" |
| 1232 | } |
| 1233 | out += result |
| 1234 | } else { |
| 1235 | // `org-export--keep-spaces`: blanks after a dropped object stay only |
| 1236 | // between text that has none. |
| 1237 | let previousBlank: Bool |
| 1238 | if index == 0 { |
| 1239 | previousBlank = true |
| 1240 | } else if case .text(let t) = items[index - 1] { |
| 1241 | previousBlank = t.last.map { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ?? false |
| 1242 | } else { |
| 1243 | previousBlank = false |
| 1244 | } |
| 1245 | dropBlanks = previousBlank |
| 1246 | } |
| 1247 | index += 1 |
| 1248 | } |
| 1249 | } |
| 1250 | return out |
| 1251 | } |
| 1252 | |
| 1253 | /// The LaTeX inside `\(…\)` for an object a math block takes, nil for others. |
| 1254 | private func mathValue(_ node: SyntaxNode) -> String? { |
| 1255 | switch node.kind { |
| 1256 | case .entity: |
| 1257 | let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "") |
| 1258 | guard let (latex, math) = OrgEntities.latex[name], math else { return nil } |
| 1259 | return latex |
| 1260 | case .latexFragment: |
| 1261 | guard options.tex else { return nil } |
| 1262 | let value = node.text |
| 1263 | if value.hasPrefix("\\(") { return String(value.dropFirst(2).dropLast(2)) } |
| 1264 | if value.hasPrefix("$"), !value.hasPrefix("$$") { return String(value.dropFirst().dropLast()) } |
| 1265 | return nil |
| 1266 | default: |
| 1267 | return nil |
| 1268 | } |
| 1269 | } |
| 1270 | |
| 1271 | private func object(_ node: SyntaxNode, _ children: [Inline]) throws -> String? { |
| 1272 | switch node.kind { |
| 1273 | case .bold: return "\\textbf{\(try transcode(children))}" |
| 1274 | case .italic: return "\\emph{\(try transcode(children))}" |
| 1275 | case .underline: return inTitle ? "\\underline{\(try transcode(children))}" : "\\uline{\(try transcode(children))}" |
| 1276 | case .strikeThrough: return "\\sout{\(try transcode(children))}" |
| 1277 | case .verbatim, .code: |
| 1278 | return Self.texttt(String(node.text.dropFirst().dropLast())) |
| 1279 | case .link: return try link(node, children) |
| 1280 | case .linkDescription: return try transcode(children) |
| 1281 | case .timestamp: return try timestamp(node.text) |
| 1282 | case .footnoteReference: return try footnote(node) |
| 1283 | case .entity: |
| 1284 | let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "") |
| 1285 | guard let (latex, _) = OrgEntities.latex[name] else { throw Unsupported(reason: "Unknown entity \(node.text)") } |
| 1286 | return latex |
| 1287 | case .superscript: return "\\textsuperscript{\(try transcode(children))}" |
| 1288 | case .subscript: return "\\textsubscript{\(try transcode(children))}" |
| 1289 | case .lineBreak: return "\\\\\n" |
| 1290 | case .latexFragment: return options.tex ? node.text : nil |
| 1291 | case .statisticsCookie: return node.text.replacingOccurrences(of: "%", with: "\\%") |
| 1292 | case .exportSnippet: |
| 1293 | let backend = node.tokens.first?.text.dropFirst(2).dropLast() ?? "" |
| 1294 | guard backend == "latex" else { return nil } |
| 1295 | return node.tokens.filter { $0.kind != .marker }.map(\.text).joined() |
| 1296 | case .target: |
| 1297 | let name = String(node.text.dropFirst(2).dropLast(2)) |
| 1298 | return "\\label{\(reference("target:" + name))}" |
| 1299 | case .macro: |
| 1300 | guard case .some(let value) = exportSource.resultsMacro(node) else { return nil } |
| 1301 | return try value.map(inlineString) |
| 1302 | default: |
| 1303 | throw Unsupported(reason: "\(node.kind)") |
| 1304 | } |
| 1305 | } |
| 1306 | |
| 1307 | // MARK: Plain text |
| 1308 | |
| 1309 | /// `org-latex-plain-text`. |
| 1310 | func plainText(_ text: String) -> String { |
| 1311 | let special = options.specialStrings |
| 1312 | var out = "" |
| 1313 | let chars = Array(text) |
| 1314 | var i = 0 |
| 1315 | while i < chars.count { |
| 1316 | let c = chars[i] |
| 1317 | switch c { |
| 1318 | case "%", "$", "#", "&", "{", "}", "_": |
| 1319 | out += "\\" + String(c) |
| 1320 | case "~": out += "\\textasciitilde{}" |
| 1321 | case "^": out += "\\^{}" |
| 1322 | case "\\": |
| 1323 | if special { |
| 1324 | if i + 1 < chars.count { |
| 1325 | if chars[i + 1] == "-" { |
| 1326 | out += "\\" |
| 1327 | } else { |
| 1328 | out += "$\\backslash$" + String(chars[i + 1]) |
| 1329 | i += 1 |
| 1330 | } |
| 1331 | } else { |
| 1332 | out += "$\\backslash$" |
| 1333 | } |
| 1334 | } else { |
| 1335 | out += "$\\backslash$" |
| 1336 | } |
| 1337 | default: |
| 1338 | out.append(c) |
| 1339 | } |
| 1340 | i += 1 |
| 1341 | } |
| 1342 | out = Self.texLogos(out) |
| 1343 | if special { out = out.replacingOccurrences(of: "...", with: "\\ldots{}") } |
| 1344 | out = out.replacing(#/(?m)^(\s*)\[/#) { $0.1 + "{[}" } |
| 1345 | if inVerse { |
| 1346 | out = out.replacing(#/(?:[ \t]*\\\\)?[ \t]*\n/#, with: "\\\\\n") |
| 1347 | out = out.replacing(#/(\\\\\n)(?:(?m:^)[ \t]*\\\\\n)+/#, with: "\n\n") |
| 1348 | out = out.replacing(#/(?m)^[ \t]+/#) { "\\hspace*{\($0.output.count)\\fontdimen2\\font}" } |
| 1349 | } |
| 1350 | return out |
| 1351 | } |
| 1352 | |
| 1353 | /// `LaTeX` and `TeX` as words, as their commands. |
| 1354 | static func texLogos(_ s: String) -> String { |
| 1355 | guard s.contains("TeX") else { return s } |
| 1356 | let chars = Array(s) |
| 1357 | var out = "" |
| 1358 | var i = 0 |
| 1359 | // Word constituents in Org's syntax table, the apostrophe among them. |
| 1360 | func isWord(_ c: Character) -> Bool { c.isLetter || c.isNumber || c == "'" } |
| 1361 | outer: while i < chars.count { |
| 1362 | if i == 0 || !isWord(chars[i - 1]) { |
| 1363 | for word in ["LaTeX", "TeX"] { |
| 1364 | let w = Array(word) |
| 1365 | if i + w.count <= chars.count, Array(chars[i..<(i + w.count)]) == w, i + w.count == chars.count || !isWord(chars[i + w.count]) { |
| 1366 | out += "\\" + word + "{}" |
| 1367 | i += w.count |
| 1368 | continue outer |
| 1369 | } |
| 1370 | } |
| 1371 | } |
| 1372 | out.append(chars[i]) |
| 1373 | i += 1 |
| 1374 | } |
| 1375 | return out |
| 1376 | } |
| 1377 | |
| 1378 | // MARK: Timestamps |
| 1379 | |
| 1380 | /// `org-latex-timestamp`: `org-element-timestamp-interpreter`'s text in `\textit`, with the |
| 1381 | /// blanks after the timestamp. |
| 1382 | private func timestamp(_ text: String) throws -> String? { |
| 1383 | guard let stamp = Timestamp.parse(text) else { throw Unsupported(reason: "Timestamp \(text)") } |
| 1384 | let open = stamp.active ? "<" : "[" |
| 1385 | let close = stamp.active ? ">" : "]" |
| 1386 | func date(_ p: Timestamp.Point, time: Bool) -> String { |
| 1387 | var components = DateComponents(year: p.year, month: p.month, day: p.day) |
| 1388 | components.calendar = Calendar(identifier: .gregorian) |
| 1389 | let weekday = components.calendar!.date(from: components).map { components.calendar!.component(.weekday, from: $0) } ?? 1 |
| 1390 | let name = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][weekday - 1] |
| 1391 | var s = String(format: "%04d-%02d-%02d ", p.year, p.month, p.day) + name |
| 1392 | if time, let h = p.hour, let m = p.minute { s += String(format: " %02d:%02d", h, m) } |
| 1393 | return s |
| 1394 | } |
| 1395 | var suffix = "" |
| 1396 | if let r = stamp.repeater { |
| 1397 | suffix += " " + r.kind.rawValue + "\(r.interval.value)\(r.interval.unit.rawValue)" |
| 1398 | if let d = r.habitDeadline { suffix += "/\(d.value)\(d.unit.rawValue)" } |
| 1399 | } |
| 1400 | if let w = stamp.warning { suffix += " " + (w.firstOccurrenceOnly ? "--" : "-") + "\(w.interval.value)\(w.interval.unit.rawValue)" } |
| 1401 | var out = open + date(stamp.start, time: true) |
| 1402 | let dateRange = text.contains(">--<") || text.contains("]--[") |
| 1403 | if let end = stamp.end { |
| 1404 | if dateRange { |
| 1405 | out += suffix + close + "--" + open + date(end, time: true) + suffix + close |
| 1406 | } else { |
| 1407 | if let h = end.hour, let m = end.minute, h != stamp.start.hour || m != stamp.start.minute { |
| 1408 | out += String(format: "-%02d:%02d", h, m) |
| 1409 | } |
| 1410 | out += suffix + close |
| 1411 | } |
| 1412 | } else { |
| 1413 | out += suffix + close |
| 1414 | } |
| 1415 | guard options.items["<"] ?? "t" == "t" else { return nil } |
| 1416 | return "\\textit{\(plainText(out))}" |
| 1417 | } |
| 1418 | |
| 1419 | // MARK: Links |
| 1420 | |
| 1421 | private func linkTarget(_ node: SyntaxNode) -> (type: String, path: String) { |
| 1422 | var raw = node.tokens.first { $0.kind == .linkPath }?.text ?? node.text |
| 1423 | if node.tokens.first(where: { $0.kind == .linkPath }) == nil, raw.hasPrefix("<"), raw.hasSuffix(">") { |
| 1424 | raw = String(raw.dropFirst().dropLast()) |
| 1425 | } |
| 1426 | if raw.hasPrefix("#") { return ("custom-id", String(raw.dropFirst())) } |
| 1427 | if raw.hasPrefix("(") && raw.hasSuffix(")") { return ("coderef", String(raw.dropFirst().dropLast())) } |
| 1428 | if raw.hasPrefix("./") || raw.hasPrefix("../") || raw.hasPrefix("/") || raw.hasPrefix("~") { return ("file", raw) } |
| 1429 | if let m = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/), Self.linkTypes.contains(m.1.lowercased()) { |
| 1430 | let type = m.1.lowercased() |
| 1431 | var path = String(m.2) |
| 1432 | if type == "file", path.hasPrefix("//") == false, let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) } |
| 1433 | return (type, path) |
| 1434 | } |
| 1435 | return ("fuzzy", raw) |
| 1436 | } |
| 1437 | |
| 1438 | /// `org-link-parameters` under `emacs -Q` with ox-latex loaded. |
| 1439 | static let linkTypes: Set<String> = ["attachment", "id", "file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"] |
| 1440 | |
| 1441 | private func isImage(_ node: SyntaxNode) -> Bool { |
| 1442 | guard node.kind == .link, node.firstChild(.linkDescription) == nil else { return false } |
| 1443 | let (type, path) = linkTarget(node) |
| 1444 | guard type == "file" || type == "https" else { return false } |
| 1445 | let ext = (path as NSString).pathExtension.lowercased() |
| 1446 | let image = type == "file" ? ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"] : ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"] |
| 1447 | return image.contains(ext) && path.lowercased().hasSuffix("." + ext) |
| 1448 | } |
| 1449 | |
| 1450 | /// The image link of a paragraph holding only it and blanks. |
| 1451 | private func soleImage(_ items: [Inline]) -> SyntaxNode? { |
| 1452 | var image: SyntaxNode? |
| 1453 | for item in items { |
| 1454 | switch item { |
| 1455 | case .text(let t): if t.contains(where: { !$0.isWhitespace }) { return nil } |
| 1456 | case .object(let node, _): |
| 1457 | guard image == nil, isImage(node) else { return nil } |
| 1458 | image = node |
| 1459 | } |
| 1460 | } |
| 1461 | return image |
| 1462 | } |
| 1463 | |
| 1464 | private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? { |
| 1465 | let (type, path) = linkTarget(node) |
| 1466 | var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children) |
| 1467 | if description == "" { description = nil } |
| 1468 | if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true { |
| 1469 | throw Unsupported(reason: "Links in link descriptions") |
| 1470 | } |
| 1471 | if let d = node.firstChild(.linkDescription)?.text, d.firstMatch(of: /^(?:[A-Za-z]+:\S+|<[^>]+>)$/) != nil { |
| 1472 | throw Unsupported(reason: "Images as link descriptions") |
| 1473 | } |
| 1474 | if isImage(node) { return try inlineImage(node, affiliated: currentAffiliated ?? Affiliated(), alone: false) } |
| 1475 | switch type { |
| 1476 | case "custom-id", "fuzzy", "id": |
| 1477 | let label: String |
| 1478 | let numberedHeading: Bool |
| 1479 | var title: String? |
| 1480 | if type == "fuzzy", !path.hasPrefix("*"), let found = target(path).map({ reference("target:" + $0) }) ?? namedElement(path) { |
| 1481 | return description.map { "\\hyperref[\(found)]{\($0)}" } ?? "\\ref{\(found)}" |
| 1482 | } |
| 1483 | guard let heading = try resolveHeading(type: type, path: path) else { |
| 1484 | throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"") |
| 1485 | } |
| 1486 | label = "sec:" + reference("heading@\(heading.headingRange.lowerBound)") |
| 1487 | numberedHeading = numbered && (num.map { heading.level + levelOffset <= $0 } ?? true) |
| 1488 | if description == nil, numberedHeading { return "\\ref{\(label)}" } |
| 1489 | if description == nil { |
| 1490 | let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound } |
| 1491 | title = try node?.firstChild(.title).map { try Self.trim(inline($0, sectionTitle: false)) } ?? "" |
| 1492 | } |
| 1493 | return "\\hyperref[\(label)]{\(description ?? title ?? "")}" |
| 1494 | case "coderef": |
| 1495 | guard let resolved = Coderef.resolve(path, in: tree) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") } |
| 1496 | // `org-export-get-coderef-format` on the transcoded description, then `format`. |
| 1497 | var format = description ?? "%s" |
| 1498 | if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") } |
| 1499 | return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%") |
| 1500 | case "file": |
| 1501 | if path.hasPrefix("~") { throw Unsupported(reason: "File links under ~") } |
| 1502 | let uri = path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path |
| 1503 | let protected = Self.protect(uri) |
| 1504 | return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}" |
| 1505 | case "http", "https", "ftp", "mailto", "news": |
| 1506 | let protected = Self.protect(type + ":" + path) |
| 1507 | return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}" |
| 1508 | default: |
| 1509 | throw Unsupported(reason: "\(type): links") |
| 1510 | } |
| 1511 | } |
| 1512 | |
| 1513 | /// Words of a fuzzy link or a title, as `org-export-search-cells` compares them. |
| 1514 | static func words(_ s: String) -> [String] { |
| 1515 | s.uppercased().split(whereSeparator: \.isWhitespace).map(String.init) |
| 1516 | } |
| 1517 | |
| 1518 | /// The `<<target>>` a fuzzy link names. |
| 1519 | private func target(_ path: String) -> String? { |
| 1520 | let search = Self.words(path) |
| 1521 | return tree.root.descendants().first { $0.kind == .target && Self.words(String($0.text.dropFirst(2).dropLast(2))) == search } |
| 1522 | .map { String($0.text.dropFirst(2).dropLast(2)) } |
| 1523 | } |
| 1524 | |
| 1525 | /// The label of the element whose `#+NAME` a fuzzy link names, as the element writes it. |
| 1526 | private func namedElement(_ path: String) -> String? { |
| 1527 | let search = path.split(whereSeparator: \.isWhitespace).map(String.init) |
| 1528 | for node in tree.root.descendants() where node.kind == .affiliatedKeyword { |
| 1529 | guard let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { continue } |
| 1530 | let name = String(m.1) |
| 1531 | let words = name.split(whereSeparator: \.isWhitespace).map(String.init) |
| 1532 | guard words == search || words == search.map({ $0.uppercased() }), let parent = node.parent else { continue } |
| 1533 | let siblings = parent.children |
| 1534 | guard let index = siblings.firstIndex(where: { $0.range == node.range }) else { continue } |
| 1535 | let keywords = siblings[index...].prefix { $0.kind == .affiliatedKeyword } |
| 1536 | guard let element = siblings[index...].first(where: { $0.kind != .affiliatedKeyword }) else { continue } |
| 1537 | let captioned = keywords.contains { $0.text.firstMatch(of: /^[ \t]*#\+(?i:caption)/) != nil } |
| 1538 | let prefix: String |
| 1539 | switch element.kind { |
| 1540 | case .table: prefix = "tab:" |
| 1541 | case .block where blockType(element) == "src": prefix = "lst:" |
| 1542 | case .paragraph where captioned: prefix = "fig:" |
| 1543 | default: prefix = "" |
| 1544 | } |
| 1545 | return prefix + reference("name:" + name) |
| 1546 | } |
| 1547 | return nil |
| 1548 | } |
| 1549 | |
| 1550 | /// The heading a link goes to: by `CUSTOM_ID`, `ID` or title. |
| 1551 | private func resolveHeading(type: String, path: String) throws -> HeadingInfo? { |
| 1552 | switch type { |
| 1553 | case "custom-id": |
| 1554 | return model.headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } } |
| 1555 | case "id": |
| 1556 | return model.headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } } |
| 1557 | default: |
| 1558 | let search = Self.words(path.hasPrefix("*") ? String(path.dropFirst()) : path) |
| 1559 | return model.headings.first { heading in |
| 1560 | let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound } |
| 1561 | let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ") |
| 1562 | return Self.words(raw) == search |
| 1563 | } |
| 1564 | } |
| 1565 | } |
| 1566 | |
| 1567 | /// `org-latex--inline-image`. |
| 1568 | private func inlineImage(_ node: SyntaxNode, affiliated: Affiliated, alone: Bool) throws -> String { |
| 1569 | let (type, path) = linkTarget(node) |
| 1570 | if type != "file" { throw Unsupported(reason: "Remote images") } |
| 1571 | if path.hasPrefix("~") || path.hasPrefix("/") { throw Unsupported(reason: "Images with absolute paths") } |
| 1572 | let ext = (path as NSString).pathExtension.lowercased() |
| 1573 | let caption = try captionLabel(affiliated, type: "figure", prefix: !affiliated.caption.isEmpty ? "fig:" : "") |
| 1574 | enum Float: Equatable { case none, nonfloat, figure, wrap, sideways, multicolumn, env(String) } |
| 1575 | var float: Float |
| 1576 | let attrFloat = affiliated.attribute("float") |
| 1577 | if !alone { |
| 1578 | float = .none |
| 1579 | } else { |
| 1580 | switch attrFloat { |
| 1581 | case .some(.some("wrap")): float = .wrap |
| 1582 | case .some(.some("sideways")): float = .sideways |
| 1583 | case .some(.some("multicolumn")): float = .multicolumn |
| 1584 | case .some(.some("t")): float = .figure |
| 1585 | case .some(nil): float = .nonfloat |
| 1586 | case .some(.some(let f)): float = .env(f) |
| 1587 | case .none: float = !affiliated.caption.isEmpty || affiliated.value("caption") != nil ? .figure : .nonfloat |
| 1588 | } |
| 1589 | } |
| 1590 | let placement: String |
| 1591 | if let p = affiliated.value("placement") { |
| 1592 | placement = p |
| 1593 | } else if float == .wrap { |
| 1594 | placement = "{l}{0.5\\textwidth}" |
| 1595 | } else if float == .figure { |
| 1596 | placement = "[htbp]" |
| 1597 | } else { |
| 1598 | placement = "" |
| 1599 | } |
| 1600 | let center = affiliated.has("center") ? affiliated.value("center") != nil : true |
| 1601 | let scale = float == .wrap ? "" : affiliated.value("scale") ?? "" |
| 1602 | let width: String = !scale.isEmpty ? "" : affiliated.value("width") ?? (affiliated.value("height") != nil ? "" : float == .wrap ? "0.48\\textwidth" : ".9\\linewidth") |
| 1603 | let height: String = !scale.isEmpty ? "" : affiliated.value("height") ?? "" |
| 1604 | var options = affiliated.value("options") ?? "" |
| 1605 | if let m = options.wholeMatch(of: /\[(.*)\]/) { options = String(m.1) } |
| 1606 | if ext == "tikz" || ext == "pgf" { throw Unsupported(reason: "TikZ images") } |
| 1607 | if affiliated.value("comment-include") != nil { throw Unsupported(reason: ":comment-include") } |
| 1608 | if !scale.isEmpty { |
| 1609 | options += ",scale=" + scale |
| 1610 | } else { |
| 1611 | if !width.isEmpty { options += ",width=" + width } |
| 1612 | if !height.isEmpty { options += ",height=" + height } |
| 1613 | } |
| 1614 | let optionString = options.isEmpty ? "" : options.hasPrefix(",") ? "[\(options.dropFirst())]" : "[\(options)]" |
| 1615 | var imagePath = path |
| 1616 | if ext == "svg", imagePath.contains(where: { !$0.isASCII }) { imagePath = "\\detokenize{\(imagePath)}" } |
| 1617 | var code = "\\includegraphics\(optionString){\(imagePath)}" |
| 1618 | if ext == "svg" { |
| 1619 | code = "\\includesvg" + code.dropFirst("\\includegraphics".count) |
| 1620 | code = code.replacingOccurrences(of: ".svg}", with: "}") |
| 1621 | } |
| 1622 | let above = false |
| 1623 | switch float { |
| 1624 | case .env(let env): |
| 1625 | return "\\begin{\(env)}\(placement)\n\(above ? caption : "")\(center ? "\\centering" : "")\n\(code)\n\(above ? "" : caption)\\end{\(env)}" |
| 1626 | case .wrap: |
| 1627 | return "\\begin{wrapfigure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{wrapfigure}" |
| 1628 | case .sideways: |
| 1629 | return "\\begin{sidewaysfigure}\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{sidewaysfigure}" |
| 1630 | case .multicolumn: |
| 1631 | return "\\begin{figure*}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure*}" |
| 1632 | case .figure: |
| 1633 | return "\\begin{figure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure}" |
| 1634 | case .none, .nonfloat: |
| 1635 | if center { return "\\begin{center}\n\(code)\n\(caption)\\end{center}" } |
| 1636 | return code |
| 1637 | } |
| 1638 | } |
| 1639 | |
| 1640 | // MARK: Footnotes |
| 1641 | |
| 1642 | private var footnoteReferences: [String: Int] = [:] |
| 1643 | private var footnotesSeen: Set<String> = [] |
| 1644 | private var definitions: [String: String] = [:] |
| 1645 | private var anonymous = 0 |
| 1646 | |
| 1647 | /// Footnote definitions, and how many references each label has. |
| 1648 | private func countFootnotes() throws { |
| 1649 | for node in tree.root.descendants() { |
| 1650 | if node.kind == .footnoteDefinition, let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) { |
| 1651 | // A definition goes on to the next one, a heading or two blank lines. |
| 1652 | if let parent = node.parent, let index = parent.children.firstIndex(where: { $0.range == node.range }), index + 1 < parent.children.count { |
| 1653 | let next = parent.children[index + 1] |
| 1654 | if next.kind != .footnoteDefinition, next.kind != .section, blankLines(from: node.range.lowerBound, to: next.range.lowerBound) < 2 { |
| 1655 | throw Unsupported(reason: "Footnote definitions of several paragraphs") |
| 1656 | } |
| 1657 | } |
| 1658 | definitions[String(m.1)] = String(node.text[m.range.upperBound...]) |
| 1659 | } |
| 1660 | if node.kind == .footnoteReference, let m = node.text.firstMatch(of: /^\[fn:([^:\]]+)/) { |
| 1661 | if node.parent.map({ Self.excluded($0, by: self) }) == true { continue } |
| 1662 | footnoteReferences[String(m.1), default: 0] += 1 |
| 1663 | } |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | /// Whether `node` is under a section the export leaves out. |
| 1668 | private static func excluded(_ node: SyntaxNode, by renderer: LaTeXRenderer) -> Bool { |
| 1669 | var current: SyntaxNode? = node |
| 1670 | while let n = current { |
| 1671 | if n.kind == .section, let heading = n.firstChild(.heading), |
| 1672 | HTMLRenderer.sectionExport(heading, options: renderer.options, selected: renderer.selected) != .all { return true } |
| 1673 | current = n.parent |
| 1674 | } |
| 1675 | return false |
| 1676 | } |
| 1677 | |
| 1678 | /// `org-latex-footnote-reference`. |
| 1679 | private func footnote(_ node: SyntaxNode) throws -> String { |
| 1680 | guard let m = node.text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { throw Unsupported(reason: "Footnote \(node.text)") } |
| 1681 | let label = String(m.1) |
| 1682 | if inFootnote { throw Unsupported(reason: "Footnotes inside footnotes") } |
| 1683 | var separator = "" |
| 1684 | if let previous = previousSibling(node), previous.kind == .footnoteReference { separator = "\\textsuperscript{,}\\," } |
| 1685 | if let inline = m.2 { |
| 1686 | if !label.isEmpty { |
| 1687 | if footnotesSeen.contains(label) { return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}" } |
| 1688 | footnotesSeen.insert(label) |
| 1689 | } |
| 1690 | inFootnote = true |
| 1691 | defer { inFootnote = false } |
| 1692 | let content = try inlineString(String(inline)) |
| 1693 | let labelText = !label.isEmpty && (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : "" |
| 1694 | return separator + "\\footnote{\(content)\(labelText)}" |
| 1695 | } |
| 1696 | guard !label.isEmpty, let definition = definitions[label] else { throw Unsupported(reason: "Definition not found for footnote \(label)") } |
| 1697 | if footnotesSeen.contains(label) { |
| 1698 | return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}" |
| 1699 | } |
| 1700 | footnotesSeen.insert(label) |
| 1701 | inFootnote = true |
| 1702 | defer { inFootnote = false } |
| 1703 | let content = Self.trim(try footnoteBody(definition)) |
| 1704 | let labelText = (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : "" |
| 1705 | return separator + "\\footnote{\(content)\(labelText)}" |
| 1706 | } |
| 1707 | |
| 1708 | private var inFootnote = false |
| 1709 | |
| 1710 | /// A definition's text transcoded, its first paragraph's first line left as it is. |
| 1711 | private func footnoteBody(_ text: String) throws -> String { |
| 1712 | let tree = OrgParser.parse(text, defaults: settings) |
| 1713 | let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] } |
| 1714 | if nodes.count == 1, nodes[0].kind == .paragraph { |
| 1715 | return try paragraph(nodes[0], affiliated: Affiliated(), ignoreFirst: true) |
| 1716 | } |
| 1717 | return try blocks(text) |
| 1718 | } |
| 1719 | |
| 1720 | /// The object or text before `node` in its parent. |
| 1721 | private func previousSibling(_ node: SyntaxNode) -> SyntaxNode? { |
| 1722 | guard let parent = node.parent else { return nil } |
| 1723 | var previous: SyntaxNode.Element? |
| 1724 | for element in parent.elements { |
| 1725 | if case .node(let n) = element, n.range == node.range { |
| 1726 | if case .node(let p)? = previous { return p } |
| 1727 | return nil |
| 1728 | } |
| 1729 | previous = element |
| 1730 | } |
| 1731 | return nil |
| 1732 | } |
| 1733 | } |