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