Sources/OrgCore/Capture/CaptureLisp.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgCore/Capture/CaptureLisp.swift history · blame · raw

142 lines · 6812 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.define("current-time") { [context] _, _ in Self.time(context.now) }
 86            lisp.define("format-time-string") { [context] _, args in
 87                guard let format = args.first?.string else { throw Elisp.Signal(message: "Wrong type argument: stringp, \(args.first?.description ?? "nil")") }
 88                let date = try args.count > 1 && !Elisp.isNil(args[1]) ? Self.date(args[1]) : context.now
 89                var at = context
 90                at.now = date
 91                return .string(Capture.strftime(format, at))
 92            }
 93            lisp.define("read-string") { [unowned self] _, args in
 94                let prompt = args.first?.string ?? ""
 95                let initial = args.count > 1 ? args[1].string : nil
 96                let fallback = args.count > 3 ? args[3].string : nil
 97                questions.append(Question(prompt: prompt.replacingOccurrences(of: ":? *$", with: "", options: .regularExpression),
 98                                          defaultValue: fallback ?? initial ?? "", choices: []))
 99                guard let answer = self.answers.popFirst() else { return .string(fallback ?? initial ?? "") }
100                used += 1
101                return .string(answer.isEmpty ? fallback ?? initial ?? "" : answer)
102            }
103        }
104
105        /// `(HIGH LOW USEC PSEC)`.
106        static func time(_ date: Date) -> Sexp {
107            let seconds = Int(date.timeIntervalSince1970.rounded(.down))
108            let micro = Int((date.timeIntervalSince1970 - Double(seconds)) * 1_000_000)
109            return .list([.integer(seconds >> 16), .integer(seconds & 0xFFFF), .integer(micro), .integer(0)])
110        }
111
112        static func date(_ time: Sexp) throws -> Date {
113            if let seconds = time.integer { return Date(timeIntervalSince1970: Double(seconds)) }
114            guard let parts = time.elements, parts.count >= 2, let high = parts[0].integer, let low = parts[1].integer else {
115                throw Elisp.Unsupported(what: "time value \(time.description)")
116            }
117            let micro = parts.count > 2 ? Double(parts[2].integer ?? 0) / 1_000_000 : 0
118            return Date(timeIntervalSince1970: Double(high << 16 + low) + micro)
119        }
120
121        /// The value to insert for the form `text`: a string, or "" for nil.
122        func evaluate(_ text: String) -> Result<String, Failure> {
123            let form: Sexp
124            do {
125                guard let read = try LispReader.read(text).first?.sexp else { return .success("") }
126                form = read
127            } catch {
128                return .failure(.message("Can't read the template's \(text): \(error)"))
129            }
130            do {
131                let result = try lisp.eval(expandKeywords(form, context))
132                if Elisp.isNil(result) { return .success("") }
133                guard let string = result.string else { return .failure(.message("Capture template sexp `\(form.description)' must evaluate to string or nil")) }
134                return .success(string)
135            } catch let unsupported as Elisp.Unsupported {
136                return .failure(.message("Template %\(form.description) needs \(unsupported.what), which orgstar's Lisp doesn't have."))
137            } catch {
138                return .failure(.message("Template %\(form.description): \(error)"))
139            }
140        }
141    }
142}