Sources/OrgCore/Snippets/Snippet.swift

9954efcbf435b2e8d78a4b59bfbbbb67c1b6c379
orgstar/Sources/OrgCore/Snippets/Snippet.swift

385 lines · 16854 bytes

  1import Foundation
  2
  3/// A snippet from `snippets.toml`:
  4///
  5/// ```toml
  6/// [[snippet]]
  7/// trigger = "meet"
  8/// description = "Meeting notes"
  9/// body = """
 10/// * Meeting with ${1:someone} %U
 11/// - $0
 12/// """
 13/// ```
 14///
 15/// The body has yasnippet's tab stops (`$1`, `${1:default}`, `$0`; a number used twice is a
 16/// mirror) and the capture escapes that need no capture (`%t`, `%U`, `%<…>`, `%^{prompt}`,
 17/// `%i` for the selected text). With `file = true` it is a template for New File from
 18/// Template… instead.
 19public struct Snippet: Sendable, Equatable, Hashable, Codable {
 20    public var trigger: String
 21    /// The description, or the trigger when there is none.
 22    public var name: String
 23    public var body: String
 24    /// A template for a new file rather than a snippet typed in one.
 25    public var file: Bool
 26
 27    public init(trigger: String, name: String? = nil, body: String, file: Bool = false) {
 28        self.trigger = trigger
 29        self.name = name ?? trigger
 30        self.body = body
 31        self.file = file
 32    }
 33
 34    /// The command that expands this snippet at the caret, for keys and the iOS key bar.
 35    public var commandID: String { Snippets.commandPrefix + trigger }
 36}
 37
 38/// What a snippet's body expands to: its text, its fields and where the caret goes last, in
 39/// UTF-16 offsets into `text`.
 40public struct SnippetExpansion: Sendable, Equatable {
 41    public struct Field: Sendable, Equatable {
 42        public let number: Int
 43        /// The field first, then its mirrors.
 44        public var ranges: [Range<Int>]
 45    }
 46
 47    public var text: String
 48    /// By number, `$0` left out.
 49    public var fields: [Field]
 50    /// `$0`, or the end of the text; not empty for `${0:text}`, which is selected.
 51    public var exit: Range<Int>
 52}
 53
 54public enum Snippets {
 55    public static let fileName = "snippets.toml"
 56    static let commandPrefix = "org.snippet:"
 57
 58    /// The trigger of a `commandID`, or nil for another command.
 59    public static func trigger(ofCommand id: String) -> String? {
 60        id.hasPrefix(commandPrefix) ? String(id.dropFirst(commandPrefix.count)) : nil
 61    }
 62
 63    public struct Problem: Error, Equatable, CustomStringConvertible {
 64        public let line: Int
 65        public let message: String
 66        public var description: String { "line \(line): \(message)" }
 67    }
 68
 69    /// The snippets in a `snippets.toml`, and problems with single snippets, which are left
 70    /// out. Throws when the file isn't valid TOML.
 71    public static func parse(_ text: String) throws -> (snippets: [Snippet], problems: [String]) {
 72        let tables = try TOML.parse(text)
 73        var snippets: [Snippet] = []
 74        var problems: [String] = []
 75        var triggers: Set<String> = []
 76        for table in tables where !(table.name.isEmpty && table.values.isEmpty) {
 77            guard table.name == "snippet", table.isArrayElement else {
 78                problems.append("line \(table.line): expected [[snippet]]")
 79                continue
 80            }
 81            let values = table.values
 82            guard let trigger = values["trigger"]?.string, !trigger.isEmpty, let body = values["body"]?.string else {
 83                problems.append("line \(table.line): a snippet needs trigger and body")
 84                continue
 85            }
 86            guard !trigger.contains(where: \.isWhitespace) else {
 87                problems.append("line \(table.line): a trigger has no spaces")
 88                continue
 89            }
 90            for key in table.keys where !["trigger", "body", "description", "file"].contains(key) {
 91                problems.append("line \(table.line): unknown key \(key)")
 92            }
 93            do {
 94                _ = try parseBody(body)
 95            } catch let problem as Problem {
 96                problems.append("line \(table.line): \(problem.message)")
 97                continue
 98            }
 99            guard triggers.insert(trigger).inserted else {
100                problems.append("line \(table.line): trigger \(trigger) is used twice")
101                continue
102            }
103            snippets.append(Snippet(trigger: trigger, name: values["description"]?.string, body: body, file: values["file"]?.bool ?? false))
104        }
105        return (snippets, problems)
106    }
107
108    // MARK: - Triggers
109
110    /// The snippet whose trigger is just before `caret`, and the trigger's range. As
111    /// yasnippet's `yas-key-syntaxes`, the longest text back to a blank is tried first, then
112    /// shorter ones starting after a character that isn't part of a word.
113    public static func trigger(before caret: Int, in text: String, snippets: [Snippet]) -> (snippet: Snippet, range: Range<Int>)? {
114        let candidates = snippets.filter { !$0.file }
115        guard !candidates.isEmpty else { return nil }
116        let ns = text as NSString
117        guard caret > 0, caret <= ns.length else { return nil }
118        var start = caret
119        while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 }
120        guard start < caret else { return nil }
121        var from = start
122        while from < caret {
123            let typed = ns.substring(with: NSRange(location: from, length: caret - from))
124            if let snippet = candidates.first(where: { $0.trigger == typed }) { return (snippet, from..<caret) }
125            // The next start: after the next character that isn't a letter, digit or `_`.
126            from += 1
127            while from < caret, let scalar = UnicodeScalar(ns.character(at: from - 1)), CharacterSet.alphanumerics.contains(scalar) || scalar == "_" { from += 1 }
128        }
129        return nil
130    }
131
132    // MARK: - Bodies
133
134    /// Tab stops and text, as `parseBody` reads a body.
135    indirect enum Node: Equatable {
136        case text(String)
137        /// `$N` (no children) or `${N:…}`.
138        case stop(Int, [Node]?)
139    }
140
141    /// Reads yasnippet's tab stops: `$N`, `${N}`, `${N:default}` with stops nested in the
142    /// default, and the escapes `\$`, `\\`, `` \` `` and, in a default, `\}`.
143    static func parseBody(_ body: String) throws -> [Node] {
144        let chars = Array(body)
145        var i = 0
146        func parse(inDefault: Bool) throws -> [Node] {
147            var nodes: [Node] = []
148            var text = ""
149            func flush() {
150                if !text.isEmpty { nodes.append(.text(text)) }
151                text = ""
152            }
153            while i < chars.count {
154                let c = chars[i]
155                if c == "\\", i + 1 < chars.count, "$\\`".contains(chars[i + 1]) || (inDefault && chars[i + 1] == "}") {
156                    text.append(chars[i + 1])
157                    i += 2
158                    continue
159                }
160                if inDefault, c == "}" {
161                    i += 1
162                    flush()
163                    return nodes
164                }
165                guard c == "$", i + 1 < chars.count else {
166                    text.append(c)
167                    i += 1
168                    continue
169                }
170                if chars[i + 1].isASCII, chars[i + 1].isNumber {
171                    var j = i + 1
172                    while j < chars.count, chars[j].isASCII, chars[j].isNumber { j += 1 }
173                    flush()
174                    nodes.append(.stop(Int(String(chars[(i + 1)..<j]))!, nil))
175                    i = j
176                    continue
177                }
178                if chars[i + 1] == "{", i + 2 < chars.count, chars[i + 2].isASCII, chars[i + 2].isNumber {
179                    var j = i + 2
180                    while j < chars.count, chars[j].isASCII, chars[j].isNumber { j += 1 }
181                    let number = Int(String(chars[(i + 2)..<j]))!
182                    guard j < chars.count, chars[j] == ":" || chars[j] == "}" else {
183                        throw Problem(line: 0, message: "expected : or } after ${\(number)")
184                    }
185                    flush()
186                    if chars[j] == "}" {
187                        nodes.append(.stop(number, []))
188                        i = j + 1
189                        continue
190                    }
191                    if j + 2 < chars.count, chars[j + 1] == "$", chars[j + 2] == "(" {
192                        throw Problem(line: 0, message: "Emacs Lisp in a field isn't supported")
193                    }
194                    i = j + 1
195                    nodes.append(.stop(number, try parse(inDefault: true)))
196                    continue
197                }
198                text.append(c)
199                i += 1
200            }
201            if inDefault { throw Problem(line: 0, message: "a ${ isn't closed") }
202            flush()
203            return nodes
204        }
205        return try parse(inDefault: false)
206    }
207
208    /// Marks in the text a body becomes before the capture escapes are filled. Capture leaves
209    /// characters in the private use area alone.
210    static let fieldOpen: Character = "\u{E020}"
211    static let fieldSeparator: Character = "\u{E021}"
212    static let mirrorSeparator: Character = "\u{E026}"
213    static let fieldClose: Character = "\u{E022}"
214    static let edge: Character = "\u{E023}"
215    static let tab: Character = "\u{E024}"
216    static let backslash: Character = "\u{E025}"
217
218    /// The body with its stops as marks: the first `${N:…}` of a number (else its first `$N`)
219    /// is the field, the others mirrors. Tabs and literal backslashes are marked too, so that
220    /// filling leaves them.
221    static func marked(_ nodes: [Node]) -> String {
222        var primaries: [Int: Int] = [:]
223        var occurrence = 0
224        var withDefault: Set<Int> = []
225        func scan(_ nodes: [Node]) {
226            for node in nodes {
227                guard case .stop(let number, let children) = node else { continue }
228                if let children {
229                    if !withDefault.contains(number) {
230                        withDefault.insert(number)
231                        primaries[number] = occurrence
232                    }
233                    occurrence += 1
234                    scan(children)
235                } else {
236                    if primaries[number] == nil { primaries[number] = occurrence }
237                    occurrence += 1
238                }
239            }
240        }
241        scan(nodes)
242        occurrence = 0
243        func emit(_ nodes: [Node]) -> String {
244            var out = ""
245            for node in nodes {
246                switch node {
247                case .text(let text):
248                    // Backslashes in capture escapes (`\\%t`, `%\\1`) stay for capture.
249                    out += text.replacingOccurrences(of: "(?<!%)\\\\(?!%)", with: String(backslash), options: .regularExpression)
250                        .replacingOccurrences(of: "\t", with: String(tab))
251                case .stop(let number, let children):
252                    let primary = primaries[number] == occurrence
253                    occurrence += 1
254                    out += String(fieldOpen) + String(number) + String(primary ? fieldSeparator : mirrorSeparator)
255                    if primary, let children { out += emit(children) } else if let children { _ = emit(children) }
256                    out += String(fieldClose)
257                }
258            }
259            return out
260        }
261        return emit(nodes)
262    }
263
264    /// The `%?` of capture as `$0`, unless escaped.
265    static func captureCaret(_ body: String) -> String {
266        body.replacingOccurrences(of: "(?<!\\\\)%\\?", with: "\\$0", options: .regularExpression)
267    }
268
269    /// The capture prompts the body asks, in order.
270    public static func questions(_ snippet: Snippet, context: CaptureContext) -> [Capture.Question] {
271        guard let nodes = try? parseBody(captureCaret(snippet.body)) else { return [] }
272        return Capture.questions(String(edge) + marked(nodes) + String(edge), context: context)
273    }
274
275    /// The snippet expanded with `answers` to its `questions`; lines after the first start
276    /// with `indentation`.
277    public static func expand(_ snippet: Snippet, context: CaptureContext, answers: [String] = [], indentation: String = "") -> Result<SnippetExpansion, Capture.Failure> {
278        let nodes: [Node]
279        do {
280            nodes = try parseBody(captureCaret(snippet.body))
281        } catch {
282            return .failure(.message("\(snippet.trigger): \(error)"))
283        }
284        let filled: String
285        switch Capture.fill(String(edge) + marked(nodes) + String(edge), context: context, answers: answers) {
286        case .failure(let failure): return .failure(failure)
287        case .success(let result): filled = result.text
288        }
289        guard let first = filled.firstIndex(of: edge), let last = filled.lastIndex(of: edge), first < last else {
290            return .failure(.message("\(snippet.trigger) couldn't be expanded"))
291        }
292        var inner = String(filled[filled.index(after: first)..<last])
293        if !indentation.isEmpty { inner = inner.replacingOccurrences(of: "\n", with: "\n" + indentation) }
294        return .success(extract(inner))
295    }
296
297    /// Reads the marks out of filled text: the text with mirrors showing their field's text,
298    /// and the ranges.
299    static func extract(_ marked: String) -> SnippetExpansion {
300        // Pieces: text, or a stop with its number, whether it is the field, and its pieces.
301        indirect enum Piece {
302            case text(String)
303            case stop(Int, Bool, [Piece])
304        }
305        let chars = Array(marked)
306        var i = 0
307        func read() -> [Piece] {
308            var pieces: [Piece] = []
309            var text = ""
310            while i < chars.count {
311                let c = chars[i]
312                if c == fieldClose {
313                    i += 1
314                    break
315                }
316                if c == fieldOpen {
317                    if !text.isEmpty { pieces.append(.text(text)) }
318                    text = ""
319                    var j = i + 1
320                    while j < chars.count, chars[j] != fieldSeparator, chars[j] != mirrorSeparator { j += 1 }
321                    let number = Int(String(chars[(i + 1)..<j])) ?? 0
322                    let primary = j < chars.count && chars[j] == fieldSeparator
323                    i = j + 1
324                    pieces.append(.stop(number, primary, read()))
325                    continue
326                }
327                text.append(c == tab ? "\t" : c == backslash ? "\\" : c)
328                i += 1
329            }
330            if !text.isEmpty { pieces.append(.text(text)) }
331            return pieces
332        }
333        let pieces = read()
334        // Each field's text, for its mirrors.
335        var values: [Int: String] = [:]
336        func flatten(_ pieces: [Piece], depth: Int = 0) -> String {
337            pieces.map { piece -> String in
338                switch piece {
339                case .text(let text): return text
340                case .stop(let number, let primary, let children):
341                    if primary { return flatten(children, depth: depth) }
342                    return depth > 8 ? "" : (values[number] ?? "")
343                }
344            }.joined()
345        }
346        func collect(_ pieces: [Piece]) {
347            for case .stop(let number, let primary, let children) in pieces where primary {
348                collect(children)
349                values[number] = flatten(children)
350            }
351        }
352        collect(pieces)
353        // Mirrors inside defaults show values found after them; one more pass settles those.
354        collect(pieces)
355        var text = ""
356        var length = 0
357        var fields: [Int: (primary: Range<Int>?, mirrors: [Range<Int>])] = [:]
358        func render(_ pieces: [Piece]) {
359            for piece in pieces {
360                switch piece {
361                case .text(let s):
362                    text += s
363                    length += s.utf16.count
364                case .stop(let number, let primary, let children):
365                    let start = length
366                    if primary {
367                        render(children)
368                        fields[number, default: (nil, [])].primary = start..<length
369                    } else {
370                        let value = values[number] ?? ""
371                        text += value
372                        length += value.utf16.count
373                        fields[number, default: (nil, [])].mirrors.append(start..<length)
374                    }
375                }
376            }
377        }
378        render(pieces)
379        let exit = fields[0]?.primary ?? fields[0]?.mirrors.first ?? length..<length
380        let list = fields.filter { $0.key != 0 }.sorted { $0.key < $1.key }.map { number, ranges in
381            SnippetExpansion.Field(number: number, ranges: [ranges.primary ?? ranges.mirrors[0]] + (ranges.primary == nil ? Array(ranges.mirrors.dropFirst()) : ranges.mirrors))
382        }
383        return SnippetExpansion(text: text, fields: list, exit: exit)
384    }
385}
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