Sources/OrgCore/Capture/CaptureLisp.swift

design-themes-widgets
orgstar/Sources/OrgCore/Capture/CaptureLisp.swift history · blame · raw

119 lines · 5426 bytes

  1import Foundation
  2
  3// `%(sexp)` in capture templates (`org-capture-expand-embedded-elisp`), evaluated by the Elisp
  4// subset with what capture templates call most: `format-time-string`, `current-time`,
  5// `read-string` and `user-full-name`, besides the subset's own functions.
  6
  7extension Capture {
  8    /// Where each `%(` that starts a whole sexp ends, by the index of its `%`: the forms
  9    /// `org-capture-expand-embedded-elisp` marks. Escaped ones are left out by the caller.
 10    static func embeddedSexps(_ chars: [Character]) -> [Int: Int] {
 11        var ends: [Int: Int] = [:]
 12        var i = 0
 13        while i + 1 < chars.count {
 14            if chars[i] == "%", chars[i + 1] == "(", let end = sexpEnd(chars, from: i + 1) {
 15                ends[i] = end
 16                i = end
 17            } else {
 18                i += 1
 19            }
 20        }
 21        return ends
 22    }
 23
 24    /// `scan-sexps` over a list starting at `start`: the index after its closing paren.
 25    static func sexpEnd(_ chars: [Character], from start: Int) -> Int? {
 26        var depth = 0
 27        var i = start
 28        while i < chars.count {
 29            switch chars[i] {
 30            case "(": depth += 1
 31            case ")":
 32                depth -= 1
 33                if depth == 0 { return i + 1 }
 34            case "\"":
 35                i += 1
 36                while i < chars.count, chars[i] != "\"" { i += chars[i] == "\\" ? 2 : 1 }
 37                guard i < chars.count else { return nil }
 38            case "?":
 39                // A character: `?a`, `?\)`.
 40                i += chars.indices.contains(i + 1) && chars[i + 1] == "\\" ? 2 : 1
 41            case "\\":
 42                i += 1
 43            case ";":
 44                while i < chars.count, chars[i] != "\n" { i += 1 }
 45            default: break
 46            }
 47            i += 1
 48        }
 49        return nil
 50    }
 51
 52    /// `org-capture--expand-keyword-in-embedded-elisp`: symbols such as `%:link` become the
 53    /// link property's value.
 54    static func expandKeywords(_ sexp: Sexp, _ context: CaptureContext) -> Sexp {
 55        switch sexp {
 56        case .list(let items): return .list(items.map { expandKeywords($0, context) })
 57        case .dotted(let items, let last): return .dotted(items.map { expandKeywords($0, context) }, expandKeywords(last, context))
 58        case .symbol(let name):
 59            guard let range = name.range(of: "%:") else { return sexp }
 60            let key = String(name[range.upperBound...])
 61            switch key {
 62            case _ where context.linkProperties[key] != nil: return .string(context.linkProperties[key]!)
 63            case "annotation": return .string(context.annotation)
 64            case "initial": return .string(context.initial)
 65            default: return sexp
 66            }
 67        default: return sexp
 68        }
 69    }
 70
 71    /// Evaluates `%(…)` forms, the text from `(` to `)`, in order. `answers` reply to
 72    /// `read-string` in order; the questions it asks and the answers it took come back.
 73    final class Embedded {
 74        let context: CaptureContext
 75        var answers: ArraySlice<String>
 76        var questions: [Question] = []
 77        var used = 0
 78        let lisp = Elisp()
 79
 80        init(_ context: CaptureContext, answers: [String]) {
 81            self.context = context
 82            self.answers = answers[...]
 83            lisp.set("user-full-name", .string(context.userName))
 84            lisp.define("user-full-name") { [context] _, _ in .string(context.userName) }
 85            lisp.standardTime(now: { [context] in context.now }, calendar: context.calendar)
 86            lisp.define("read-string") { [unowned self] _, args in
 87                let prompt = args.first?.string ?? ""
 88                let initial = args.count > 1 ? args[1].string : nil
 89                let fallback = args.count > 3 ? args[3].string : nil
 90                questions.append(Question(prompt: prompt.replacingOccurrences(of: ":? *$", with: "", options: .regularExpression),
 91                                          defaultValue: fallback ?? initial ?? "", choices: []))
 92                guard let answer = self.answers.popFirst() else { return .string(fallback ?? initial ?? "") }
 93                used += 1
 94                return .string(answer.isEmpty ? fallback ?? initial ?? "" : answer)
 95            }
 96        }
 97
 98        /// The value to insert for the form `text`: a string, or "" for nil.
 99        func evaluate(_ text: String) -> Result<String, Failure> {
100            let form: Sexp
101            do {
102                guard let read = try LispReader.read(text).first?.sexp else { return .success("") }
103                form = read
104            } catch {
105                return .failure(.message("Can't read the template's \(text): \(error)"))
106            }
107            do {
108                let result = try lisp.eval(expandKeywords(form, context))
109                if Elisp.isNil(result) { return .success("") }
110                guard let string = result.string else { return .failure(.message("Capture template sexp `\(form.description)' must evaluate to string or nil")) }
111                return .success(string)
112            } catch let unsupported as Elisp.Unsupported {
113                return .failure(.message("Template %\(form.description) needs \(unsupported.what), which orgstar's Lisp doesn't have."))
114            } catch {
115                return .failure(.message("Template %\(form.description): \(error)"))
116            }
117        }
118    }
119}