Sources/OrgApp/EmacsRunner.swift
141 lines · 7451 bytes
1#if os(macOS)
2import Foundation
3
4/// Runs `emacs --batch` for what the native code hands over, such as tables outside the
5/// native formula domain.
6public enum EmacsRunner {
7 public struct Failure: Error, CustomStringConvertible {
8 public let description: String
9 }
10
11 /// `ORGSTAR_EMACS`, then the usual install locations: an app launched from the Dock
12 /// doesn't see the shell's PATH.
13 public static func executable(environment: [String: String] = ProcessInfo.processInfo.environment) -> URL? {
14 let candidates = [environment["ORGSTAR_EMACS"]].compactMap { $0 } + [
15 "/opt/homebrew/bin/emacs", "/usr/local/bin/emacs", "/Applications/Emacs.app/Contents/MacOS/Emacs",
16 "/run/current-system/sw/bin/emacs", "/usr/bin/emacs",
17 ]
18 return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }.map(URL.init(fileURLWithPath:))
19 }
20
21 /// Emacs point for a UTF-16 offset.
22 static func point(_ offset: Int, in text: String) -> Int {
23 let index = String.Index(utf16Offset: offset, in: text)
24 return text.unicodeScalars[..<index].count + 1
25 }
26
27 /// Runs `form` with point at `point` in a copy of `text` whose directory is `directory`,
28 /// then returns the text of the table that starts at `table.lowerBound`.
29 public static func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String, timeout: Duration = .seconds(60)) async throws -> String {
30 guard let emacs = executable() else { throw Failure(description: "Emacs isn't installed, so this table can't be recalculated.") }
31 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-emacs-\(UUID().uuidString)")
32 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
33 defer { try? FileManager.default.removeItem(at: folder) }
34 let input = folder.appendingPathComponent("input.org")
35 let output = folder.appendingPathComponent("output.org")
36 let script = folder.appendingPathComponent("recalc.el")
37 try text.write(to: input, atomically: true, encoding: .utf8)
38 func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
39 try """
40 ;;; -*- lexical-binding: t -*-
41 (require 'org)
42 (require 'org-table)
43 (setq enable-local-variables :safe)
44 (with-temp-buffer
45 (let ((coding-system-for-read 'utf-8-unix))
46 (insert-file-contents \(lisp(input.path))))
47 (setq default-directory \(lisp(directory.path + "/")))
48 (org-mode)
49 (goto-char \(Self.point(point, in: text)))
50 \(form)
51 (goto-char \(Self.point(table.lowerBound, in: text)))
52 (let ((coding-system-for-write 'utf-8-unix))
53 (write-region (org-table-begin) (org-table-end) \(lisp(output.path)))))
54 """.write(to: script, atomically: true, encoding: .utf8)
55
56 let process = Process()
57 process.executableURL = emacs
58 process.arguments = ["-Q", "--batch", "-l", script.path]
59 process.currentDirectoryURL = directory
60 let errors = Pipe()
61 process.standardError = errors
62 process.standardOutput = FileHandle.nullDevice
63 try process.run()
64 let deadline = ContinuousClock.now + timeout
65 while process.isRunning {
66 if ContinuousClock.now > deadline {
67 process.terminate()
68 throw Failure(description: "Emacs took too long to recalculate the table.")
69 }
70 try? await Task.sleep(for: .milliseconds(50))
71 if Task.isCancelled {
72 process.terminate()
73 throw CancellationError()
74 }
75 }
76 guard process.terminationStatus == 0, let data = FileManager.default.contents(atPath: output.path) else {
77 let log = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
78 let last = log.split(separator: "\n").last.map(String.init) ?? "Emacs failed"
79 throw Failure(description: last)
80 }
81 return String(decoding: data, as: UTF8.self)
82 }
83
84 /// Exports `text`, the buffer of the file at `path`, with an ox function such as
85 /// `org-latex-export-to-pdf`. The file is written beside `path`, as Emacs does; source
86 /// blocks are not run. Returns the path Emacs wrote.
87 public static func export(text: String, path: String, function: String, timeout: Duration = .seconds(120)) async throws -> String {
88 guard let emacs = executable() else { throw Failure(description: "Emacs isn't installed, so this format can't be exported.") }
89 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-export-\(UUID().uuidString)")
90 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
91 defer { try? FileManager.default.removeItem(at: folder) }
92 let snapshot = folder.appendingPathComponent("snapshot.org")
93 let output = folder.appendingPathComponent("output")
94 let script = folder.appendingPathComponent("export.el")
95 try text.write(to: snapshot, atomically: true, encoding: .utf8)
96 func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
97 try """
98 ;;; -*- lexical-binding: t -*-
99 (require 'org)
100 (require 'ox)
101 (setq enable-local-variables :safe
102 org-export-use-babel nil)
103 (with-current-buffer (find-file-noselect \(lisp(path)))
104 (let ((inhibit-read-only t)
105 (coding-system-for-read 'utf-8-unix))
106 (erase-buffer)
107 (insert-file-contents \(lisp(snapshot.path)))
108 (set-buffer-modified-p nil))
109 (let ((file (\(function))))
110 (with-temp-file \(lisp(output.path)) (insert (expand-file-name file)))))
111 """.write(to: script, atomically: true, encoding: .utf8)
112 let process = Process()
113 process.executableURL = emacs
114 process.arguments = ["-Q", "--batch", "-l", script.path]
115 process.currentDirectoryURL = URL(fileURLWithPath: path).deletingLastPathComponent()
116 // Babel's PATH, so a Dock-launched app's Emacs finds latexmk and pdflatex.
117 process.environment = BabelRunner.environment
118 let errors = Pipe()
119 process.standardError = errors
120 process.standardOutput = FileHandle.nullDevice
121 try process.run()
122 let deadline = ContinuousClock.now + timeout
123 while process.isRunning {
124 if ContinuousClock.now > deadline {
125 process.terminate()
126 throw Failure(description: "Emacs took too long to export.")
127 }
128 try? await Task.sleep(for: .milliseconds(100))
129 if Task.isCancelled {
130 process.terminate()
131 throw CancellationError()
132 }
133 }
134 guard let written = try? String(contentsOf: output, encoding: .utf8) else {
135 let log = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
136 throw Failure(description: log.split(separator: "\n").last.map(String.init) ?? "Emacs couldn't export the file.")
137 }
138 return written
139 }
140}
141#endif