Commit 7fee8f1214

7fee8f1214931d1d034bc40d1155a605813239cc

parent: ed56474574

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 09:04 UTC

Run elisp: links after asking, in Emacs or the native interpreter

Layout: unified · split

Sources/OrgApp/LinkFollow.swift +24 −2
@@ -10,6 +10,8 @@ public enum LinkFollow: Equatable, Sendable {
1010 case message(String)
1111 /// Files to choose one of to open: a Denote query link's matches.
1212 case choose(prompt: String, paths: [String])
13 /// An `elisp:` link's form, to run with `evaluateLink` once the user agrees.
14 case elisp(String)
1315}
1416
1517extension DocumentSession {
@@ -66,13 +68,33 @@ extension DocumentSession {
6668 return followFile(file, isText: isText)
6769 case "coderef":
6870 return searchCurrent("(" + link.path + ")")
69 case "shell", "elisp":
70 return .message("orgstar doesn't run \(link.type) links")
71 case "elisp":
72 // `org-link--open-elisp`: a form is evaluated, anything else is a command to call.
73 guard link.path.hasPrefix("(") else { return .message("orgstar doesn't run Emacs commands from elisp: links") }
74 return .elisp(link.path)
75 case "shell":
76 return .message("orgstar doesn't run shell links")
7177 default:
7278 return .message("orgstar can't open \(link.type) links")
7379 }
7480 }
7581
82 /// Evaluates an `elisp:` link's form as `org-link--open-elisp` does: in Emacs, in a copy of
83 /// the open file, when `programs` has it, otherwise in `Elisp`. Returns the message to show.
84 public func evaluateLink(_ form: String) async -> String {
85 if let programs = Self.runner, let path, let text = document?.text {
86 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
87 do {
88 if let value = try await programs.evaluateLisp(form, text: text, point: caret(of: path) ?? 0, directory: directory) {
89 return "\(form) => \(value)"
90 }
91 } catch {
92 return "\(error)"
93 }
94 }
95 return Links.evaluateElisp(form)
96 }
97
7698 static func url(_ string: String) -> LinkFollow {
7799 let allowed = CharacterSet.urlFragmentAllowed.union(.urlQueryAllowed).union(CharacterSet(charactersIn: "#%"))
78100 guard let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: allowed) ?? string) else {
Sources/OrgApp/ProgramRunning.swift +7
@@ -7,6 +7,13 @@ public protocol ProgramRunning: Sendable {
77 func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput
88 /// Runs `form` in Emacs on a copy of `text`; returns the table that starts at `table.lowerBound`.
99 func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String
10 /// Evaluates `form` in Emacs, in a copy of `text` with point at `point`, and returns its
11 /// value as `%s` prints it; nil when there is no Emacs to run.
12 func evaluateLisp(_ form: String, text: String, point: Int, directory: URL) async throws -> String?
13}
14
15extension ProgramRunning {
16 public func evaluateLisp(_ form: String, text: String, point: Int, directory: URL) async throws -> String? { nil }
1017}
1118
1219extension DocumentSession {
Sources/OrgCore/Config/Elisp.swift +4 −4
@@ -321,15 +321,15 @@ public final class Elisp {
321321 }
322322 }
323323
324 /// `prin1-to-string` with `princ` for strings when `escape` is false.
324 /// `prin1-to-string`, or `princ` when `escape` is false.
325325 public static func printed(_ v: Sexp, escape: Bool = false) -> String {
326326 switch v {
327327 case .string(let s): return escape ? "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" : s
328328 case .float(let d): return floatText(d)
329329 case .character(let c): return String(c)
330 case .list(let items): return "(" + items.map { printed($0, escape: true) }.joined(separator: " ") + ")"
331 case .dotted(let items, let last): return "(" + items.map { printed($0, escape: true) }.joined(separator: " ") + " . " + printed(last, escape: true) + ")"
332 case .vector(let items): return "[" + items.map { printed($0, escape: true) }.joined(separator: " ") + "]"
330 case .list(let items): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + ")"
331 case .dotted(let items, let last): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + " . " + printed(last, escape: escape) + ")"
332 case .vector(let items): return "[" + items.map { printed($0, escape: escape) }.joined(separator: " ") + "]"
333333 default: return v.description
334334 }
335335 }
Sources/OrgCore/Links/Links.swift +18
@@ -272,6 +272,24 @@ public struct OpenLinkAtPoint: OrgCommand {
272272 }
273273}
274274
275extension Links {
276 /// An `elisp:` link's form evaluated in `Elisp`: `org-link--open-elisp`'s message, the
277 /// error's, or why it needs Emacs.
278 public static func evaluateElisp(_ form: String) -> String {
279 let lisp = Elisp()
280 lisp.standardTime()
281 do {
282 let value = try lisp.eval(try LispReader.readFirst(form).sexp)
283 if Elisp.containsClosure(value) { throw Elisp.Unsupported(what: "a closure") }
284 return "\(form) => \(try Elisp.format([.string("%s"), value]))"
285 } catch is Elisp.Unsupported {
286 return "This link uses Emacs Lisp that runs only in Emacs."
287 } catch {
288 return "\(error)"
289 }
290 }
291}
292
275293extension Links {
276294 /// `org-at-date-range-p` with INACTIVE-OK: the range starting at one of the two brackets
277295 /// back from `offset` that reaches it.
Sources/OrgPrograms/EmacsRunner.swift +60
@@ -89,6 +89,66 @@ public enum EmacsRunner {
8989 return String(decoding: data, as: UTF8.self)
9090 }
9191
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
92152 /// Exports `text`, the buffer of the file at `path`, with an ox function such as
93153 /// `org-latex-export-to-pdf`. The file is written beside `path`, as Emacs does; source
94154 /// blocks are not run. Returns the path Emacs wrote.
Sources/OrgPrograms/Programs.swift +6
@@ -33,5 +33,11 @@ public struct Programs: ProgramRunning {
3333 public func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String {
3434 try await EmacsRunner.recalculateTable(text: text, directory: directory, table: table, point: point, form: form)
3535 }
36
37 /// `elisp:` links in Emacs; nil without it, so they run in `Elisp`.
38 public func evaluateLisp(_ form: String, text: String, point: Int, directory: URL) async throws -> String? {
39 guard emacs() != nil else { return nil }
40 return try await EmacsRunner.evaluate(form, text: text, point: point, directory: directory)
41 }
3642}
3743#endif
Sources/Orgstar/ContentView.swift +18 −1
@@ -1049,7 +1049,7 @@ struct ContentView: View {
10491049 private func runExternal(_ request: ExternalRequest) {
10501050 switch request {
10511051 case .openLink(let link):
1052 if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
1052 if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask, elisp: runElispLink) { commands.show(message) }
10531053 // `org-occur` for a regexp link, once the editor shows the file.
10541054 if let regexp = Links.regexpSearch(link) {
10551055 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
@@ -1122,6 +1122,23 @@ struct ContentView: View {
11221122 }
11231123 }
11241124
1125 /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does.
1126 private func runElispLink(_ form: String) {
1127 let run = { _ = Task { commands.show(await session.evaluateLink(form)) } }
1128 let content = "elisp:" + form
1129 if let path = session.path, trust.isTrusted(path: path, content: content) { return run() }
1130 let choices = session.path == nil ? ["yes", "no"] : ["yes", "no", "always"]
1131 commands.ask(Prompt(key: "confirm", message: "Execute \(form) as Elisp? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
1132 switch answer {
1133 case "always":
1134 if let path = session.path { trust.trust(path: path, content: content) }
1135 run()
1136 case "yes": run()
1137 default: commands.show("Not run")
1138 }
1139 }
1140 }
1141
11251142 private struct ReminderKey: Equatable {
11261143 var enabled: Bool
11271144 var lead: Int
Sources/Orgstar/LinkOpener.swift +7 −2
@@ -6,8 +6,9 @@ import OrgCore
66@MainActor
77enum LinkOpener {
88 /// Returns a message when the link can't be followed.
9 /// `ask` picks among a query link's matches.
10 static func open(_ link: OrgLink, session: DocumentSession, workspace: WorkspaceModel, ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void) -> String? {
9 /// `ask` picks among a query link's matches; `elisp` runs an `elisp:` link's form.
10 static func open(_ link: OrgLink, session: DocumentSession, workspace: WorkspaceModel, ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void,
11 elisp: ((String) -> Void)? = nil) -> String? {
1112 #if APPSTORE
1213 // A file outside the sidebar's folders needs access to its folder first.
1314 if link.type == "file", !link.path.isEmpty,
@@ -26,6 +27,10 @@ enum LinkOpener {
2627 _ = open(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]), session: session, workspace: workspace, ask: ask)
2728 }
2829 return nil
30 case .elisp(let form):
31 guard let elisp else { return "orgstar doesn't run elisp links here" }
32 elisp(form)
33 return nil
2934 }
3035 }
3136}
Sources/OrgstarMobile/EditorScreen.swift +14
@@ -486,6 +486,20 @@ extension EditorScreen {
486486 guard let answer, let index = labels.firstIndex(of: answer) else { return }
487487 follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]))
488488 }
489 case .elisp(let form):
490 // Once trusted, as `org-link-elisp-confirm-function` asks.
491 let go = { _ = Task { message = await session.evaluateLink(form) } }
492 let content = "elisp:" + form
493 if trust.isTrusted(path: path, content: content) { return go() }
494 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Execute \(form) as Elisp?", choices: ["yes", "no", "always"])) { answer in
495 switch answer {
496 case "always":
497 trust.trust(path: path, content: content)
498 go()
499 case "yes": go()
500 default: message = "Not run"
501 }
502 }
489503 }
490504 }
491505
Sources/OrgstarMobile/ReaderScreen.swift +1
@@ -384,6 +384,7 @@ struct ReaderScreen: View {
384384 case .openExternally(let target): openURL(target)
385385 case .message(let text): message = text
386386 case .choose(let question, let paths): message = question + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
387 case .elisp: message = "Open the file in the editor to run elisp links."
387388 }
388389 return .handled
389390 }
Tests/OrgAppTests/AppTests.swift +4
@@ -1323,6 +1323,10 @@ struct LinkFollowTests {
13231323 #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
13241324 #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
13251325 #expect(follow("shell:rm -rf x") == .message("orgstar doesn't run shell links"))
1326 #expect(follow("elisp:(+ 1 2)") == .elisp("(+ 1 2)"))
1327 #expect(follow("elisp:org-agenda") == .message("orgstar doesn't run Emacs commands from elisp: links"))
1328 // Without a runner, in orgstar's interpreter.
1329 #expect(await session.evaluateLink("(+ 1 2)") == "(+ 1 2) => 3")
13261330 }
13271331
13281332 @Test func followsDenoteLinks() async throws {
Tests/OrgCoreTests/ElispLinkTests.swift added +28
@@ -0,0 +1,28 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// `elisp:` links evaluated in `Elisp`, with the message `org-link--open-elisp` shows.
6struct ElispLinkTests {
7 static let forms = [
8 "(+ 1 2)", "(list 1 \"a\" 'b 2.5)", "(concat \"a\" \"b\")", "(message \"hi\")", "(let ((x 2)) (* x x))",
9 "(mapcar (lambda (n) (* n 10)) '(1 2 3))", "nil", "(car 1)", "(/ 1 0)", "(error \"Nope %d\" 3)", "(format \"%S\" \"q\")",
10 ]
11
12 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
13 func matchesEmacs() throws {
14 let list = "(list " + Self.forms.map { form in
15 let quoted = form.debugDescription
16 return "(condition-case e (format \"%s => %s\" \(quoted) (eval (read \(quoted)))) (error (error-message-string e)))"
17 }.joined(separator: " ") + ")"
18 let emacs = try EmacsOracle.evaluate("", list)
19 #expect(emacs.count == Self.forms.count)
20 for (form, expected) in zip(Self.forms, emacs) {
21 #expect(Links.evaluateElisp(form) == expected, "\(form)")
22 }
23 }
24
25 @Test func refusesWhatOnlyEmacsHas() {
26 #expect(Links.evaluateElisp("(org-agenda nil \"a\")") == "This link uses Emacs Lisp that runs only in Emacs.")
27 }
28}
Tests/OrgProgramsTests/ProgramsTests.swift +20
@@ -38,6 +38,26 @@ struct EmacsFallbackTests {
3838 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-----------|\n| x | a | sqrt(a) |\n| y | 2 | 1.4142136 |\n#+TBLFM: $3=sqrt($2)\n")
3939 }
4040
41 /// `elisp:` links run in Emacs, in a copy of the file with point at the caret; in
42 /// orgstar's interpreter when Emacs is missing.
43 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
44 func evaluatesElispLinks() async throws {
45 let notes = try Folder()
46 let file = try notes.write("l.org", "* Head\nSee [[elisp:(org-get-heading t t)]].\n")
47 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
48 session.open(file.path)
49 let heading = await session.evaluateLink("(org-get-heading t t)")
50 #expect(heading == "(org-get-heading t t) => Head")
51 let list = await session.evaluateLink("(list 1 \"a\")")
52 #expect(list == "(list 1 \"a\") => (1 a)")
53 let error = await session.evaluateLink("(car 1)")
54 #expect(error == "Wrong type argument: listp, 1")
55 await DocumentSession.$scopedPrograms.withValue(Programs(emacs: { nil })) {
56 #expect(await session.evaluateLink("(+ 1 2)") == "(+ 1 2) => 3")
57 #expect(await session.evaluateLink("(org-get-heading t t)") == "This link uses Emacs Lisp that runs only in Emacs.")
58 }
59 }
60
4161 /// `org-sbe` on a block only Emacs runs: Emacs runs it without asking again.
4262 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
4363 func runsOtherLanguagesForOrgSbe() async throws {
docs/manual/guide/09-links.org +20 −1
@@ -61,7 +61,8 @@ A message in the echo area explains a link that can't be followed.
6161| Text | =[[budget table]]= | Searches this file: a =<<budget table>>= target, then =#+NAME: budget table=, then a heading. |
6262| Coderef | =[[(ref)]]= | Moves to the label =(ref:ref)= in a src or example block; see /Code references/ below. |
6363| Regexp | =[[/TODO.*soon/]]= | Shows a sparse tree of the regular expression's matches, as =org-occur=; iOS moves to the first match. |
64| =shell=, =elisp= | =[[shell:ls]]= | Not run. orgstar never executes these links. |
64| =shell= | =[[shell:ls]]= | Not run. orgstar never executes these links. |
65| =elisp= | =[[elisp:(+ 1 2)]]= | Runs the form once you agree; see /Emacs Lisp links/ below. |
6566| =attachment= | =[[attachment:scan.pdf]]= | Opens the file in the entry's attachment folder; see /Attachment links/ below. |
6667| Radio link | Text matching a =<<<radio target>>>= | Moves to the radio target. |
6768| =info=, =help=, others | | Not followed. The echo area says orgstar can't open the type. |
@@ -136,6 +137,24 @@ identifier, such as a PDF. A search after =::=, such as =::#custom-id= or =::*He
136137works as in a =file:= link. Backlinks list =denote:= links to a file, and to a heading when
137138the link searches for it.
138139
140** Emacs Lisp links
141
142Following an =elisp:= link whose path starts with =(= asks
143=Execute (form) as Elisp? (yes, no, always)=, as =org-link-elisp-confirm-function= does.
144=always= trusts the link's form in this file, so the question isn't asked again until it
145changes. The echo area then shows =(form) => value=, or the error's message.
146
147- On the Mac with Emacs installed, the form runs in =emacs -Q --batch= in a copy of the
148 file, with point at the caret, so Org functions see the file's text. Changes the form
149 makes to the buffer or to files in Emacs's session are not kept.
150- On iOS, in the Mac App Store version, and on the Mac without Emacs, the form runs in
151 orgstar's Emacs Lisp interpreter, with the functions listed under Lisp formulas in
152 [[file:10-tables.org][Tables]]. A form that uses anything else shows
153 =This link uses Emacs Lisp that runs only in Emacs.=
154
155A path that names a command, such as =elisp:org-agenda=, isn't run. The reader view on iOS
156doesn't run =elisp:= links; open the file in the editor.
157
139158** Timestamps
140159
141160=C-c C-o= (Mac =⌃⌘O=) or =⌘=-click on a timestamp opens the agenda on that day, as
docs/manual/guide/15-alongside-emacs.org +2 −1
@@ -225,7 +225,8 @@ Code blocks (see [[file:11-code-blocks.org][Code blocks]]):
225225
226226Links (see [[file:09-links.org][Links]]):
227227
228- =shell:= and =elisp:= links aren't run.
228- =shell:= links aren't run. =elisp:= links run a form after asking, in Emacs on the Mac
229 when it is installed, otherwise in orgstar's interpreter; command names aren't run.
229230
230231Capture templates (see [[file:08-capture.org][Capture]]):
231232