Sources/OrgCore/Snippets/SnippetCommands.swift

1e2bc5fb0b3e80e3b2d877c37d07f3ec7f183be2
orgstar/Sources/OrgCore/Snippets/SnippetCommands.swift

116 lines · 6216 bytes

  1import Foundation
  2
  3/// TAB after a trigger, where TAB means nothing else, and any key bound to it: `yas-expand`.
  4public struct ExpandSnippet: OrgCommand {
  5    public init() {}
  6    public var id: String { "org.snippet.expand" }
  7    public var title: String { "Expand Snippet" }
  8    public func applies(in context: EditContext) -> Bool {
  9        context.selection.allSatisfy(\.isEmpty) && Snippets.trigger(before: context.caret, in: context.text, snippets: context.options.snippets) != nil
 10    }
 11    public func run(in context: EditContext) -> CommandStep {
 12        guard context.selection.allSatisfy(\.isEmpty),
 13              let found = Snippets.trigger(before: context.caret, in: context.text, snippets: context.options.snippets) else {
 14            return .failed("No snippet to expand")
 15        }
 16        return Snippets.step(found.snippet, replacing: found.range, in: context)
 17    }
 18}
 19
 20/// Insert Snippet…: one chosen by name replaces the selection, which `%i` inserts
 21/// (`yas-insert-snippet`).
 22public struct InsertSnippet: OrgCommand {
 23    public init() {}
 24    public var id: String { "org.snippet.insert" }
 25    public var title: String { "Insert Snippet…" }
 26    public func applies(in context: EditContext) -> Bool { context.options.snippets.contains { !$0.file } }
 27    public func run(in context: EditContext) -> CommandStep {
 28        let snippets = context.options.snippets.filter { !$0.file }
 29        guard !snippets.isEmpty else { return .failed("No snippets in \(Snippets.fileName)") }
 30        guard let answer = context.answers["snippet"] else {
 31            return .prompt(Prompt(key: "snippet", message: "Choose snippet: ", choices: snippets.map(Snippets.label)))
 32        }
 33        guard let snippet = snippets.first(where: { Snippets.label($0) == answer || $0.trigger == answer }) else {
 34            return .failed("No snippet \(answer)")
 35        }
 36        let selected = context.selection.first ?? context.caret..<context.caret
 37        return Snippets.step(snippet, replacing: selected, in: context)
 38    }
 39}
 40
 41/// A snippet or file template by trigger, at the caret: the command `Snippet.commandID` names.
 42public struct ExpandNamedSnippet: OrgCommand {
 43    public let trigger: String
 44    /// The snippet itself, for a template expanded before the editor has the snippets.
 45    let snippet: Snippet?
 46    public init(trigger: String) {
 47        self.trigger = trigger
 48        snippet = nil
 49    }
 50    public init(snippet: Snippet) {
 51        trigger = snippet.trigger
 52        self.snippet = snippet
 53    }
 54    public var id: String { Snippets.commandPrefix + trigger }
 55    public var title: String { "Expand Snippet" }
 56    public func applies(in context: EditContext) -> Bool { snippet != nil || context.options.snippets.contains { $0.trigger == trigger } }
 57    public func run(in context: EditContext) -> CommandStep {
 58        guard let snippet = snippet ?? context.options.snippets.first(where: { $0.trigger == trigger }) else { return .failed("No snippet \(trigger)") }
 59        let selected = context.selection.first ?? context.caret..<context.caret
 60        return Snippets.step(snippet, replacing: selected, in: context)
 61    }
 62}
 63
 64extension Snippets {
 65    /// How Insert Snippet… lists a snippet.
 66    public static func label(_ snippet: Snippet) -> String {
 67        snippet.name == snippet.trigger ? snippet.trigger : "\(snippet.name) (\(snippet.trigger))"
 68    }
 69
 70    /// The command for an id of the form `Snippet.commandID`.
 71    public static func command(_ id: String) -> (any OrgCommand)? {
 72        trigger(ofCommand: id).map(ExpandNamedSnippet.init)
 73    }
 74
 75    /// Asks the body's prompts one at a time, then replaces `range` with the expansion and
 76    /// starts a session on its fields.
 77    static func step(_ snippet: Snippet, replacing range: Range<Int>, in context: EditContext) -> CommandStep {
 78        let ns = context.text as NSString
 79        var capture = CaptureContext(now: context.now, calendar: context.calendar,
 80                                     initial: range.isEmpty ? "" : ns.substring(with: NSRange(location: range.lowerBound, length: range.count)),
 81                                     file: context.options.filePath ?? "")
 82        capture.tagsColumn = context.options.tagsColumn
 83        let questions = questions(snippet, context: capture)
 84        var answers: [String] = []
 85        for (index, question) in questions.enumerated() {
 86            let key = "snippet-\(index)"
 87            guard let answer = context.answers[key] else { return .prompt(prompt(question, key: key)) }
 88            answers.append(answer)
 89        }
 90        let lineStart = ns.lineRange(for: NSRange(location: range.lowerBound, length: 0)).location
 91        let indentation = String(ns.substring(with: NSRange(location: lineStart, length: range.lowerBound - lineStart)).prefix { $0 == " " || $0 == "\t" })
 92        switch expand(snippet, context: capture, answers: answers, indentation: indentation) {
 93        case .failure(.message(let message)):
 94            return .failed(message)
 95        case .success(let expansion):
 96            let session = SnippetSession(expansion, at: range.lowerBound)
 97            let exit = (expansion.exit.lowerBound + range.lowerBound)..<(expansion.exit.upperBound + range.lowerBound)
 98            return .commit(EditResult(
 99                baseRevision: context.revision, edits: [TextEdit(range: range, replacement: expansion.text)],
100                selection: [session?.selection ?? exit], effects: session.map { [.snippet($0)] } ?? []
101            ))
102        }
103    }
104
105    static func prompt(_ question: Capture.Question, key: String) -> Prompt {
106        switch question.kind {
107        case .date(_, let inactive):
108            return Prompt(key: key, message: question.prompt + ": ", date: .init(defaultDate: nil, inactive: inactive))
109        case .tags:
110            return Prompt(key: key, message: question.prompt + ": ", choices: question.choices, requireMatch: false, completionSeparator: ":")
111        case .text, .clipboard, .property:
112            return Prompt(key: key, message: question.prompt + (question.defaultValue.isEmpty ? ": " : " (\(question.defaultValue)): "),
113                          choices: question.choices, requireMatch: false)
114        }
115    }
116}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form