Sources/OrgstarCLI/ExportCommand.swift
151 lines · 8510 bytes
1import Foundation
2import OrgConfig
3import OrgCore
4
5/// `orgstar export` and `orgstar tangle`.
6@MainActor
7enum ExportCommand {
8 static let help = """
9 Usage: orgstar export <file> --to <format> [-o <path>]
10
11 Exports the whole file with the settings of config.toml and the file's own, as File ▸ Export
12 does. Formats: html, md, latex, txt, odt, reveal, and pdf, which runs the LaTeX export
13 through latexmk or pdflatex, as Emacs does (the app's PDF export doesn't need TeX).
14
15 The output goes beside the file, named by #+EXPORT_FILE_NAME or the file's name, unless
16 -o names a path; -o - writes it to standard output.
17
18 Options:
19 --to <format> html, md, pdf, latex, odt, txt or reveal
20 -o, --output <path> where to write the export
21 """
22
23 static let tangleHelp = """
24 Usage: orgstar tangle <file>
25
26 Writes the file's code blocks with :tangle to their files, as org-babel-tangle does: a file
27 whose contents haven't changed is left alone, :mkdirp makes its folder, :tangle-mode sets
28 its mode.
29 """
30
31 static let extensions = ["html": "html", "md": "md", "pdf": "pdf", "latex": "tex", "odt": "odt", "txt": "txt", "reveal": "html"]
32
33 static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
34 let arguments = try Arguments(words, command: "export", flags: [], options: ["--to", "--output"], aliases: ["-o": "--output"])
35 try arguments.expect(1, 1, "export")
36 guard let format = arguments.value("--to") else { throw Failure(.usage, "export: --to is html, md, pdf, latex, odt, txt or reveal") }
37 guard let ext = extensions[format] else { throw Failure(.usage, "export: unknown format \(format); use html, md, pdf, latex, odt, txt or reveal") }
38 let host = workspace.host
39 let path = host.absolute(arguments.positional[0])
40 let text = try workspace.text(path)
41 let url = URL(fileURLWithPath: path)
42 let name = url.lastPathComponent
43 let settings = workspace.settings(for: text, path: path)
44 let language = OrgPreferences.exportLanguage(workspace.defaults)
45 let base = url.deletingPathExtension().lastPathComponent
46 let data: Data
47 do {
48 switch format {
49 case "html":
50 data = Data(HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, language: language).utf8)
51 case "md":
52 data = Data(MarkdownExport.document(text, settings: settings, path: path, bodyOnly: false).utf8)
53 case "latex":
54 data = Data(try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: false, author: NSFullUserName(), language: language, file: true).utf8)
55 case "txt":
56 data = Data(try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: false, author: NSFullUserName(), language: language, file: true).utf8)
57 case "odt":
58 data = try ODTExport.document(text, settings: settings, path: path, author: NSFullUserName(), language: language)
59 case "reveal":
60 let library = bundledScripts(host).map { $0.url(forResource: "Reveal", withExtension: nil) } ?? nil
61 let mathJax = bundledScripts(host).map { $0.url(forResource: "tex-svg-full", withExtension: "js", subdirectory: "MathJax") } ?? nil
62 data = Data(RevealExport.document(text, fallbackTitle: base, settings: settings, path: path, language: language, library: library, mathJax: mathJax).utf8)
63 default:
64 let latex = try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: false, author: NSFullUserName(), language: language, file: true)
65 data = try pdf(latex: latex, name: base, directory: url.deletingLastPathComponent(), host)
66 }
67 } catch let failure as Failure {
68 throw failure
69 } catch let error as LaTeXExport.Unsupported {
70 throw Failure(.failure, "Can't export \(name) to \(format == "txt" ? "plain text" : "LaTeX"): \(error.reason)")
71 } catch {
72 throw Failure(.failure, "Can't export \(name): \(error.localizedDescription)")
73 }
74 if arguments.value("--output") == "-" {
75 host.output(data)
76 return
77 }
78 let target = arguments.value("--output").map { URL(fileURLWithPath: host.absolute($0)) }
79 ?? ExportScope.output(for: url, name: ExportScope.fileName(text, settings: settings), extension: ext)
80 do {
81 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
82 try data.write(to: target, options: .atomic)
83 } catch {
84 throw Failure(.failure, "Can't write \(target.path): \(error.localizedDescription)")
85 }
86 host.print("Exported to \(target.path)")
87 }
88
89 /// The app's bundle of scripts (reveal.js, MathJax): beside this executable in a build
90 /// folder, or in the app's resources.
91 static func bundledScripts(_ host: Host) -> Bundle? {
92 let folder = host.executable.deletingLastPathComponent()
93 let candidates = [folder, folder.deletingLastPathComponent().appendingPathComponent("Resources")]
94 return candidates.lazy.compactMap { Bundle(url: $0.appendingPathComponent("Orgstar_OrgMathJax.bundle")) }.first
95 }
96
97 /// `org-latex-export-to-pdf`: `latex` compiled in a temporary folder, run from `directory`
98 /// so that relative image paths resolve, by latexmk or else pdflatex three times.
99 static func pdf(latex: String, name: String, directory: URL, _ host: Host) throws -> Data {
100 let path = (host.environment["PATH"] ?? "/usr/bin:/bin") + ":/Library/TeX/texbin"
101 func find(_ program: String) -> String? {
102 path.split(separator: ":").map { "\($0)/\(program)" }.first { FileManager.default.isExecutableFile(atPath: $0) }
103 }
104 let work = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-pdf-\(UUID().uuidString)")
105 try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
106 defer { try? FileManager.default.removeItem(at: work) }
107 let tex = work.appendingPathComponent(name + ".tex")
108 try latex.write(to: tex, atomically: true, encoding: .utf8)
109 let runs: [(String, [String])]
110 if let latexmk = find("latexmk") {
111 runs = [(latexmk, ["-f", "-pdf", "-interaction=nonstopmode", "-output-directory=\(work.path)", tex.path])]
112 } else if let pdflatex = find("pdflatex") {
113 runs = Array(repeating: (pdflatex, ["-interaction", "nonstopmode", "-output-directory", work.path, tex.path]), count: 3)
114 } else {
115 throw Failure(.failure, "PDF export from the command line needs TeX (latexmk or pdflatex), such as MacTeX. Export to PDF in orgstar, which doesn't.")
116 }
117 for (program, arguments) in runs {
118 let process = Process()
119 process.executableURL = URL(fileURLWithPath: program)
120 process.arguments = arguments
121 process.currentDirectoryURL = directory
122 process.standardOutput = FileHandle.nullDevice
123 process.standardError = FileHandle.nullDevice
124 try process.run()
125 process.waitUntilExit()
126 }
127 guard let data = FileManager.default.contents(atPath: work.appendingPathComponent(name + ".pdf").path) else {
128 throw Failure(.failure, "TeX made no PDF from \(name).tex; export to LaTeX and run it to see why.")
129 }
130 return data
131 }
132
133 static func tangle(_ words: [String], _ workspace: Workspace) throws(Failure) {
134 let arguments = try Arguments(words, command: "tangle", flags: [])
135 try arguments.expect(1, 1, "tangle")
136 let path = workspace.host.absolute(arguments.positional[0])
137 let text = try workspace.text(path)
138 let tree = OrgParser.parse(text, defaults: workspace.settings(for: text, path: path))
139 switch Tangle.run(text: text, path: path, scope: .all, tree: tree) {
140 case .failure(.message(let message)):
141 throw Failure(.failure, message)
142 case .success(let output):
143 do {
144 try TangleWriter.write(output, source: path)
145 } catch {
146 throw Failure(.failure, error.message)
147 }
148 workspace.host.print(TangleWriter.message(output, source: path))
149 }
150 }
151}