Run elisp: links and org-sbe in process !419
29 files changed, +954 −23
Layout: unified · split
Sources/OrgApp/JavaScriptBlocks.swift +64
| @@ -36,6 +36,59 @@ public enum JavaScriptBlocks { | |||
| 36 | } | 36 | } |
| 37 | } | 37 | } |
| 38 | 38 | ||
| 39 | /// Runs a js `job` without a session, as `org-sbe` in a table formula needs, waiting on the | ||
| 40 | /// calling thread at most `timeout`; nil for other jobs. A block whose earlier run timed out | ||
| 41 | /// and is still running is refused without starting another. | ||
| 42 | public static func runHere(_ job: BabelJob, timeout: Duration = .seconds(5)) throws -> BabelOutput? { | ||
| 43 | guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil } | ||
| 44 | if abandoned.contains(job.input) { throw Stopped(description: "The block took too long before and is still running.") } | ||
| 45 | let run = Run() | ||
| 46 | let flag = Abandoned.Flag() | ||
| 47 | let thread = Thread { | ||
| 48 | run.end(Result { try Engine().main(job.input, run: run) }) | ||
| 49 | abandoned.ended(job.input, flag) | ||
| 50 | } | ||
| 51 | thread.stackSize = 8 << 20 | ||
| 52 | thread.start() | ||
| 53 | do { | ||
| 54 | return try run.result(within: timeout) | ||
| 55 | } catch let error as Stopped { | ||
| 56 | abandoned.add(job.input, flag) | ||
| 57 | throw error | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | private static let abandoned = Abandoned() | ||
| 62 | |||
| 63 | /// The inputs of `runHere` blocks that timed out and whose threads still run. | ||
| 64 | final class Abandoned: @unchecked Sendable { | ||
| 65 | final class Flag: @unchecked Sendable { | ||
| 66 | var ended = false | ||
| 67 | var abandoned = false | ||
| 68 | } | ||
| 69 | |||
| 70 | private let lock = NSLock() | ||
| 71 | private var running: [String: Int] = [:] | ||
| 72 | |||
| 73 | func contains(_ input: String) -> Bool { lock.withLock { running[input] != nil } } | ||
| 74 | |||
| 75 | func add(_ input: String, _ flag: Flag) { | ||
| 76 | lock.withLock { | ||
| 77 | guard !flag.ended else { return } | ||
| 78 | flag.abandoned = true | ||
| 79 | running[input, default: 0] += 1 | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | func ended(_ input: String, _ flag: Flag) { | ||
| 84 | lock.withLock { | ||
| 85 | flag.ended = true | ||
| 86 | guard flag.abandoned else { return } | ||
| 87 | if let n = running[input] { running[input] = n > 1 ? n - 1 : nil } | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
| 91 | |||
| 39 | struct Stopped: Error, CustomStringConvertible { | 92 | struct Stopped: Error, CustomStringConvertible { |
| 40 | let description: String | 93 | let description: String |
| 41 | } | 94 | } |
| @@ -64,6 +117,7 @@ public enum JavaScriptBlocks { | |||
| 64 | private var result: Result<BabelOutput, Error>? | 117 | private var result: Result<BabelOutput, Error>? |
| 65 | private var continuation: CheckedContinuation<BabelOutput, Error>? | 118 | private var continuation: CheckedContinuation<BabelOutput, Error>? |
| 66 | private let wake = DispatchSemaphore(value: 0) | 119 | private let wake = DispatchSemaphore(value: 0) |
| 120 | private let done = DispatchSemaphore(value: 0) | ||
| 67 | 121 | ||
| 68 | var stopped: Bool { lock.withLock { result != nil } } | 122 | var stopped: Bool { lock.withLock { result != nil } } |
| 69 | 123 | ||
| @@ -77,6 +131,16 @@ public enum JavaScriptBlocks { | |||
| 77 | guard first else { return } | 131 | guard first else { return } |
| 78 | waiting?.resume(with: outcome) | 132 | waiting?.resume(with: outcome) |
| 79 | wake.signal() | 133 | wake.signal() |
| 134 | done.signal() | ||
| 135 | } | ||
| 136 | |||
| 137 | /// Blocks until the run ends, ending it when `timeout` passes first. | ||
| 138 | func result(within timeout: Duration) throws -> BabelOutput { | ||
| 139 | let (seconds, attoseconds) = timeout.components | ||
| 140 | if done.wait(timeout: .now() + .nanoseconds(Int(seconds) * 1_000_000_000 + Int(attoseconds / 1_000_000_000))) == .timedOut { | ||
| 141 | end(.failure(Stopped(description: "The block took longer than \(timeout) and was stopped."))) | ||
| 142 | } | ||
| 143 | return try lock.withLock { result! }.get() | ||
| 80 | } | 144 | } |
| 81 | 145 | ||
| 82 | func wait(_ continuation: CheckedContinuation<BabelOutput, Error>) { | 146 | func wait(_ continuation: CheckedContinuation<BabelOutput, Error>) { |
Sources/OrgApp/LinkFollow.swift +24 −2
| @@ -10,6 +10,8 @@ public enum LinkFollow: Equatable, Sendable { | |||
| 10 | case message(String) | 10 | case message(String) |
| 11 | /// Files to choose one of to open: a Denote query link's matches. | 11 | /// Files to choose one of to open: a Denote query link's matches. |
| 12 | case choose(prompt: String, paths: [String]) | 12 | case choose(prompt: String, paths: [String]) |
| 13 | /// An `elisp:` link's form, to run with `evaluateLink` once the user agrees. | ||
| 14 | case elisp(String) | ||
| 13 | } | 15 | } |
| 14 | 16 | ||
| 15 | extension DocumentSession { | 17 | extension DocumentSession { |
| @@ -66,13 +68,33 @@ extension DocumentSession { | |||
| 66 | return followFile(file, isText: isText) | 68 | return followFile(file, isText: isText) |
| 67 | case "coderef": | 69 | case "coderef": |
| 68 | return searchCurrent("(" + link.path + ")") | 70 | return searchCurrent("(" + link.path + ")") |
| 69 | case "shell", "elisp": | 71 | case "elisp": |
| 70 | return .message("orgstar doesn't run \(link.type) links") | 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") | ||
| 71 | default: | 77 | default: |
| 72 | return .message("orgstar can't open \(link.type) links") | 78 | return .message("orgstar can't open \(link.type) links") |
| 73 | } | 79 | } |
| 74 | } | 80 | } |
| 75 | 81 | ||
| 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 | |||
| 76 | static func url(_ string: String) -> LinkFollow { | 98 | static func url(_ string: String) -> LinkFollow { |
| 77 | let allowed = CharacterSet.urlFragmentAllowed.union(.urlQueryAllowed).union(CharacterSet(charactersIn: "#%")) | 99 | let allowed = CharacterSet.urlFragmentAllowed.union(.urlQueryAllowed).union(CharacterSet(charactersIn: "#%")) |
| 78 | guard let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: allowed) ?? string) else { | 100 | guard let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: allowed) ?? string) else { |
Sources/OrgApp/ProgramRunning.swift +7
| @@ -7,6 +7,13 @@ public protocol ProgramRunning: Sendable { | |||
| 7 | func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput | 7 | func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput |
| 8 | /// Runs `form` in Emacs on a copy of `text`; returns the table that starts at `table.lowerBound`. | 8 | /// Runs `form` in Emacs on a copy of `text`; returns the table that starts at `table.lowerBound`. |
| 9 | func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String | 9 | 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 | |||
| 15 | extension ProgramRunning { | ||
| 16 | public func evaluateLisp(_ form: String, text: String, point: Int, directory: URL) async throws -> String? { nil } | ||
| 10 | } | 17 | } |
| 11 | 18 | ||
| 12 | extension DocumentSession { | 19 | extension DocumentSession { |
Sources/OrgApp/TableReason.swift +1
| @@ -62,6 +62,7 @@ public enum TableReason { | |||
| 62 | if let clause = value("cl-loop ") { return String(localized: "cl-loop \(clause)", comment: comment) } | 62 | if let clause = value("cl-loop ") { return String(localized: "cl-loop \(clause)", comment: comment) } |
| 63 | if let names = value("condition-case on ") { return String(localized: "condition-case on \(names)", comment: comment) } | 63 | if let names = value("condition-case on ") { return String(localized: "condition-case on \(names)", comment: comment) } |
| 64 | if let pattern = value("pcase pattern ") { return String(localized: "pcase pattern \(pattern)", comment: comment) } | 64 | if let pattern = value("pcase pattern ") { return String(localized: "pcase pattern \(pattern)", comment: comment) } |
| 65 | if let name = value("variable ") { return String(localized: "variable \(name)", comment: "Why a table needs Emacs: a Lisp variable with no value") } | ||
| 65 | if let name = value("let-alist ") { return String(localized: "let-alist \(name)", comment: comment) } | 66 | if let name = value("let-alist ") { return String(localized: "let-alist \(name)", comment: comment) } |
| 66 | if let text = value("string-width of ") { return String(localized: "string-width of \(text)", comment: comment) } | 67 | if let text = value("string-width of ") { return String(localized: "string-width of \(text)", comment: comment) } |
| 67 | if let rest = value("regexp "), let parts = split(rest, " in ") { | 68 | if let rest = value("regexp "), let parts = split(rest, " in ") { |
Sources/OrgApp/WorkspaceModel.swift +4
| @@ -64,6 +64,10 @@ public final class WorkspaceModel { | |||
| 64 | guard let path = (try? index.headings(withID: id))?.first?.path else { return nil } | 64 | guard let path = (try? index.headings(withID: id))?.first?.path else { return nil } |
| 65 | return FileManager.default.contents(atPath: path).map { SourceText(bytes: [UInt8]($0)).text } | 65 | return FileManager.default.contents(atPath: path).map { SourceText(bytes: [UInt8]($0)).text } |
| 66 | } | 66 | } |
| 67 | #if canImport(JavaScriptCore) | ||
| 68 | // `org-sbe` in table formulas runs js blocks in JavaScriptCore. | ||
| 69 | TableBlocks.javaScript = { try JavaScriptBlocks.runHere($0) } | ||
| 70 | #endif | ||
| 67 | } | 71 | } |
| 68 | 72 | ||
| 69 | /// `~/Library/Application Support/Orgstar`, or `ORGSTAR_DATA_DIR` when set (for development). | 73 | /// `~/Library/Application Support/Orgstar`, or `ORGSTAR_DATA_DIR` when set (for development). |
Sources/OrgCore/Compute/BabelExpand.swift +2 −2
| @@ -41,7 +41,7 @@ extension Babel { | |||
| 41 | guard let raw = params.single[key] else { return nil } | 41 | guard let raw = params.single[key] else { return nil } |
| 42 | var value = params.evaluated[key] | 42 | var value = params.evaluated[key] |
| 43 | if value == nil, params.lisp.contains(key) { | 43 | if value == nil, params.lisp.contains(key) { |
| 44 | guard let form = try? LispReader.readFirst(raw).sexp, let result = try? Elisp().eval(form) else { | 44 | guard let form = try? LispReader.readFirst(raw).sexp, let result = try? Elisp().eval(form), !Elisp.containsClosure(result) else { |
| 45 | throw Failure.message("\(key) \(raw) is Lisp that only Emacs can evaluate.") | 45 | throw Failure.message("\(key) \(raw) is Lisp that only Emacs can evaluate.") |
| 46 | } | 46 | } |
| 47 | value = result | 47 | value = result |
| @@ -61,7 +61,7 @@ extension Babel { | |||
| 61 | guard case .string(let s) = read(value) else { return .string(value) } | 61 | guard case .string(let s) = read(value) else { return .string(value) } |
| 62 | return .string(s) | 62 | return .string(s) |
| 63 | } | 63 | } |
| 64 | guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form) else { | 64 | guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form), !Elisp.containsClosure(result) else { |
| 65 | throw Failure.message("The property value \(value) is Lisp that only Emacs can evaluate.") | 65 | throw Failure.message("The property value \(value) is Lisp that only Emacs can evaluate.") |
| 66 | } | 66 | } |
| 67 | if let s = result.string { return .string(s) } | 67 | if let s = result.string { return .string(s) } |
Sources/OrgCore/Compute/BabelHeaders.swift +1 −1
| @@ -21,7 +21,7 @@ extension Babel { | |||
| 21 | mutating func evaluateLisp(file: String?) { | 21 | mutating func evaluateLisp(file: String?) { |
| 22 | for key in lisp { | 22 | for key in lisp { |
| 23 | guard let form = try? LispReader.readFirst(single[key] ?? "").sexp, | 23 | guard let form = try? LispReader.readFirst(single[key] ?? "").sexp, |
| 24 | let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form) else { continue } | 24 | let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form), !Elisp.containsClosure(value) else { continue } |
| 25 | let printed = Elisp.printed(value) | 25 | let printed = Elisp.printed(value) |
| 26 | if let s = value.string { | 26 | if let s = value.string { |
| 27 | single[key] = s | 27 | single[key] = s |
Sources/OrgCore/Compute/BabelVars.swift +1 −1
| @@ -88,7 +88,7 @@ extension Babel { | |||
| 88 | /// table. | 88 | /// table. |
| 89 | static func lispValue(_ value: String) throws -> VarValue { | 89 | static func lispValue(_ value: String) throws -> VarValue { |
| 90 | let refusal = Failure.message(":var value \(value) is Lisp that only Emacs can evaluate.") | 90 | let refusal = Failure.message(":var value \(value) is Lisp that only Emacs can evaluate.") |
| 91 | guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form) else { throw refusal } | 91 | guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form), !Elisp.containsClosure(result) else { throw refusal } |
| 92 | func cell(_ v: Sexp) throws -> Cell { | 92 | func cell(_ v: Sexp) throws -> Cell { |
| 93 | if let s = v.string { return .text(s) } | 93 | if let s = v.string { return .text(s) } |
| 94 | if let n = number(Elisp.printed(v)), Elisp.printed(v) == n { return .number(n) } | 94 | if let n = number(Elisp.printed(v)), Elisp.printed(v) == n { return .number(n) } |
Sources/OrgCore/Compute/TableFormulas.swift +3
| @@ -652,6 +652,7 @@ extension EmacsBuffer { | |||
| 652 | let lisp = Elisp() | 652 | let lisp = Elisp() |
| 653 | lisp.standardTime() | 653 | lisp.standardTime() |
| 654 | Self.defineLookups(lisp) | 654 | Self.defineLookups(lisp) |
| 655 | Babel.defineSbe(lisp) { [unowned self] in text as String } | ||
| 655 | let value: Sexp | 656 | let value: Sexp |
| 656 | do { | 657 | do { |
| 657 | value = try lisp.eval(try lisp.eval(try LispReader.readFirst(form).sexp)) | 658 | value = try lisp.eval(try lisp.eval(try LispReader.readFirst(form).sexp)) |
| @@ -660,6 +661,8 @@ extension EmacsBuffer { | |||
| 660 | } catch { | 661 | } catch { |
| 661 | return "#ERROR" | 662 | return "#ERROR" |
| 662 | } | 663 | } |
| 664 | // Emacs prints functions as `#[ARGS BODY ENV]`. | ||
| 665 | if Elisp.containsClosure(value) { throw Calc.Unsupported("Lisp formula with a function value") } | ||
| 663 | var result = Elisp.printed(value) | 666 | var result = Elisp.printed(value) |
| 664 | if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) } | 667 | if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) } |
| 665 | return result | 668 | return result |
Sources/OrgCore/Compute/TableSbe.swift added +257
| @@ -0,0 +1,257 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // `org-sbe` (ob-table.el, Org 9.8.7) in Lisp table formulas. The named block runs in `Elisp`, | ||
| 4 | // or for js through `TableBlocks.javaScript`, and named tables and lists are read from the | ||
| 5 | // file. Other languages, and references this can't follow, throw `Elisp.Unsupported`, so the | ||
| 6 | // table goes to Emacs. | ||
| 7 | |||
| 8 | /// How `org-sbe` runs js blocks. | ||
| 9 | public enum TableBlocks { | ||
| 10 | /// Runs a js job to the end on the calling thread; nil when it can't. The app sets it. | ||
| 11 | nonisolated(unsafe) public static var javaScript: ((BabelJob) throws -> BabelOutput?)? | ||
| 12 | /// Whether `org-sbe` may run; the app ties it to running source blocks. | ||
| 13 | nonisolated(unsafe) public static var allowed: () -> Bool = { true } | ||
| 14 | /// The reason a table goes to the app when `allowed` is false. | ||
| 15 | public static let lockedReason = "Lisp org-sbe with source blocks locked" | ||
| 16 | } | ||
| 17 | |||
| 18 | extension Babel { | ||
| 19 | /// Defines `org-sbe` for formulas in the file whose text `text` gives. | ||
| 20 | static func defineSbe(_ lisp: Elisp, text: @escaping () -> String) { | ||
| 21 | lisp.defineForm("org-sbe") { _, args in | ||
| 22 | guard TableBlocks.allowed() else { throw Elisp.Unsupported(what: "org-sbe with source blocks locked") } | ||
| 23 | return .string(try sbe(args, text: text())) | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | /// The macro's value: `(org-trim (format "%S" result))`, or the result when it is a string. | ||
| 28 | static func sbe(_ args: [Sexp], text: String) throws -> String { | ||
| 29 | guard let first = args.first else { throw Elisp.Signal(message: "Wrong number of arguments: org-sbe, 0") } | ||
| 30 | let name: String | ||
| 31 | switch first { | ||
| 32 | case .string(let s): name = s | ||
| 33 | case .symbol(let s): name = s | ||
| 34 | default: throw Elisp.Unsupported(what: "org-sbe with a block name that isn't a symbol") | ||
| 35 | } | ||
| 36 | var variables = Array(args.dropFirst()) | ||
| 37 | var header = "" | ||
| 38 | if case .string(let s)? = variables.first { | ||
| 39 | header = s | ||
| 40 | variables.removeFirst() | ||
| 41 | } | ||
| 42 | var specs: [String] = [] | ||
| 43 | for variable in variables { | ||
| 44 | guard case .list(let items) = variable, case .symbol(let variableName)? = items.first else { | ||
| 45 | throw Elisp.Unsupported(what: "org-sbe with an argument that isn't (NAME VALUE)") | ||
| 46 | } | ||
| 47 | // A value after `$` is written as Lisp, so a string stays a string. | ||
| 48 | var quote = false | ||
| 49 | var values: [Sexp] = [] | ||
| 50 | for item in items.dropFirst() { | ||
| 51 | if item == .symbol("$") { | ||
| 52 | quote = true | ||
| 53 | continue | ||
| 54 | } | ||
| 55 | if quote { | ||
| 56 | values.append(.string(Elisp.printed(item, escape: true))) | ||
| 57 | } else if !Elisp.isNil(item) { | ||
| 58 | values.append(item) | ||
| 59 | } | ||
| 60 | quote = false | ||
| 61 | } | ||
| 62 | if values.count > 1 { | ||
| 63 | let read = try values.map { value -> Sexp in | ||
| 64 | guard case .string(let s) = value else { throw Elisp.Unsupported(what: "org-sbe with values that aren't text") } | ||
| 65 | do { return try LispReader.readFirst(s).sexp } catch { throw Elisp.Signal(message: "End of file during parsing") } | ||
| 66 | } | ||
| 67 | specs.append(variableName + "='" + Elisp.printed(.list(read), escape: true)) | ||
| 68 | } else { | ||
| 69 | specs.append(variableName + "=" + (try Elisp.format([.string("%s"), values.first ?? .nil]))) | ||
| 70 | } | ||
| 71 | } | ||
| 72 | guard !name.isEmpty else { return "" } | ||
| 73 | guard !name.contains(where: { "[]():\"".contains($0) }) else { throw Elisp.Unsupported(what: "org-sbe with the reference \(name)") } | ||
| 74 | var value = try sbeReference(name, header: header, arguments: splitArguments(specs.joined(separator: ", ")), text: text) | ||
| 75 | // `org-babel-ref-resolve` gives a symbol's name. | ||
| 76 | if case .symbol(let s) = value, !Elisp.isNil(value) { value = .string(s) } | ||
| 77 | // `:var results=` takes off a first row followed by a rule, as column names. | ||
| 78 | if case .list(let rows) = value, rows.count > 1, rows[0] != .symbol("hline"), rows[1] == .symbol("hline"), | ||
| 79 | !rows.dropFirst(2).contains(.symbol("hline")) { | ||
| 80 | value = rows.count > 2 ? .list(Array(rows.dropFirst(2))) : .nil | ||
| 81 | } | ||
| 82 | let printed = value.string ?? Elisp.printed(value, escape: true) | ||
| 83 | return printed.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r")) | ||
| 84 | } | ||
| 85 | |||
| 86 | /// `org-babel-ref-resolve` for `name[header](arguments)`: a src block's value, or a named | ||
| 87 | /// table or list. | ||
| 88 | static func sbeReference(_ name: String, header: String, arguments: [String], text: String) throws -> Sexp { | ||
| 89 | let ns = text as NSString | ||
| 90 | let model = DocumentModel(tree: OrgParser.parse(text)) | ||
| 91 | let options = Options() | ||
| 92 | // The first `#+NAME:` line with the name outside COMMENTed headings that names an | ||
| 93 | // element: a src block's, or another element's. The keyword's case doesn't matter; the | ||
| 94 | // name's does. | ||
| 95 | let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*(" + NSRegularExpression.escapedPattern(for: name) + ")[ \\t]*$" | ||
| 96 | let found = try NSRegularExpression(pattern: pattern).matches(in: text, range: NSRange(location: 0, length: ns.length)) | ||
| 97 | let matches = found.filter { ns.substring(with: $0.range(at: 1)) == name }.map(\.range) | ||
| 98 | let headingStarts = model.headings.map(\.headingRange.lowerBound) | ||
| 99 | func commented(_ location: Int) -> Bool { | ||
| 100 | guard let h = headingStarts.lastIndex(where: { $0 <= location }) else { return false } | ||
| 101 | return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") } | ||
| 102 | } | ||
| 103 | // A keyword followed by a blank line, after any other affiliated keywords, names nothing. | ||
| 104 | func orphaned(_ match: NSRange) -> Bool { | ||
| 105 | var location = NSMaxRange(ns.lineRange(for: match)) | ||
| 106 | while location < ns.length { | ||
| 107 | let line = ns.lineRange(for: NSRange(location: location, length: 0)) | ||
| 108 | let content = ns.substring(with: line) | ||
| 109 | if content.range(of: "(?i)^[ \\t]*#\\+(name|caption|header|plot|results|attr_[-\\w]+)(\\[.*\\])?:", options: .regularExpression) == nil { | ||
| 110 | return content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty | ||
| 111 | } | ||
| 112 | location = NSMaxRange(line) | ||
| 113 | } | ||
| 114 | return true | ||
| 115 | } | ||
| 116 | guard let named = matches.first(where: { !commented($0.location) && !orphaned($0) }) else { throw notFound(name, text: text) } | ||
| 117 | let start = named.location | ||
| 118 | let block = model.srcBlocks.first { block in | ||
| 119 | guard block.name == name, block.range.lowerBound > start else { return false } | ||
| 120 | let between = ns.substring(with: NSRange(location: start, length: block.range.lowerBound - start)) | ||
| 121 | return between.split(separator: "\n").allSatisfy { $0.trimmingCharacters(in: .whitespaces).hasPrefix("#+") } | ||
| 122 | } | ||
| 123 | guard let block else { | ||
| 124 | // `resolve` reads the first element with the name in any case, and runs a src block | ||
| 125 | // before it. | ||
| 126 | guard named == found.first?.range, !model.srcBlocks.contains(where: { $0.name == name }) else { | ||
| 127 | throw Elisp.Unsupported(what: "org-sbe with a name used more than once") | ||
| 128 | } | ||
| 129 | do { | ||
| 130 | return try sbeSexp(resolve(name, model: model, text: ns, refs: References(resolved: [:], options: options))) | ||
| 131 | } catch let failure as Failure { | ||
| 132 | throw sbeError(failure, text: text) | ||
| 133 | } | ||
| 134 | } | ||
| 135 | let params: Params | ||
| 136 | do { | ||
| 137 | params = try Params(block: block, model: model, text: ns, extra: [Params.parse(header) + arguments.map { (":var", $0) }]) | ||
| 138 | } catch let failure as Failure { | ||
| 139 | throw sbeError(failure, text: text) | ||
| 140 | } | ||
| 141 | if params.single[":cache"] == "yes" { throw Elisp.Unsupported(what: "org-sbe with :cache") } | ||
| 142 | var refs = References(resolved: [:], options: options) | ||
| 143 | refs.visiting = [name] | ||
| 144 | // The blocks its `:var`s refer to run first, as `DocumentSession.runBabel` runs them. | ||
| 145 | while true { | ||
| 146 | switch plan(block, params: params, model: model, text: ns, options: options, location: block.range, name: name, refs: refs, useCache: false) { | ||
| 147 | case .failure(let failure): | ||
| 148 | throw sbeError(failure, text: text) | ||
| 149 | case .success(let job): | ||
| 150 | if job.needsFile { throw Elisp.Unsupported(what: "org-sbe with Lisp that needs the file's name") } | ||
| 151 | if let need = job.needs.first { | ||
| 152 | refs.resolved[need.reference] = varValue(need.job.finish, try sbeRun(need.job)) | ||
| 153 | continue | ||
| 154 | } | ||
| 155 | // `org-babel-emacs-lisp-lexical`: "yes" and "t" are lexical; other Lisp is read. | ||
| 156 | let lexical: Bool | ||
| 157 | switch params.single[":lexical"] { | ||
| 158 | case "yes", "t": lexical = true | ||
| 159 | case nil, "no", "nil": lexical = false | ||
| 160 | default: throw Elisp.Unsupported(what: "org-sbe with this :lexical") | ||
| 161 | } | ||
| 162 | return try sbeValue(job, lexical: lexical) | ||
| 163 | } | ||
| 164 | } | ||
| 165 | } | ||
| 166 | |||
| 167 | /// A block a reference needs, run as `Babel.evaluateNatively` or in JavaScriptCore. | ||
| 168 | static func sbeRun(_ job: BabelJob) throws -> BabelOutput { | ||
| 169 | if job.lispForm != nil { | ||
| 170 | do { | ||
| 171 | guard let output = try evaluateNatively(job) else { throw Elisp.Unsupported(what: "org-sbe with Lisp only Emacs runs") } | ||
| 172 | return output | ||
| 173 | } catch let Failure.message(message) { | ||
| 174 | // An error in the block. | ||
| 175 | throw Elisp.Signal(message: message) | ||
| 176 | } | ||
| 177 | } | ||
| 178 | guard job.language == "js" || job.language == "javascript" else { throw Elisp.Unsupported(what: "org-sbe with \(job.language) blocks") } | ||
| 179 | guard let output = try? TableBlocks.javaScript?(job), output.status == 0 else { throw Elisp.Unsupported(what: "org-sbe with js blocks") } | ||
| 180 | return output | ||
| 181 | } | ||
| 182 | |||
| 183 | /// The block's value as `org-babel-execute-src-block` returns it. | ||
| 184 | static func sbeValue(_ job: BabelJob, lexical: Bool) throws -> Sexp { | ||
| 185 | let params = job.finish.params | ||
| 186 | if params.contains("file") || job.finish.colnames != nil || job.finish.rownames != nil { | ||
| 187 | throw Elisp.Unsupported(what: "org-sbe with this block's results") | ||
| 188 | } | ||
| 189 | let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code") | ||
| 190 | || params.contains("pp") || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table")) | ||
| 191 | var result: Sexp | ||
| 192 | if let form = job.lispForm { | ||
| 193 | // `org-babel-execute:emacs-lisp`: dynamic binding unless `:lexical` is yes or t. | ||
| 194 | let lisp = Elisp() | ||
| 195 | lisp.lexical = lexical | ||
| 196 | lisp.syntax = .emacsLisp | ||
| 197 | lisp.standardTime() | ||
| 198 | result = try lisp.eval(try LispReader.readFirst(form).sexp) | ||
| 199 | if Elisp.containsClosure(result) { throw Elisp.Unsupported(what: "org-sbe with a function value") } | ||
| 200 | if scalar { | ||
| 201 | result = .string(params.contains("scalar") || params.contains("verbatim") ? Elisp.printed(result, escape: true) : try Elisp.format([.string("%s"), result])) | ||
| 202 | } | ||
| 203 | } else { | ||
| 204 | // `org-babel-js-read`: a number, a string, or the symbol a quoted word reads as. | ||
| 205 | let raw = rawResult(job.finish, try sbeRun(job)) | ||
| 206 | if scalar { | ||
| 207 | result = .string(raw) | ||
| 208 | } else if raw.hasPrefix("(") || raw.hasPrefix("[") || raw.hasPrefix("`") || raw.contains("\\") { | ||
| 209 | throw Elisp.Unsupported(what: "org-sbe with this js value") | ||
| 210 | } else if raw.hasPrefix("'") { | ||
| 211 | guard let m = raw.firstMatch(of: /^'([A-Za-z0-9_-]+)(?:'|\s)/) else { throw Elisp.Unsupported(what: "org-sbe with this js value") } | ||
| 212 | result = try number(String(m.1)).map { try LispReader.readFirst($0).sexp } ?? .symbol(String(m.1)) | ||
| 213 | } else if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 { | ||
| 214 | result = .string(String(raw.dropFirst().dropLast())) | ||
| 215 | } else { | ||
| 216 | result = try number(raw).map { try LispReader.readFirst($0).sexp } ?? .string(raw) | ||
| 217 | } | ||
| 218 | } | ||
| 219 | if params.contains("discard") { return .nil } | ||
| 220 | if !job.finish.output, params.contains("vector") || params.contains("table") { | ||
| 221 | if case .list = result {} else if !Elisp.isNil(result) { result = .list([.list([result])]) } | ||
| 222 | } | ||
| 223 | return result | ||
| 224 | } | ||
| 225 | |||
| 226 | /// A named table or list as `org-babel-read-element` reads it. | ||
| 227 | static func sbeSexp(_ value: VarValue) throws -> Sexp { | ||
| 228 | func cell(_ c: Cell) throws -> Sexp { | ||
| 229 | switch c { | ||
| 230 | case .text(let s): return .string(s) | ||
| 231 | case .number(let n): return try LispReader.readFirst(n).sexp | ||
| 232 | } | ||
| 233 | } | ||
| 234 | switch value { | ||
| 235 | case .scalar(let s): return .string(s) | ||
| 236 | case .number(let n): return try LispReader.readFirst(n).sexp | ||
| 237 | case .list(let items): return .list(try items.map(cell)) | ||
| 238 | case .table(let rows): return .list(try rows.map { row in try row.map { .list(try $0.map(cell)) } ?? .symbol("hline") }) | ||
| 239 | } | ||
| 240 | } | ||
| 241 | |||
| 242 | /// A reference to nothing is an error; to an ID, which only Emacs looks up, unsupported. | ||
| 243 | static func notFound(_ name: String, text: String) -> Error { | ||
| 244 | let pattern = "(?im)^[ \\t]*:(custom_)?id:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$" | ||
| 245 | if text.range(of: pattern, options: .regularExpression) != nil { return Elisp.Unsupported(what: "org-sbe with an ID reference") } | ||
| 246 | return Elisp.Signal(message: "Reference ‘\(name)’ not found in this buffer") | ||
| 247 | } | ||
| 248 | |||
| 249 | /// What a planning failure is in Emacs: a reference to nothing is an error, the rest | ||
| 250 | /// unsupported here. | ||
| 251 | static func sbeError(_ failure: Failure, text: String) -> Error { | ||
| 252 | guard case .message(let message) = failure, let m = message.firstMatch(of: /^Can't find (.+) for :var\.$/) else { | ||
| 253 | return Elisp.Unsupported(what: "org-sbe with a block orgstar can't run") | ||
| 254 | } | ||
| 255 | return notFound(String(m.1), text: text) | ||
| 256 | } | ||
| 257 | } | ||
Sources/OrgCore/Config/Elisp.swift +29 −9
| @@ -46,10 +46,13 @@ public final class Elisp { | |||
| 46 | /// `lexical-binding`: lambdas close over the local frames, and only special variables | 46 | /// `lexical-binding`: lambdas close over the local frames, and only special variables |
| 47 | /// (the host's and `defvar`'s) are bound dynamically. | 47 | /// (the host's and `defvar`'s) are bound dynamically. |
| 48 | public var lexical = false | 48 | public var lexical = false |
| 49 | /// A variable with no value throws `Unsupported` rather than `void-variable`: Emacs may | ||
| 50 | /// give it one, such as `fill-column`. | ||
| 51 | public var unboundUnsupported = false | ||
| 49 | /// Variables bound dynamically when `lexical` is set. | 52 | /// Variables bound dynamically when `lexical` is set. |
| 50 | var specials: Set<String> = [] | 53 | var specials: Set<String> = [] |
| 51 | /// Under lexical binding, running a lambda list, which Emacs evaluates with dynamic binding: | 54 | /// Under lexical binding, running a lambda list, which Emacs evaluates with dynamic binding: |
| 52 | /// every variable is bound dynamically and lambdas aren't closures. | 55 | /// every variable is bound dynamically and lambdas capture nothing. |
| 53 | private var dynamicOnly = false | 56 | private var dynamicOnly = false |
| 54 | /// The functions `defun` defined, which may take closures. | 57 | /// The functions `defun` defined, which may take closures. |
| 55 | var defined: Set<String> = [] | 58 | var defined: Set<String> = [] |
| @@ -68,6 +71,8 @@ public final class Elisp { | |||
| 68 | didSet { regexes = [:] } | 71 | didSet { regexes = [:] } |
| 69 | } | 72 | } |
| 70 | private var functions: [String: Builtin] = [:] | 73 | private var functions: [String: Builtin] = [:] |
| 74 | /// Forms the host defines, given their arguments unevaluated. | ||
| 75 | private var forms: [String: Builtin] = [:] | ||
| 71 | var steps = 0 | 76 | var steps = 0 |
| 72 | static let stepLimit = 1_000_000 | 77 | static let stepLimit = 1_000_000 |
| 73 | /// Nested evaluations, as `max-lisp-eval-depth` limits them. | 78 | /// Nested evaluations, as `max-lisp-eval-depth` limits them. |
| @@ -95,6 +100,9 @@ public final class Elisp { | |||
| 95 | /// Defines or replaces a function. | 100 | /// Defines or replaces a function. |
| 96 | public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function } | 101 | public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function } |
| 97 | 102 | ||
| 103 | /// Defines a macro by its value: `form` gets the arguments unevaluated. | ||
| 104 | public func defineForm(_ name: String, _ form: @escaping Builtin) { forms[name] = form } | ||
| 105 | |||
| 98 | /// Sets a global variable, which is special. | 106 | /// Sets a global variable, which is special. |
| 99 | public func set(_ name: String, _ value: Sexp) { | 107 | public func set(_ name: String, _ value: Sexp) { |
| 100 | scopes[0].vars[name] = value | 108 | scopes[0].vars[name] = value |
| @@ -107,6 +115,7 @@ public final class Elisp { | |||
| 107 | if v == Self.unknownError { throw Unsupported(what: "the data of this error") } | 115 | if v == Self.unknownError { throw Unsupported(what: "the data of this error") } |
| 108 | return v | 116 | return v |
| 109 | } | 117 | } |
| 118 | if unboundUnsupported { throw Unsupported(what: "variable \(name)") } | ||
| 110 | throw Signal(message: "Symbol’s value as variable is void: \(name)", data: [.symbol(name)]) | 119 | throw Signal(message: "Symbol’s value as variable is void: \(name)", data: [.symbol(name)]) |
| 111 | } | 120 | } |
| 112 | 121 | ||
| @@ -143,11 +152,19 @@ public final class Elisp { | |||
| 143 | scopes[0].vars[name] = v | 152 | scopes[0].vars[name] = v |
| 144 | } | 153 | } |
| 145 | 154 | ||
| 155 | /// The ids in `closures` of functions made under dynamic binding, which capture nothing. | ||
| 156 | var dynamicClosures: Set<Int> = [] | ||
| 157 | |||
| 146 | /// A lambda as `function` makes it: a closure over the local frames under lexical | 158 | /// A lambda as `function` makes it: a closure over the local frames under lexical |
| 147 | /// binding, else the list itself. | 159 | /// binding, else one that captures nothing. Emacs 31 makes both function objects, not lists. |
| 148 | func closure(_ lambda: Sexp) -> Sexp { | 160 | func closure(_ lambda: Sexp) -> Sexp { |
| 149 | guard lexical, !dynamicOnly, case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda } | 161 | guard case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda } |
| 150 | closures.append(Array(scopes.dropFirst())) | 162 | if lexical, !dynamicOnly { |
| 163 | closures.append(Array(scopes.dropFirst())) | ||
| 164 | } else { | ||
| 165 | closures.append([]) | ||
| 166 | dynamicClosures.insert(closures.count - 1) | ||
| 167 | } | ||
| 151 | return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst()) | 168 | return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst()) |
| 152 | } | 169 | } |
| 153 | 170 | ||
| @@ -161,7 +178,7 @@ public final class Elisp { | |||
| 161 | static let closureArguments: [String: Int] = [ | 178 | static let closureArguments: [String: Int] = [ |
| 162 | "funcall": 0, "apply": 0, "mapcar": 0, "mapc": 0, "mapconcat": 0, "seq-map": 0, "seq-filter": 0, "seq-remove": 0, | 179 | "funcall": 0, "apply": 0, "mapcar": 0, "mapc": 0, "mapconcat": 0, "seq-map": 0, "seq-filter": 0, "seq-remove": 0, |
| 163 | "seq-reduce": 0, "cl-reduce": 0, "cl-remove-if": 0, "cl-remove-if-not": 0, "cl-find": 1, "cl-position": 1, "sort": 0, | 180 | "seq-reduce": 0, "cl-reduce": 0, "cl-remove-if": 0, "cl-remove-if-not": 0, "cl-find": 1, "cl-position": 1, "sort": 0, |
| 164 | "replace-regexp-in-string": 1, "list": 0, "identity": 0, "ignore": 0, "null": 0, "not": 0, | 181 | "replace-regexp-in-string": 1, "org-lookup-first": 3, "org-lookup-last": 3, "org-lookup-all": 3, "list": 0, "identity": 0, "ignore": 0, "null": 0, "not": 0, |
| 165 | ] | 182 | ] |
| 166 | /// Builtins that compare or print what lists hold. | 183 | /// Builtins that compare or print what lists hold. |
| 167 | static let closureInspectors: Set<String> = [ | 184 | static let closureInspectors: Set<String> = [ |
| @@ -316,15 +333,16 @@ public final class Elisp { | |||
| 316 | } | 333 | } |
| 317 | } | 334 | } |
| 318 | 335 | ||
| 319 | /// `prin1-to-string` with `princ` for strings when `escape` is false. | 336 | /// `prin1-to-string`, or `princ` when `escape` is false. |
| 320 | public static func printed(_ v: Sexp, escape: Bool = false) -> String { | 337 | public static func printed(_ v: Sexp, escape: Bool = false) -> String { |
| 321 | switch v { | 338 | switch v { |
| 322 | case .string(let s): return escape ? "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" : s | 339 | case .string(let s): return escape ? "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" : s |
| 323 | case .float(let d): return floatText(d) | 340 | case .float(let d): return floatText(d) |
| 324 | case .character(let c): return String(c) | 341 | case .character(let c): return String(c) |
| 325 | case .list(let items): return "(" + items.map { printed($0, escape: true) }.joined(separator: " ") + ")" | 342 | case .list(let items) where items.isEmpty: return "nil" |
| 326 | case .dotted(let items, let last): return "(" + items.map { printed($0, escape: true) }.joined(separator: " ") + " . " + printed(last, escape: true) + ")" | 343 | case .list(let items): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + ")" |
| 327 | case .vector(let items): return "[" + items.map { printed($0, escape: true) }.joined(separator: " ") + "]" | 344 | case .dotted(let items, let last): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + " . " + printed(last, escape: escape) + ")" |
| 345 | case .vector(let items): return "[" + items.map { printed($0, escape: escape) }.joined(separator: " ") + "]" | ||
| 328 | default: return v.description | 346 | default: return v.description |
| 329 | } | 347 | } |
| 330 | } | 348 | } |
| @@ -375,6 +393,7 @@ public final class Elisp { | |||
| 375 | } | 393 | } |
| 376 | let args = Array(items.dropFirst()) | 394 | let args = Array(items.dropFirst()) |
| 377 | if let value = try special(name, args) { return value } | 395 | if let value = try special(name, args) { return value } |
| 396 | if let form = forms[name] { return try form(self, args) } | ||
| 378 | // The function first, so an unknown one, or a macro this evaluator lacks, is | 397 | // The function first, so an unknown one, or a macro this evaluator lacks, is |
| 379 | // unsupported rather than an error from its arguments. | 398 | // unsupported rather than an error from its arguments. |
| 380 | guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } | 399 | guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } |
| @@ -566,6 +585,7 @@ public final class Elisp { | |||
| 566 | case .symbol(let name): return try callNamed(name, args) | 585 | case .symbol(let name): return try callNamed(name, args) |
| 567 | case .list(let items) where Self.isClosure(function): | 586 | case .list(let items) where Self.isClosure(function): |
| 568 | guard closures.indices.contains(items[1].integer!) else { throw Unsupported(what: "a closure as a list") } | 587 | guard closures.indices.contains(items[1].integer!) else { throw Unsupported(what: "a closure as a list") } |
| 588 | if dynamicClosures.contains(items[1].integer!) { return try call(.list([.symbol("lambda")] + items.dropFirst(2)), args) } | ||
| 569 | let saved = dynamicOnly | 589 | let saved = dynamicOnly |
| 570 | dynamicOnly = false | 590 | dynamicOnly = false |
| 571 | defer { dynamicOnly = saved } | 591 | defer { dynamicOnly = saved } |
Sources/OrgCore/Links/Links.swift +20
| @@ -272,6 +272,26 @@ public struct OpenLinkAtPoint: OrgCommand { | |||
| 272 | } | 272 | } |
| 273 | } | 273 | } |
| 274 | 274 | ||
| 275 | extension 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 | EmacsBuffer.defineLookups(lisp) | ||
| 282 | lisp.unboundUnsupported = true | ||
| 283 | do { | ||
| 284 | let value = try lisp.eval(try LispReader.readFirst(form).sexp) | ||
| 285 | if Elisp.containsClosure(value) { return "This link uses Emacs Lisp that runs only in Emacs." } | ||
| 286 | return "\(form) => \(try Elisp.format([.string("%s"), value]))" | ||
| 287 | } catch is Elisp.Unsupported { | ||
| 288 | return "This link uses Emacs Lisp that runs only in Emacs." | ||
| 289 | } catch { | ||
| 290 | return "\(error)" | ||
| 291 | } | ||
| 292 | } | ||
| 293 | } | ||
| 294 | |||
| 275 | extension Links { | 295 | extension Links { |
| 276 | /// `org-at-date-range-p` with INACTIVE-OK: the range starting at one of the two brackets | 296 | /// `org-at-date-range-p` with INACTIVE-OK: the range starting at one of the two brackets |
| 277 | /// back from `offset` that reaches it. | 297 | /// back from `offset` that reaches it. |
Sources/OrgPrograms/EmacsRunner.swift +72
| @@ -36,11 +36,17 @@ public enum EmacsRunner { | |||
| 36 | let script = folder.appendingPathComponent("recalc.el") | 36 | let script = folder.appendingPathComponent("recalc.el") |
| 37 | try text.write(to: input, atomically: true, encoding: .utf8) | 37 | try text.write(to: input, atomically: true, encoding: .utf8) |
| 38 | func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" } | 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 | """ : "" | ||
| 39 | try """ | 44 | try """ |
| 40 | ;;; -*- lexical-binding: t -*- | 45 | ;;; -*- lexical-binding: t -*- |
| 41 | (require 'org) | 46 | (require 'org) |
| 42 | (require 'org-table) | 47 | (require 'org-table) |
| 43 | (setq enable-local-variables :safe) | 48 | (setq enable-local-variables :safe) |
| 49 | \(blocks) | ||
| 44 | (with-temp-buffer | 50 | (with-temp-buffer |
| 45 | (let ((coding-system-for-read 'utf-8-unix)) | 51 | (let ((coding-system-for-read 'utf-8-unix)) |
| 46 | (insert-file-contents \(lisp(input.path)))) | 52 | (insert-file-contents \(lisp(input.path)))) |
| @@ -82,6 +88,72 @@ public enum EmacsRunner { | |||
| 82 | return String(decoding: data, as: UTF8.self) | 88 | return String(decoding: data, as: UTF8.self) |
| 83 | } | 89 | } |
| 84 | 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 | |||
| 85 | /// Exports `text`, the buffer of the file at `path`, with an ox function such as | 157 | /// Exports `text`, the buffer of the file at `path`, with an ox function such as |
| 86 | /// `org-latex-export-to-pdf`. The file is written beside `path`, as Emacs does; source | 158 | /// `org-latex-export-to-pdf`. The file is written beside `path`, as Emacs does; source |
| 87 | /// blocks are not run. Returns the path Emacs wrote. | 159 | /// blocks are not run. Returns the path Emacs wrote. |
Sources/OrgPrograms/Programs.swift +6
| @@ -33,5 +33,11 @@ public struct Programs: ProgramRunning { | |||
| 33 | public func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String { | 33 | public func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String { |
| 34 | try await EmacsRunner.recalculateTable(text: text, directory: directory, table: table, point: point, form: form) | 34 | try await EmacsRunner.recalculateTable(text: text, directory: directory, table: table, point: point, form: form) |
| 35 | } | 35 | } |
| 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 | } | ||
| 36 | } | 42 | } |
| 37 | #endif | 43 | #endif |
Sources/Orgstar/ContentView.swift +32 −3
| @@ -1049,7 +1049,7 @@ struct ContentView: View { | |||
| 1049 | private func runExternal(_ request: ExternalRequest) { | 1049 | private func runExternal(_ request: ExternalRequest) { |
| 1050 | switch request { | 1050 | switch request { |
| 1051 | case .openLink(let link): | 1051 | 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) } |
| 1053 | // `org-occur` for a regexp link, once the editor shows the file. | 1053 | // `org-occur` for a regexp link, once the editor shows the file. |
| 1054 | if let regexp = Links.regexpSearch(link) { | 1054 | if let regexp = Links.regexpSearch(link) { |
| 1055 | DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) } | 1055 | DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) } |
| @@ -1068,6 +1068,10 @@ struct ContentView: View { | |||
| 1068 | case .emacsTable(_, _, _, let reason, _, let formula, let partial): | 1068 | case .emacsTable(_, _, _, let reason, _, let formula, let partial): |
| 1069 | // The fields written before the formula stay, as Emacs leaves them when a formula fails. | 1069 | // The fields written before the formula stay, as Emacs leaves them when a formula fails. |
| 1070 | if let partial { commands.editor?.perform(PrecomputedEdit(partial)) } | 1070 | if let partial { commands.editor?.perform(PrecomputedEdit(partial)) } |
| 1071 | if reason == TableBlocks.lockedReason { | ||
| 1072 | ProAccess.shared.allows(.babel) | ||
| 1073 | return | ||
| 1074 | } | ||
| 1071 | if let formula { | 1075 | if let formula { |
| 1072 | commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't")) | 1076 | commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't")) |
| 1073 | } else { | 1077 | } else { |
| @@ -1075,6 +1079,13 @@ struct ContentView: View { | |||
| 1075 | } | 1079 | } |
| 1076 | #else | 1080 | #else |
| 1077 | case .emacsTable(let table, let point, let form, let reason, let lisp, let formula, let partial): | 1081 | case .emacsTable(let table, let point, let form, let reason, let lisp, let formula, let partial): |
| 1082 | // Emacs runs the blocks `org-sbe` names without asking, so they need Babel, and | ||
| 1083 | // the question below each time. | ||
| 1084 | let blocks = reason == TableBlocks.lockedReason || session.document?.text.contains("org-sbe") == true | ||
| 1085 | if blocks, !ProAccess.shared.allows(.babel) { | ||
| 1086 | if let partial { commands.editor?.perform(PrecomputedEdit(partial)) } | ||
| 1087 | return | ||
| 1088 | } | ||
| 1078 | guard EmacsRunner.executable() != nil else { | 1089 | guard EmacsRunner.executable() != nil else { |
| 1079 | // Without Emacs this is the App Store build's case: keep the fields written so far. | 1090 | // Without Emacs this is the App Store build's case: keep the fields written so far. |
| 1080 | if let partial { commands.editor?.perform(PrecomputedEdit(partial)) } | 1091 | if let partial { commands.editor?.perform(PrecomputedEdit(partial)) } |
| @@ -1089,8 +1100,9 @@ struct ContentView: View { | |||
| 1089 | } | 1100 | } |
| 1090 | guard lisp, let path = session.path, let text = session.document?.text else { return run() } | 1101 | guard lisp, let path = session.path, let text = session.document?.text else { return run() } |
| 1091 | let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound)) | 1102 | let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound)) |
| 1092 | if trust.isTrusted(path: path, content: content) { return run() } | 1103 | if !blocks, trust.isTrusted(path: path, content: content) { return run() } |
| 1093 | commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in | 1104 | let message = blocks ? "This table's formulas run Lisp and source blocks. Run them? (yes, no)" : "This table's formulas run Lisp. Run them? (yes, no, always)" |
| 1105 | commands.ask(Prompt(key: "confirm", message: message, choices: blocks ? ["yes", "no"] : ["yes", "no", "always"])) { answer in | ||
| 1094 | switch answer { | 1106 | switch answer { |
| 1095 | case "always": | 1107 | case "always": |
| 1096 | trust.trust(path: path, content: content) | 1108 | trust.trust(path: path, content: content) |
| @@ -1122,6 +1134,23 @@ struct ContentView: View { | |||
| 1122 | } | 1134 | } |
| 1123 | } | 1135 | } |
| 1124 | 1136 | ||
| 1137 | /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does. | ||
| 1138 | private func runElispLink(_ form: String) { | ||
| 1139 | let run = { _ = Task { commands.show(await session.evaluateLink(form)) } } | ||
| 1140 | let content = "elisp:" + form | ||
| 1141 | if let path = session.path, trust.isTrusted(path: path, content: content) { return run() } | ||
| 1142 | let choices = session.path == nil ? ["yes", "no"] : ["yes", "no", "always"] | ||
| 1143 | commands.ask(Prompt(key: "confirm", message: "Execute \(form) as Elisp? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in | ||
| 1144 | switch answer { | ||
| 1145 | case "always": | ||
| 1146 | if let path = session.path { trust.trust(path: path, content: content) } | ||
| 1147 | run() | ||
| 1148 | case "yes": run() | ||
| 1149 | default: commands.show("Not run") | ||
| 1150 | } | ||
| 1151 | } | ||
| 1152 | } | ||
| 1153 | |||
| 1125 | private struct ReminderKey: Equatable { | 1154 | private struct ReminderKey: Equatable { |
| 1126 | var enabled: Bool | 1155 | var enabled: Bool |
| 1127 | var lead: Int | 1156 | var lead: Int |
Sources/Orgstar/LinkOpener.swift +7 −2
| @@ -6,8 +6,9 @@ import OrgCore | |||
| 6 | @MainActor | 6 | @MainActor |
| 7 | enum LinkOpener { | 7 | enum LinkOpener { |
| 8 | /// Returns a message when the link can't be followed. | 8 | /// Returns a message when the link can't be followed. |
| 9 | /// `ask` picks among a query link's matches. | 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) -> String? { | 10 | static func open(_ link: OrgLink, session: DocumentSession, workspace: WorkspaceModel, ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, |
| 11 | elisp: ((String) -> Void)? = nil) -> String? { | ||
| 11 | #if APPSTORE | 12 | #if APPSTORE |
| 12 | // A file outside the sidebar's folders needs access to its folder first. | 13 | // A file outside the sidebar's folders needs access to its folder first. |
| 13 | if link.type == "file", !link.path.isEmpty, | 14 | if link.type == "file", !link.path.isEmpty, |
| @@ -26,6 +27,10 @@ enum LinkOpener { | |||
| 26 | _ = open(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]), session: session, workspace: workspace, ask: ask) | 27 | _ = open(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]), session: session, workspace: workspace, ask: ask) |
| 27 | } | 28 | } |
| 28 | return nil | 29 | 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 | ||
| 29 | } | 34 | } |
| 30 | } | 35 | } |
| 31 | } | 36 | } |
Sources/Orgstar/OrgstarApp.swift +2
| @@ -384,6 +384,8 @@ struct OrgstarApp: App { | |||
| 384 | MacPro.resolve() | 384 | MacPro.resolve() |
| 385 | MacPro.renewInBackground() | 385 | MacPro.renewInBackground() |
| 386 | #endif | 386 | #endif |
| 387 | // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do. | ||
| 388 | TableBlocks.allowed = { ProAccess.isUnlockedNow } | ||
| 387 | // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console. | 389 | // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console. |
| 388 | #if DEBUG | 390 | #if DEBUG |
| 389 | Perf.watchMainThread() | 391 | Perf.watchMainThread() |
Sources/OrgstarMobile/EditorScreen.swift +14
| @@ -486,6 +486,20 @@ extension EditorScreen { | |||
| 486 | guard let answer, let index = labels.firstIndex(of: answer) else { return } | 486 | guard let answer, let index = labels.firstIndex(of: answer) else { return } |
| 487 | follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index])) | 487 | follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index])) |
| 488 | } | 488 | } |
| 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 | } | ||
| 489 | } | 503 | } |
| 490 | } | 504 | } |
| 491 | 505 | ||
Sources/OrgstarMobile/MobileEditor.swift +5
| @@ -337,6 +337,11 @@ final class MobileEditor: NSObject, DocumentBuffer { | |||
| 337 | // The fields written before a formula only Emacs can do stay, as Emacs leaves them | 337 | // The fields written before a formula only Emacs can do stay, as Emacs leaves them |
| 338 | // when a formula fails. | 338 | // when a formula fails. |
| 339 | if case .emacsTable(_, _, _, _, _, _, let partial?) = request { _ = perform(PrecomputedEdit(partial)) } | 339 | if case .emacsTable(_, _, _, _, _, _, let partial?) = request { _ = perform(PrecomputedEdit(partial)) } |
| 340 | // `org-sbe` without Babel shows its paywall. | ||
| 341 | if case .emacsTable(_, _, _, TableBlocks.lockedReason, _, _, _) = request { | ||
| 342 | ProAccess.shared.allows(.babel) | ||
| 343 | return step | ||
| 344 | } | ||
| 340 | onMessage?(Self.unavailable(request, title: command.title)) | 345 | onMessage?(Self.unavailable(request, title: command.title)) |
| 341 | } | 346 | } |
| 342 | return step | 347 | return step |
Sources/OrgstarMobile/MobileModel.swift +2
| @@ -72,6 +72,8 @@ final class MobileModel { | |||
| 72 | UserConfig.directoryOverride = folder | 72 | UserConfig.directoryOverride = folder |
| 73 | let (problems, colors) = Self.readConfig(folder) | 73 | let (problems, colors) = Self.readConfig(folder) |
| 74 | let settings = OrgPreferences.orgSettings() | 74 | let settings = OrgPreferences.orgSettings() |
| 75 | // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do. | ||
| 76 | TableBlocks.allowed = { ProAccess.isUnlockedNow } | ||
| 75 | do { | 77 | do { |
| 76 | let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings)) | 78 | let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings)) |
| 77 | // Recently Deleted where the folder's provider keeps one (iCloud Drive); otherwise gone. | 79 | // Recently Deleted where the folder's provider keeps one (iCloud Drive); otherwise gone. |
Sources/OrgstarMobile/ReaderScreen.swift +1
| @@ -384,6 +384,7 @@ struct ReaderScreen: View { | |||
| 384 | case .openExternally(let target): openURL(target) | 384 | case .openExternally(let target): openURL(target) |
| 385 | case .message(let text): message = text | 385 | case .message(let text): message = text |
| 386 | case .choose(let question, let paths): message = question + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ") | 386 | 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." | ||
| 387 | } | 388 | } |
| 388 | return .handled | 389 | return .handled |
| 389 | } | 390 | } |
Tests/OrgAppTests/AppTests.swift +4
| @@ -1323,6 +1323,10 @@ struct LinkFollowTests { | |||
| 1323 | #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!)) | 1323 | #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!)) |
| 1324 | #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!)) | 1324 | #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!)) |
| 1325 | #expect(follow("shell:rm -rf x") == .message("orgstar doesn't run shell links")) | 1325 | #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") | ||
| 1326 | } | 1330 | } |
| 1327 | 1331 | ||
| 1328 | @Test func followsDenoteLinks() async throws { | 1332 | @Test func followsDenoteLinks() async throws { |
Tests/OrgAppTests/JavaScriptBlocksTests.swift +76
| @@ -266,4 +266,80 @@ struct JavaScriptBlocksTests { | |||
| 266 | let interval = try Self.plan("#+begin_src js :results output\nsetInterval(() => {}, 10)\n#+end_src\n") | 266 | let interval = try Self.plan("#+begin_src js :results output\nsetInterval(() => {}, 10)\n#+end_src\n") |
| 267 | await #expect(throws: JavaScriptBlocks.Stopped.self) { try await JavaScriptBlocks.run(interval, directory: folder, timeout: .milliseconds(100)) } | 267 | await #expect(throws: JavaScriptBlocks.Stopped.self) { try await JavaScriptBlocks.run(interval, directory: folder, timeout: .milliseconds(100)) } |
| 268 | } | 268 | } |
| 269 | |||
| 270 | /// A block `org-sbe` runs that doesn't finish is stopped, so recalculating can't hang. | ||
| 271 | @Test func runHereStopsAtItsDeadline() throws { | ||
| 272 | let start = ContinuousClock.now | ||
| 273 | let interval = try Self.plan("#+begin_src js\nsetInterval(() => {}, 10)\n#+end_src\n") | ||
| 274 | #expect(throws: JavaScriptBlocks.Stopped.self) { try JavaScriptBlocks.runHere(interval, timeout: .milliseconds(100)) } | ||
| 275 | #expect(ContinuousClock.now - start < .seconds(2)) | ||
| 276 | let quick = try Self.plan("#+begin_src js\nreturn 6*7\n#+end_src\n") | ||
| 277 | #expect(try JavaScriptBlocks.runHere(quick)?.stdout.contains("42") == true) | ||
| 278 | } | ||
| 279 | |||
| 280 | /// A block whose earlier run timed out and still runs isn't started again, so a later | ||
| 281 | /// recalculation neither waits nor leaves another thread busy; once it ends it runs again. | ||
| 282 | @Test func runHereRefusesABlockStillRunning() throws { | ||
| 283 | let spin = try Self.plan("#+begin_src js\nconst end = Date.now() + 1500; while (Date.now() < end) {}\nreturn 7\n#+end_src\n") | ||
| 284 | #expect(throws: JavaScriptBlocks.Stopped.self) { try JavaScriptBlocks.runHere(spin, timeout: .milliseconds(100)) } | ||
| 285 | let start = ContinuousClock.now | ||
| 286 | #expect(throws: JavaScriptBlocks.Stopped.self) { try JavaScriptBlocks.runHere(spin, timeout: .seconds(5)) } | ||
| 287 | #expect(ContinuousClock.now - start < .milliseconds(500)) | ||
| 288 | Thread.sleep(forTimeInterval: 2) | ||
| 289 | #expect(try JavaScriptBlocks.runHere(spin)?.stdout.contains("7") == true) | ||
| 290 | } | ||
| 291 | |||
| 292 | /// `org-sbe` on js blocks in a table formula, as Emacs runs them with node. | ||
| 293 | @Test(.enabled(if: oracle && nodeInstalled)) | ||
| 294 | func tableFormulasMatchEmacs() throws { | ||
| 295 | TableBlocks.javaScript = { try JavaScriptBlocks.runHere($0) } | ||
| 296 | let text = """ | ||
| 297 | #+NAME: sq | ||
| 298 | #+begin_src js :var n=2 | ||
| 299 | return n*n | ||
| 300 | #+end_src | ||
| 301 | |||
| 302 | #+NAME: hi | ||
| 303 | #+begin_src js :var who="x" | ||
| 304 | return 'hi ' + who | ||
| 305 | #+end_src | ||
| 306 | |||
| 307 | #+NAME: quote | ||
| 308 | #+begin_src js :var who="x" | ||
| 309 | return who + "'s" | ||
| 310 | #+end_src | ||
| 311 | |||
| 312 | #+NAME: out | ||
| 313 | #+begin_src js :results output :var n=1 | ||
| 314 | console.log(' n is', n) | ||
| 315 | #+end_src | ||
| 316 | |||
| 317 | #+NAME: obj | ||
| 318 | #+begin_src js | ||
| 319 | return {a: 1} | ||
| 320 | #+end_src | ||
| 321 | |||
| 322 | | n | sq | hi | hi$ | quote | out | obj | | ||
| 323 | |---+----+----+-----+-------+-----+-----| | ||
| 324 | | 3 | | | | | | | | ||
| 325 | | abc | | | | | | | | ||
| 326 | | 2.5 | | | | | | | | ||
| 327 | #+TBLFM: $2='(org-sbe sq (n $1))::$3='(org-sbe hi (who $1))::$4='(org-sbe hi (who $$1))::$5='(org-sbe quote (who $$1))::$6='(org-sbe out (n $1))::$7='(org-sbe obj) | ||
| 328 | |||
| 329 | """ | ||
| 330 | let caret = (text as NSString).range(of: "#+TBLFM").location + 3 | ||
| 331 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) | ||
| 332 | guard case .commit(let result) = TableRecalculate(all: true).run(in: context) else { | ||
| 333 | Issue.record("not calculated: \(TableRecalculate(all: true).run(in: context))") | ||
| 334 | return | ||
| 335 | } | ||
| 336 | let ours = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) } | ||
| 337 | let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" | ||
| 338 | let emacs = try DailiesTests.emacs(""" | ||
| 339 | (progn (require 'org) (require 'ob-js) | ||
| 340 | (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node") | ||
| 341 | (with-temp-buffer (insert \(quoted)) (org-mode) (goto-char \(caret + 1)) (org-ctrl-c-ctrl-c) (princ (buffer-string)))) | ||
| 342 | """) | ||
| 343 | #expect(ours == emacs, "ours:\n\(ours)\nemacs:\n\(emacs)") | ||
| 344 | } | ||
| 269 | } | 345 | } |
Tests/OrgCoreTests/ElispLinkTests.swift added +38
| @@ -0,0 +1,38 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import OrgCore | ||
| 4 | |||
| 5 | /// `elisp:` links evaluated in `Elisp`, with the message `org-link--open-elisp` shows. | ||
| 6 | struct 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 | "(org-lookup-first 2 '(1 2 3) '(a b c))", "(org-lookup-all 1 '(1 2 1) '(x y z))", "(format \"%S\" '(lambda () 1))", | ||
| 11 | ] | ||
| 12 | |||
| 13 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 14 | func matchesEmacs() throws { | ||
| 15 | let list = "(list " + Self.forms.map { form in | ||
| 16 | let quoted = form.debugDescription | ||
| 17 | return "(condition-case e (format \"%s => %s\" \(quoted) (eval (read \(quoted)))) (error (error-message-string e)))" | ||
| 18 | }.joined(separator: " ") + ")" | ||
| 19 | let emacs = try EmacsOracle.evaluate("", list) | ||
| 20 | #expect(emacs.count == Self.forms.count) | ||
| 21 | for (form, expected) in zip(Self.forms, emacs) { | ||
| 22 | #expect(Links.evaluateElisp(form) == expected, "\(form)") | ||
| 23 | } | ||
| 24 | } | ||
| 25 | |||
| 26 | @Test func refusesWhatOnlyEmacsHas() { | ||
| 27 | #expect(Links.evaluateElisp("(org-agenda nil \"a\")") == "This link uses Emacs Lisp that runs only in Emacs.") | ||
| 28 | // Emacs has values for variables the interpreter doesn't define. | ||
| 29 | for form in ["(+ fill-column 1)", "most-positive-fixnum", "(concat user-full-name \"\")", "(condition-case nil org-directory (void-variable 0))"] { | ||
| 30 | #expect(Links.evaluateElisp(form) == "This link uses Emacs Lisp that runs only in Emacs.", "\(form)") | ||
| 31 | } | ||
| 32 | #expect(Links.evaluateElisp("(let ((x 2)) (+ x 1))") == "(let ((x 2)) (+ x 1)) => 3") | ||
| 33 | // Emacs 31 prints a function made under dynamic binding as `#[nil (1) nil]`. | ||
| 34 | for form in ["(let ((f (lambda () 1))) f)", "(prin1-to-string (lambda () 1))", "(format \"%S\" (lambda () 1))", "(car (lambda () 1))"] { | ||
| 35 | #expect(Links.evaluateElisp(form) == "This link uses Emacs Lisp that runs only in Emacs.", "\(form)") | ||
| 36 | } | ||
| 37 | } | ||
| 38 | } | ||
Tests/OrgCoreTests/TableSbeTests.swift added +168
| @@ -0,0 +1,168 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import OrgCore | ||
| 4 | |||
| 5 | /// `org-sbe` in Lisp table formulas, compared with Emacs. | ||
| 6 | struct TableSbeTests { | ||
| 7 | static let blocks = """ | ||
| 8 | #+NAME: square | ||
| 9 | #+begin_src emacs-lisp :var n=2 | ||
| 10 | (* n n) | ||
| 11 | #+end_src | ||
| 12 | |||
| 13 | #+NAME: greet | ||
| 14 | #+begin_src emacs-lisp :var who="x" | ||
| 15 | (concat "hi " who) | ||
| 16 | #+end_src | ||
| 17 | |||
| 18 | #+NAME: lst | ||
| 19 | #+begin_src emacs-lisp | ||
| 20 | '(a "b" 1 2.5) | ||
| 21 | #+end_src | ||
| 22 | |||
| 23 | #+NAME: sym | ||
| 24 | #+begin_src emacs-lisp | ||
| 25 | 'foo | ||
| 26 | #+end_src | ||
| 27 | |||
| 28 | #+NAME: tbl | ||
| 29 | #+begin_src emacs-lisp | ||
| 30 | '((1 2) hline (3 4)) | ||
| 31 | #+end_src | ||
| 32 | |||
| 33 | #+NAME: rules | ||
| 34 | #+begin_src emacs-lisp | ||
| 35 | '((1 2) hline (3 4) hline (5 6)) | ||
| 36 | #+end_src | ||
| 37 | |||
| 38 | #+NAME: two | ||
| 39 | #+begin_src emacs-lisp :var a=1 b=2 | ||
| 40 | (list a b) | ||
| 41 | #+end_src | ||
| 42 | |||
| 43 | #+NAME: out | ||
| 44 | #+begin_src emacs-lisp :results output :var x=1 | ||
| 45 | (princ (format " x is %s\\n" x)) | ||
| 46 | #+end_src | ||
| 47 | |||
| 48 | #+NAME: quad | ||
| 49 | #+begin_src emacs-lisp :var x=square(n=3) | ||
| 50 | (* x 2) | ||
| 51 | #+end_src | ||
| 52 | |||
| 53 | #+NAME: oops | ||
| 54 | #+begin_src emacs-lisp | ||
| 55 | (car 1) | ||
| 56 | #+end_src | ||
| 57 | |||
| 58 | #+NAME: data | ||
| 59 | | k | v | | ||
| 60 | |---+---| | ||
| 61 | | a | 1 | | ||
| 62 | | b | 2.5 | | ||
| 63 | |||
| 64 | #+NAME: items | ||
| 65 | - one | ||
| 66 | - 2 | ||
| 67 | |||
| 68 | |||
| 69 | """ | ||
| 70 | |||
| 71 | static let tables = [ | ||
| 72 | blocks + "| n | sq | sqN | g | g$ | lst | sym |\n|---+----+-----+---+----+-----+-----|\n| 3 | | | | | | |\n| abc | | | | | | |\n| 2.5 | | | | | | |\n" | ||
| 73 | + "#+TBLFM: $2='(org-sbe \"square\" (n $1))::$3='(org-sbe square (n $1));N::$4='(org-sbe greet (who $1))::$5='(org-sbe greet (who $$1))::$6='(org-sbe lst)::$7='(org-sbe sym)\n", | ||
| 74 | blocks + "| n | tbl | rules | none | str | noargs |\n|---+-----+-------+------+-----+--------|\n| 3 | | | | | | |\n| abc | | | | | | |\n" | ||
| 75 | + "#+TBLFM: $2='(org-sbe tbl)::$3='(org-sbe rules)::$4='(org-sbe nope)::$5='(org-sbe greet (who \"\\\"q r\\\"\"))::$6='(org-sbe square)\n", | ||
| 76 | blocks + "| n | out | quad | oops | data | items | verbatim | empty | two |\n|---+-----+------+------+------+-------+----------+-------+-----|\n| 4 | | | | | | | | |\n" | ||
| 77 | + "#+TBLFM: $2='(org-sbe out (x $1))::$3='(org-sbe quad)::$4='(org-sbe oops)::$5='(org-sbe data)::$6='(org-sbe items)::$7='(org-sbe greet \":results verbatim\" (who $$1))::$8='(org-sbe \"\")::$9='(org-sbe two (a $1 $1) (b $$1))\n", | ||
| 78 | blocks + "| n | sum |\n|---+-----|\n| 2 | |\n| 5 | |\n#+TBLFM: $2='(+ 1 (string-to-number (org-sbe square (n $1))))\n", | ||
| 79 | // `:lexical t` and `yes` are lexical; a name under a COMMENT heading, or on a keyword | ||
| 80 | // that names nothing, is skipped. | ||
| 81 | "#+NAME: lext\n#+begin_src emacs-lisp :lexical t\n(let ((f (let ((y 2)) (lambda () y)))) (let ((y 3)) (funcall f)))\n#+end_src\n\n" | ||
| 82 | + "#+NAME: lexy\n#+begin_src emacs-lisp :lexical yes\n(let ((f (let ((y 2)) (lambda () y)))) (let ((y 3)) (funcall f)))\n#+end_src\n\n" | ||
| 83 | + "#+NAME: dyn\n#+begin_src emacs-lisp :lexical no\n(let ((f (let ((y 2)) (lambda () y)))) (let ((y 3)) (funcall f)))\n#+end_src\n\n" | ||
| 84 | + "#+NAME: orph\n\n#+NAME: orph\n#+begin_src emacs-lisp\n\"real\"\n#+end_src\n\n" | ||
| 85 | + "| t | yes | no | cm | orph |\n|---+-----+----+----+------|\n| | | | | |\n" | ||
| 86 | + "#+TBLFM: $1='(org-sbe lext)::$2='(org-sbe lexy)::$3='(org-sbe dyn)::$4='(org-sbe cm)::$5='(org-sbe orph)\n\n" | ||
| 87 | + "* COMMENT Old\n#+NAME: cm\n| old |\n\n* New\n#+NAME: cm\n#+begin_src emacs-lisp\n\"new\"\n#+end_src\n", | ||
| 88 | // A quoted lambda stays a list, a name in another case names nothing, and a lambda | ||
| 89 | // can be a lookup's predicate. | ||
| 90 | "#+NAME: quo\n#+begin_src emacs-lisp :lexical yes\n(list 1 '(lambda () 1))\n#+end_src\n\n" | ||
| 91 | + "| q | up | lk |\n|---+----+----|\n| | | |\n" | ||
| 92 | + "#+TBLFM: $1='(org-sbe quo)::$2='(org-sbe x)::$3='(org-lookup-first 2 '(1 2 3) '(a b c) (lambda (a b) (= a b)))\n\n" | ||
| 93 | + "#+NAME: X\n| up |\n", | ||
| 94 | ] | ||
| 95 | |||
| 96 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 97 | func matchesEmacs() throws { | ||
| 98 | var cases: [EmacsOracle.Case] = [] | ||
| 99 | var ours: [(text: String, caret: Int, failure: String?)] = [] | ||
| 100 | for text in Self.tables { | ||
| 101 | let caret = (text as NSString).range(of: "#+TBLFM").location + 3 | ||
| 102 | cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: "(let ((org-confirm-babel-evaluate nil)) (org-ctrl-c-ctrl-c))")) | ||
| 103 | ours.append(TableFormulaTests.recalculate(TableRecalculate(all: true), text, caret: caret)) | ||
| 104 | } | ||
| 105 | let emacs = try EmacsOracle.run(cases) | ||
| 106 | for (i, (mine, theirs)) in zip(ours, emacs).enumerated() { | ||
| 107 | let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error) | ||
| 108 | #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2, | ||
| 109 | "case \(i)\nours:\n\(mine.text.components(separatedBy: "\n\n").last ?? "") \(mine.failure ?? "")\nemacs:\n\(theirs.text.components(separatedBy: "\n\n").last ?? "") \(theirs.error)") | ||
| 110 | } | ||
| 111 | } | ||
| 112 | |||
| 113 | /// The reason a table with `org-sbe` in `formula` goes to Emacs; nil when it doesn't. | ||
| 114 | static func reason(_ head: String, _ formula: String) -> String? { | ||
| 115 | let text = head + "| n | f |\n|---+---|\n| 3 | |\n#+TBLFM: $2=" + formula + "\n" | ||
| 116 | let caret = (text as NSString).range(of: "#+TBLFM").location + 3 | ||
| 117 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) | ||
| 118 | guard case .external(.emacsTable(_, _, _, let reason, _, _, _)) = TableRecalculate(all: true).run(in: context) else { return nil } | ||
| 119 | return reason | ||
| 120 | } | ||
| 121 | |||
| 122 | /// Values Emacs 31 prints or reads as interpreted-function objects, `:lexical` values Emacs reads as | ||
| 123 | /// Lisp, and a name whose first use is skipped and that doesn't name a src block go to Emacs. | ||
| 124 | @Test func refusesWhatPrintsOrReadsDifferently() { | ||
| 125 | let lambda = "#+NAME: lam\n#+begin_src emacs-lisp\n(lambda () 1)\n#+end_src\n\n" | ||
| 126 | let printed = "#+NAME: lam\n#+begin_src emacs-lisp\n(format \"%S\" (lambda () 1))\n#+end_src\n\n" | ||
| 127 | let car = "#+NAME: lam\n#+begin_src emacs-lisp\n(car (lambda () 1))\n#+end_src\n\n" | ||
| 128 | let lexical = "#+NAME: lam\n#+begin_src emacs-lisp :lexical (identity t)\n1\n#+end_src\n\n" | ||
| 129 | let twice = "* COMMENT Old\n#+NAME: lam\n| a |\n\n* New\n#+NAME: lam\n| b |\n\n" | ||
| 130 | #expect(Self.reason(lambda, "'(org-sbe lam)") == "Lisp org-sbe with a function value") | ||
| 131 | #expect(Self.reason(printed, "'(org-sbe lam)") == "Lisp format on a closure") | ||
| 132 | #expect(Self.reason(car, "'(org-sbe lam)") == "Lisp car on a closure") | ||
| 133 | #expect(Self.reason("", "'(format \"%S\" (lambda () 1))") == "Lisp format on a closure") | ||
| 134 | #expect(Self.reason("", "'(lambda () 1)") == "Lisp formula with a function value") | ||
| 135 | #expect(Self.reason(lexical, "'(org-sbe lam)") == "Lisp org-sbe with this :lexical") | ||
| 136 | #expect(Self.reason(twice, "'(org-sbe lam)") == "Lisp org-sbe with a name used more than once") | ||
| 137 | #expect(Self.reason("#+NAME: lam\n| a |\n\n", "'(org-sbe lam)") == nil) | ||
| 138 | } | ||
| 139 | |||
| 140 | @TaskLocal static var locked = false | ||
| 141 | |||
| 142 | /// Without the app's leave to run blocks, `org-sbe` goes to the app with `lockedReason`. | ||
| 143 | @Test func lockedWithoutBabel() { | ||
| 144 | TableBlocks.allowed = { !TableSbeTests.locked } | ||
| 145 | let square = "#+NAME: f\n#+begin_src emacs-lisp :var n=2\n(* n n)\n#+end_src\n\n" | ||
| 146 | Self.$locked.withValue(true) { | ||
| 147 | #expect(Self.reason(square, "'(org-sbe f (n $1))") == TableBlocks.lockedReason) | ||
| 148 | } | ||
| 149 | #expect(Self.reason(square, "'(org-sbe f (n $1))") == nil) | ||
| 150 | } | ||
| 151 | |||
| 152 | /// Other languages, and references only Emacs follows, go to Emacs. | ||
| 153 | @Test func otherLanguagesNeedEmacs() { | ||
| 154 | let python = "#+NAME: f\n#+begin_src python :var n=2\nreturn n\n#+end_src\n\n" | ||
| 155 | let id = "* Data\n:PROPERTIES:\n:CUSTOM_ID: f\n:END:\n\n" | ||
| 156 | for (head, expected) in [(python, "Lisp org-sbe with python blocks"), (id, "Lisp org-sbe with an ID reference")] { | ||
| 157 | let text = head + "| n | f |\n|---+---|\n| 3 | |\n#+TBLFM: $2='(org-sbe f (n $1))\n" | ||
| 158 | let caret = (text as NSString).range(of: "#+TBLFM").location + 3 | ||
| 159 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) | ||
| 160 | guard case .external(.emacsTable(_, _, _, let reason, let lisp, _, _)) = TableRecalculate(all: true).run(in: context) else { | ||
| 161 | Issue.record("not sent to Emacs: \(expected)") | ||
| 162 | continue | ||
| 163 | } | ||
| 164 | #expect(reason == expected) | ||
| 165 | #expect(lisp) | ||
| 166 | } | ||
| 167 | } | ||
| 168 | } | ||
Tests/OrgProgramsTests/ProgramsTests.swift +55
| @@ -38,6 +38,61 @@ struct EmacsFallbackTests { | |||
| 38 | #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") | 38 | #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") |
| 39 | } | 39 | } |
| 40 | 40 | ||
| 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 | |||
| 61 | /// Emacs can run each compiled language and interpreter orgstar runs, for `org-sbe`. | ||
| 62 | @Test(.enabled(if: EmacsRunner.executable() != nil)) | ||
| 63 | func loadsEveryLanguageForOrgSbe() throws { | ||
| 64 | let languages = ["C", "C++", "D", "fortran", "java", "clojure", "awk", "js", "python", "R", "ruby", "sh", "bash"] | ||
| 65 | let process = Process() | ||
| 66 | process.executableURL = EmacsRunner.executable() | ||
| 67 | process.arguments = ["-Q", "--batch", "--eval", "(progn (require 'org) " + EmacsRunner.sbeLanguages | ||
| 68 | + " (princ (mapconcat (lambda (l) (if (fboundp (intern (concat \"org-babel-execute:\" l))) \"\" l)) '(" + languages.map { "\"\($0)\"" }.joined(separator: " ") + ") \"\")))"] | ||
| 69 | let out = Pipe() | ||
| 70 | process.standardOutput = out | ||
| 71 | process.standardError = FileHandle.nullDevice | ||
| 72 | try process.run() | ||
| 73 | process.waitUntilExit() | ||
| 74 | #expect(String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) == "") | ||
| 75 | } | ||
| 76 | |||
| 77 | /// `org-sbe` on a block only Emacs runs: Emacs runs it without asking again. | ||
| 78 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 79 | func runsOtherLanguagesForOrgSbe() async throws { | ||
| 80 | let notes = try Folder() | ||
| 81 | let text = "#+NAME: f\n#+begin_src sh :var n=2\necho $((n * 3))\n#+end_src\n\n| n | f |\n|---+---|\n| 3 | |\n#+TBLFM: $2='(org-sbe f (n $1))\n" | ||
| 82 | let file = try notes.write("t.org", text) | ||
| 83 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | ||
| 84 | session.open(file.path) | ||
| 85 | let step = session.perform(TableRecalculate(all: true), path: file.path, at: (text as NSString).range(of: "#+TBLFM").location + 3, expect: nil) | ||
| 86 | guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp, _, _)) = step else { | ||
| 87 | Issue.record("\(step)") | ||
| 88 | return | ||
| 89 | } | ||
| 90 | #expect(reason == "Lisp org-sbe with sh blocks") | ||
| 91 | #expect(lisp) | ||
| 92 | #expect(await session.recalculateInEmacs(table: table, point: point, form: form) == "Recalculated in Emacs") | ||
| 93 | #expect(session.document?.text.hasSuffix("| n | f |\n|---+---|\n| 3 | 9 |\n#+TBLFM: $2='(org-sbe f (n $1))\n") == true) | ||
| 94 | } | ||
| 95 | |||
| 41 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | 96 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| 42 | func cancelingARecalculationLeavesTheTable() async throws { | 97 | func cancelingARecalculationLeavesTheTable() async throws { |
| 43 | let notes = try Folder() | 98 | let notes = try Folder() |
docs/manual/guide/09-links.org +21 −1
| @@ -61,7 +61,8 @@ A message in the echo area explains a link that can't be followed. | |||
| 61 | | Text | =[[budget table]]= | Searches this file: a =<<budget table>>= target, then =#+NAME: budget table=, then a heading. | | 61 | | Text | =[[budget table]]= | Searches this file: a =<<budget table>>= target, then =#+NAME: budget table=, then a heading. | |
| 62 | | Coderef | =[[(ref)]]= | Moves to the label =(ref:ref)= in a src or example block; see /Code references/ below. | | 62 | | Coderef | =[[(ref)]]= | Moves to the label =(ref:ref)= in a src or example block; see /Code references/ below. | |
| 63 | | Regexp | =[[/TODO.*soon/]]= | Shows a sparse tree of the regular expression's matches, as =org-occur=; iOS moves to the first match. | | 63 | | 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. | | ||
| 65 | | =attachment= | =[[attachment:scan.pdf]]= | Opens the file in the entry's attachment folder; see /Attachment links/ below. | | 66 | | =attachment= | =[[attachment:scan.pdf]]= | Opens the file in the entry's attachment folder; see /Attachment links/ below. | |
| 66 | | Radio link | Text matching a =<<<radio target>>>= | Moves to the radio target. | | 67 | | Radio link | Text matching a =<<<radio target>>>= | Moves to the radio target. | |
| 67 | | =info=, =help=, others | | Not followed. The echo area says orgstar can't open the type. | | 68 | | =info=, =help=, others | | Not followed. The echo area says orgstar can't open the type. | |
| @@ -136,6 +137,25 @@ identifier, such as a PDF. A search after =::=, such as =::#custom-id= or =::*He | |||
| 136 | works as in a =file:= link. Backlinks list =denote:= links to a file, and to a heading when | 137 | works as in a =file:= link. Backlinks list =denote:= links to a file, and to a heading when |
| 137 | the link searches for it. | 138 | the link searches for it. |
| 138 | 139 | ||
| 140 | ** Emacs Lisp links | ||
| 141 | |||
| 142 | Following 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 | ||
| 145 | changes. 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, or a variable it doesn't | ||
| 153 | bind itself, such as =fill-column=, shows | ||
| 154 | =This link uses Emacs Lisp that runs only in Emacs.= | ||
| 155 | |||
| 156 | A path that names a command, such as =elisp:org-agenda=, isn't run. The reader view on iOS | ||
| 157 | doesn't run =elisp:= links; open the file in the editor. | ||
| 158 | |||
| 139 | ** Timestamps | 159 | ** Timestamps |
| 140 | 160 | ||
| 141 | =C-c C-o= (Mac =⌃⌘O=) or =⌘=-click on a timestamp opens the agenda on that day, as | 161 | =C-c C-o= (Mac =⌃⌘O=) or =⌘=-click on a timestamp opens the agenda on that day, as |
docs/manual/guide/10-tables.org +36 −1
| @@ -570,9 +570,44 @@ when the error isn't one of =wrong-type-argument=, =args-out-of-range=, =arith-e | |||
| 570 | widths; other codes need Emacs, as do float times in =time-add= and =time-subtract=. =date-to-time= and =days-between= read dates as | 570 | widths; other codes need Emacs, as do float times in =time-add= and =time-subtract=. =date-to-time= and =days-between= read dates as |
| 571 | =YYYY-MM-DD=, with an optional =HH:MM= or =HH:MM:SS=. | 571 | =YYYY-MM-DD=, with an optional =HH:MM= or =HH:MM:SS=. |
| 572 | 572 | ||
| 573 | Any other function, or a macro not listed, needs Emacs. An error inside a Lisp formula | 573 | Any other function, or a macro not listed, needs Emacs. As in Emacs 31, =lambda= and |
| 574 | =function= make function objects rather than lists, so a formula whose value is one, or | ||
| 575 | that prints one or takes it apart as a list, needs Emacs; calling one, or passing it to a | ||
| 576 | function that calls it, doesn't. An error inside a Lisp formula | ||
| 574 | writes =#ERROR= in the field, as does a Calc error. | 577 | writes =#ERROR= in the field, as does a Calc error. |
| 575 | 578 | ||
| 579 | =org-sbe= writes the value of a named src block, run with the variables given: | ||
| 580 | |||
| 581 | #+BEGIN_SRC org | ||
| 582 | ,#+NAME: square | ||
| 583 | ,#+begin_src emacs-lisp :var n=2 | ||
| 584 | (* n n) | ||
| 585 | ,#+end_src | ||
| 586 | |||
| 587 | | n | square | | ||
| 588 | |---+--------| | ||
| 589 | | 3 | 9 | | ||
| 590 | ,#+TBLFM: $2='(org-sbe square (n $1)) | ||
| 591 | #+END_SRC | ||
| 592 | |||
| 593 | As in Org, a field's text is read as a value, so =abc= names another block or table; | ||
| 594 | write =$$1= instead of =$1= to pass the text as a string. A string before the variables | ||
| 595 | holds header arguments, and the name may also be a named table or list in the file. As in | ||
| 596 | Org, a name under a =COMMENT= heading is skipped, and the name's case must match. =org-sbe= needs Pro's source blocks | ||
| 597 | feature. | ||
| 598 | |||
| 599 | Emacs Lisp blocks run in orgstar's interpreter, with dynamic binding unless the block | ||
| 600 | has =:lexical yes= or =:lexical t=, and =js= blocks run in JavaScriptCore, everywhere and | ||
| 601 | without asking, since neither can reach files or other programs. After five seconds orgstar | ||
| 602 | stops waiting for a =js= block and the table needs Emacs; a block that never finishes | ||
| 603 | keeps running in the background until orgstar quits, and isn't started again while it runs. Blocks in other languages, blocks with =:cache yes=, | ||
| 604 | =:file= results or column and row names, other =:lexical= values, values that hold a | ||
| 605 | function, Lisp values with symbols in a variable with several values, a name given to | ||
| 606 | more than one element, in any case, when the first isn't a src block, references to an =ID= or | ||
| 607 | =CUSTOM_ID=, and =js= values that are arrays need Emacs. When Emacs runs a table in a file | ||
| 608 | that uses =org-sbe=, it runs the blocks without asking again, so orgstar asks | ||
| 609 | =This table's formulas run Lisp and source blocks. Run them? (yes, no)= each time. | ||
| 610 | |||
| 576 | * Entering formulas | 611 | * Entering formulas |
| 577 | 612 | ||
| 578 | There are three ways to set a formula. | 613 | There are three ways to set a formula. |
docs/manual/guide/15-alongside-emacs.org +2 −1
| @@ -225,7 +225,8 @@ Code blocks (see [[file:11-code-blocks.org][Code blocks]]): | |||
| 225 | 225 | ||
| 226 | Links (see [[file:09-links.org][Links]]): | 226 | Links (see [[file:09-links.org][Links]]): |
| 227 | 227 | ||
| 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. | ||
| 229 | 230 | ||
| 230 | Capture templates (see [[file:08-capture.org][Capture]]): | 231 | Capture templates (see [[file:08-capture.org][Capture]]): |
| 231 | 232 | ||