Sources/OrgPrograms/EmacsRunner.swift
214 lines · 11640 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 // `org-sbe` runs blocks: the user agreed to the table's Lisp, and Babel needs the languages.
40 let blocks = text.contains("org-sbe") ? """
41 (setq org-confirm-babel-evaluate nil)
42 (dolist (language '(C awk clojure java js python R ruby shell))
43 (require (intern (format "ob-%s" language)) nil t))
44 """ : ""
45 try """
46 ;;; -*- lexical-binding: t -*-
47 (require 'org)
48 (require 'org-table)
49 (setq enable-local-variables :safe)
50 \(blocks)
51 (with-temp-buffer
52 (let ((coding-system-for-read 'utf-8-unix))
53 (insert-file-contents \(lisp(input.path))))
54 (setq default-directory \(lisp(directory.path + "/")))
55 (org-mode)
56 (goto-char \(Self.point(point, in: text)))
57 \(form)
58 (goto-char \(Self.point(table.lowerBound, in: text)))
59 (let ((coding-system-for-write 'utf-8-unix))
60 (write-region (org-table-begin) (org-table-end) \(lisp(output.path)))))
61 """.write(to: script, atomically: true, encoding: .utf8)
62
63 let process = Process()
64 process.executableURL = emacs
65 process.arguments = ["-Q", "--batch", "-l", script.path]
66 process.currentDirectoryURL = directory
67 process.environment = BabelRunner.environment
68 let errors = Pipe()
69 process.standardError = errors
70 process.standardOutput = FileHandle.nullDevice
71 try process.run()
72 let deadline = ContinuousClock.now + timeout
73 while process.isRunning {
74 if ContinuousClock.now > deadline {
75 process.terminate()
76 throw Failure(description: "Emacs took too long to recalculate the table.")
77 }
78 try? await Task.sleep(for: .milliseconds(50))
79 if Task.isCancelled {
80 process.terminate()
81 throw CancellationError()
82 }
83 }
84 guard process.terminationStatus == 0, let data = FileManager.default.contents(atPath: output.path) else {
85 let log = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
86 let last = log.split(separator: "\n").last.map(String.init) ?? "Emacs failed"
87 throw Failure(description: last)
88 }
89 return String(decoding: data, as: UTF8.self)
90 }
91
92 /// Evaluates `form` as `org-link--open-elisp` does, in a copy of `text` with point at
93 /// `point` and `directory` as its directory; returns the value as `%s` prints it, or throws
94 /// the error's message.
95 public static func evaluate(_ form: String, text: String, point: Int, directory: URL, timeout: Duration = .seconds(60)) async throws -> String {
96 guard let emacs = executable() else { throw Failure(description: "Emacs isn't installed.") }
97 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-emacs-\(UUID().uuidString)")
98 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
99 defer { try? FileManager.default.removeItem(at: folder) }
100 let input = folder.appendingPathComponent("input.org")
101 let output = folder.appendingPathComponent("output")
102 let script = folder.appendingPathComponent("eval.el")
103 try text.write(to: input, atomically: true, encoding: .utf8)
104 func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
105 try """
106 ;;; -*- lexical-binding: t -*-
107 (require 'org)
108 (setq enable-local-variables :safe)
109 (with-temp-buffer
110 (let ((coding-system-for-read 'utf-8-unix))
111 (insert-file-contents \(lisp(input.path))))
112 (setq default-directory \(lisp(directory.path + "/")))
113 (org-mode)
114 (goto-char \(Self.point(min(point, (text as NSString).length), in: text)))
115 (let ((result (condition-case e
116 (concat "=" (format "%s" (eval (read \(lisp(form))))))
117 (error (concat "!" (error-message-string e)))))
118 (coding-system-for-write 'utf-8-unix))
119 (with-temp-file \(lisp(output.path)) (insert result))))
120 """.write(to: script, atomically: true, encoding: .utf8)
121
122 let process = Process()
123 process.executableURL = emacs
124 process.arguments = ["-Q", "--batch", "-l", script.path]
125 process.currentDirectoryURL = directory
126 process.environment = BabelRunner.environment
127 let errors = Pipe()
128 process.standardError = errors
129 process.standardOutput = FileHandle.nullDevice
130 process.standardInput = FileHandle.nullDevice
131 try process.run()
132 let deadline = ContinuousClock.now + timeout
133 while process.isRunning {
134 if ContinuousClock.now > deadline {
135 process.terminate()
136 throw Failure(description: "Emacs took too long to evaluate the link.")
137 }
138 try? await Task.sleep(for: .milliseconds(50))
139 if Task.isCancelled {
140 process.terminate()
141 throw CancellationError()
142 }
143 }
144 guard let written = try? String(contentsOf: output, encoding: .utf8), let mark = written.first else {
145 let log = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
146 throw Failure(description: log.split(separator: "\n").last.map(String.init) ?? "Emacs failed")
147 }
148 guard mark == "=" else { throw Failure(description: String(written.dropFirst())) }
149 return String(written.dropFirst())
150 }
151
152 /// Exports `text`, the buffer of the file at `path`, with an ox function such as
153 /// `org-latex-export-to-pdf`. The file is written beside `path`, as Emacs does; source
154 /// blocks are not run. Returns the path Emacs wrote.
155 /// `subtree` is a point (1-based, in characters) whose subtree alone is exported;
156 /// `bodyOnly` leaves out the document's preamble, as the dispatcher's `C-s` and `C-b`.
157 public static func export(
158 text: String, path: String, function: String, subtree: Int? = nil, bodyOnly: Bool = false, timeout: Duration = .seconds(120)
159 ) async throws -> String {
160 guard let emacs = executable() else { throw Failure(description: "Emacs isn't installed, so this format can't be exported.") }
161 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-export-\(UUID().uuidString)")
162 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
163 defer { try? FileManager.default.removeItem(at: folder) }
164 let snapshot = folder.appendingPathComponent("snapshot.org")
165 let output = folder.appendingPathComponent("output")
166 let script = folder.appendingPathComponent("export.el")
167 try text.write(to: snapshot, atomically: true, encoding: .utf8)
168 func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
169 try """
170 ;;; -*- lexical-binding: t -*-
171 (require 'org)
172 (require 'ox)
173 (setq enable-local-variables :safe
174 org-export-use-babel nil)
175 (with-current-buffer (find-file-noselect \(lisp(path)))
176 (let ((inhibit-read-only t)
177 (coding-system-for-read 'utf-8-unix))
178 (erase-buffer)
179 (insert-file-contents \(lisp(snapshot.path)))
180 (set-buffer-modified-p nil))
181 \(subtree.map { "(goto-char \($0))" } ?? "")
182 (let ((file (\(function)\(subtree == nil && !bodyOnly ? "" : " nil \(subtree == nil ? "nil" : "t") nil \(bodyOnly ? "t" : "nil")"))))
183 (with-temp-file \(lisp(output.path)) (insert (expand-file-name file)))))
184 """.write(to: script, atomically: true, encoding: .utf8)
185 let process = Process()
186 process.executableURL = emacs
187 process.arguments = ["-Q", "--batch", "-l", script.path]
188 process.currentDirectoryURL = URL(fileURLWithPath: path).deletingLastPathComponent()
189 // Babel's PATH, so a Dock-launched app's Emacs finds latexmk and pdflatex.
190 process.environment = BabelRunner.environment
191 let errors = Pipe()
192 process.standardError = errors
193 process.standardOutput = FileHandle.nullDevice
194 try process.run()
195 let deadline = ContinuousClock.now + timeout
196 while process.isRunning {
197 if ContinuousClock.now > deadline {
198 process.terminate()
199 throw Failure(description: "Emacs took too long to export.")
200 }
201 try? await Task.sleep(for: .milliseconds(100))
202 if Task.isCancelled {
203 process.terminate()
204 throw CancellationError()
205 }
206 }
207 guard let written = try? String(contentsOf: output, encoding: .utf8) else {
208 let log = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
209 throw Failure(description: log.split(separator: "\n").last.map(String.init) ?? "Emacs couldn't export the file.")
210 }
211 return written
212 }
213}
214#endif