Tests/OrgCoreTests/SnippetTests.swift

e2e03d8e64769c76d83334a767f4c950947f47b1
orgstar/Tests/OrgCoreTests/SnippetTests.swift

393 lines · 18638 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct SnippetTests {
  6    static let utc: Calendar = {
  7        var calendar = Calendar(identifier: .gregorian)
  8        calendar.timeZone = TimeZone(identifier: "UTC")!
  9        return calendar
 10    }()
 11    /// Wednesday 2026-11-25 09:30 UTC.
 12    static let now = Date(timeIntervalSince1970: 1_795_599_000)
 13
 14    func capture() -> CaptureContext { CaptureContext(now: Self.now, calendar: Self.utc) }
 15
 16    func expand(_ body: String, answers: [String] = [], indentation: String = "") throws -> SnippetExpansion {
 17        try Snippets.expand(Snippet(trigger: "t", body: body), context: capture(), answers: answers, indentation: indentation).get()
 18    }
 19
 20    func text(_ expansion: SnippetExpansion, _ range: Range<Int>) -> String {
 21        (expansion.text as NSString).substring(with: NSRange(range))
 22    }
 23
 24    // MARK: - snippets.toml
 25
 26    @Test func readsAFile() throws {
 27        let (snippets, problems) = try Snippets.parse(#"""
 28            # Comments are fine.
 29            [[snippet]]
 30            trigger = "meet"
 31            description = "Meeting notes"
 32            body = """
 33            * Meeting with ${1:someone} %U
 34            - $0
 35            """
 36
 37            [[snippet]]
 38            trigger = "day"
 39            body = '%<%A>'
 40
 41            [[snippet]]
 42            trigger = "weekly"
 43            description = "Weekly review"
 44            file = true
 45            body = '''
 46            #+title: Week of %t
 47            '''
 48            """#)
 49        #expect(problems.isEmpty)
 50        #expect(snippets == [
 51            Snippet(trigger: "meet", name: "Meeting notes", body: "* Meeting with ${1:someone} %U\n- $0\n"),
 52            Snippet(trigger: "day", body: "%<%A>"),
 53            Snippet(trigger: "weekly", name: "Weekly review", body: "#+title: Week of %t\n", file: true),
 54        ])
 55        #expect(snippets[2].commandID == "org.snippet:weekly" && Snippets.trigger(ofCommand: "org.snippet:weekly") == "weekly")
 56    }
 57
 58    @Test func reportsWhereAFileIsWrong() throws {
 59        #expect(throws: TOML.ParseError(line: 3, message: "unclosed string")) {
 60            try Snippets.parse("[[snippet]]\ntrigger = \"a\"\nbody = \"\"\"\nnever closed\n")
 61        }
 62        #expect(throws: TOML.ParseError(line: 2, message: "unclosed string")) { try Snippets.parse("[[snippet]]\ntrigger = \"a\n") }
 63        let (snippets, problems) = try Snippets.parse("""
 64            [[snippet]]
 65            trigger = "ok"
 66            body = "fine"
 67            [[snippet]]
 68            body = "no trigger"
 69            [[snippet]]
 70            trigger = "two words"
 71            body = "x"
 72            [[snippet]]
 73            trigger = "lisp"
 74            body = "${1:$(upcase yas-text)}"
 75            [[snippet]]
 76            trigger = "open"
 77            body = "${1:never closed"
 78            [[snippet]]
 79            trigger = "ok"
 80            body = "again"
 81            [snippets]
 82            """)
 83        #expect(snippets.map(\.trigger) == ["ok"])
 84        #expect(problems == [
 85            "line 4: a snippet needs trigger and body", "line 6: a trigger has no spaces",
 86            "line 9: Emacs Lisp in a field isn't supported", "line 12: a ${ isn't closed",
 87            "line 15: trigger ok is used twice", "line 18: expected [[snippet]]",
 88        ])
 89    }
 90
 91    @Test func multilineStringsFollowTOML() throws {
 92        let tables = try TOML.parse("a = \"\"\"\none \\\n   two\\tthree\"\"\"\nb = '''x\\n'''\nc = \"\"\"same line\"\"\" # note\n")
 93        #expect(tables[0].values["a"] == .string("one two\tthree"))
 94        #expect(tables[0].values["b"] == .string("x\\n"))
 95        #expect(tables[0].values["c"] == .string("same line"))
 96    }
 97
 98    // MARK: - Bodies
 99
100    @Test func fieldsDefaultsAndMirrors() throws {
101        let e = try expand("a ${1:foo} b $1 c ${2:bar} $0 d")
102        #expect(e.text == "a foo b foo c bar  d")
103        #expect(e.fields.map(\.number) == [1, 2])
104        #expect(e.fields[0].ranges.map { text(e, $0) } == ["foo", "foo"])
105        #expect(e.fields[0].ranges[0] == 2..<5 && e.fields[0].ranges[1] == 8..<11)
106        #expect(text(e, e.fields[1].ranges[0]) == "bar" && e.fields[1].ranges.count == 1)
107        #expect(e.exit == 18..<18)
108    }
109
110    @Test func theFieldIsTheOccurrenceWithADefault() throws {
111        // As yasnippet: `$1` before `${1:x}` mirrors it.
112        let e = try expand("$1 then ${1:x}")
113        #expect(e.text == "x then x")
114        #expect(e.fields[0].ranges == [7..<8, 0..<1])
115        let empty = try expand("$2 and $2")
116        #expect(empty.text == " and " && empty.fields[0].ranges == [0..<0, 5..<5])
117    }
118
119    @Test func escapesAndExits() throws {
120        #expect(try expand(#"cost \$1 \\ ${1:x\}y} $1"#).text == #"cost $1 \ x}y x}y"#)
121        #expect(try expand("no fields").exit == 9..<9)
122        let selected = try expand("${0:end} $1")
123        #expect(text(selected, selected.exit) == "end")
124        // `%?` of capture is the exit too.
125        #expect(try expand("ab%?cd").exit == 2..<2)
126        // Tabs and blank lines stay as written.
127        #expect(try expand("\n\tx $1\n\n").text == "\n\tx \n\n")
128    }
129
130    @Test func captureEscapesFill() throws {
131        #expect(try expand("%t %U %<%A>").text == "<2026-11-25 Wed> [2026-11-25 Wed 09:30] Wednesday")
132        #expect(try expand("${1:%u} $1").text == "[2026-11-25 Wed] [2026-11-25 Wed]")
133        // An escaped escape stays.
134        #expect(try expand(#"\%t"#).text == "%t")
135    }
136
137    @Test func promptsAreAskedInOrder() throws {
138        let snippet = Snippet(trigger: "p", body: "* %^{Title} $1\n%^{Where|home|home|work} %^t %\\1")
139        let questions = Snippets.questions(snippet, context: capture())
140        #expect(questions.map(\.prompt) == ["Title", "Where", "Date"])
141        #expect(questions[1].defaultValue == "home" && questions[1].choices == ["home", "work"])
142        #expect(Snippets.prompt(questions[2], key: "snippet-2").date == .init(defaultDate: nil))
143        let e = try Snippets.expand(snippet, context: capture(), answers: ["Plan", "", "+1d"]).get()
144        #expect(e.text == "* Plan \nhome <2026-11-26 Thu> Plan")
145        #expect(e.fields[0].ranges == [7..<7])
146    }
147
148    @Test func linesAfterTheFirstTakeTheIndentation() throws {
149        let e = try expand("- ${1:a}\n- $1", indentation: "  ")
150        #expect(e.text == "- a\n  - a")
151        #expect(e.fields[0].ranges == [2..<3, 8..<9])
152    }
153
154    // MARK: - Triggers
155
156    @Test func triggerBeforeTheCaret() {
157        let snippets = [Snippet(trigger: "date", body: "%t"), Snippet(trigger: "<d", body: "x"), Snippet(trigger: "file", body: "x", file: true)]
158        func found(_ text: String) -> String? {
159            Snippets.trigger(before: text.utf16.count, in: text, snippets: snippets).map { "\($0.snippet.trigger)@\($0.range.lowerBound)" }
160        }
161        #expect(found("today date") == "date@6")
162        #expect(found("(date") == "date@1")
163        #expect(found("x<d") == nil)
164        #expect(found("<d") == "<d@0")
165        #expect(found("update") == nil)
166        #expect(found("date ") == nil)
167        #expect(found("file") == nil)
168    }
169
170    // MARK: - Commands
171
172    func context(_ text: String, caret: Int? = nil, selection: Range<Int>? = nil, snippets: [Snippet], answers: [String: String] = [:]) -> EditContext {
173        var options = EditingOptions.org
174        options.snippets = snippets
175        let caret = caret ?? text.utf16.count
176        return EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection ?? caret..<caret],
177                           now: Self.now, calendar: Self.utc, answers: answers, options: options)
178    }
179
180    @Test func expandingReplacesTheTriggerAndStartsASession() throws {
181        let snippets = [Snippet(trigger: "todo", body: "TODO ${1:what} by ${2:when}$0")]
182        let ctx = context("* todo", snippets: snippets)
183        #expect(ExpandSnippet().applies(in: ctx))
184        guard case .commit(let result) = ExpandSnippet().run(in: ctx) else { Issue.record("no commit"); return }
185        #expect(result.edits == [TextEdit(range: 2..<6, replacement: "TODO what by when")])
186        #expect(result.selection == [7..<11])
187        guard case .snippet(let session) = result.effects.first else { Issue.record("no session"); return }
188        #expect(session.fields.map(\.ranges) == [[7..<11], [15..<19]] && session.extent == 2..<19)
189        #expect(!ExpandSnippet().applies(in: context("* todo ", snippets: snippets)))
190        #expect(!ExpandSnippet().applies(in: context("* todo", selection: 2..<6, snippets: snippets)))
191    }
192
193    @Test func promptsComeBackAsAnswers() throws {
194        let snippets = [Snippet(trigger: "m", body: "Meet %^{Who}: $0")]
195        guard case .prompt(let prompt) = ExpandSnippet().run(in: context("m", snippets: snippets)) else { Issue.record("no prompt"); return }
196        #expect(prompt.key == "snippet-0" && prompt.message == "Who: ")
197        guard case .commit(let result) = ExpandSnippet().run(in: context("m", snippets: snippets, answers: ["snippet-0": "Ana"])) else {
198            Issue.record("no commit")
199            return
200        }
201        #expect(result.edits.first?.replacement == "Meet Ana: " && result.selection == [10..<10] && result.effects.isEmpty)
202    }
203
204    @Test func insertSnippetChoosesByNameAndWrapsTheSelection() throws {
205        let snippets = [Snippet(trigger: "q", name: "Quote", body: "#+begin_quote\n%i$0\n#+end_quote"), Snippet(trigger: "f", body: "x", file: true)]
206        guard case .prompt(let prompt) = InsertSnippet().run(in: context("hello", selection: 0..<5, snippets: snippets)) else { Issue.record("no prompt"); return }
207        #expect(prompt.choices == ["Quote (q)"])
208        guard case .commit(let result) = InsertSnippet().run(in: context("hello", selection: 0..<5, snippets: snippets, answers: ["snippet": "Quote (q)"])) else {
209            Issue.record("no commit")
210            return
211        }
212        #expect(result.edits == [TextEdit(range: 0..<5, replacement: "#+begin_quote\nhello\n#+end_quote")])
213        #expect(!InsertSnippet().applies(in: context("", snippets: [snippets[1]])))
214        // The named command reaches file templates too.
215        #expect(Snippets.command("org.snippet:f")?.applies(in: context("", snippets: snippets)) == true)
216        #expect(Snippets.command("org.cycle") == nil)
217    }
218
219    // MARK: - Sessions
220
221    /// The buffer and session after typing `typed` over the active field, as the editors do it:
222    /// the edit, then the mirrors.
223    func type(_ typed: String, into text: inout String, _ session: inout SnippetSession?, caret: Int? = nil) {
224        let end = caret ?? text.utf16.count
225        let range = session?.selection ?? (end..<end)
226        let edit = TextEdit(range: range, replacement: typed)
227        text = edit.apply(to: text)
228        if session?.map(edit) == false { session = nil }
229        guard let current = session else { return }
230        for mirror in current.mirrorEdits(in: text).reversed() {
231            text = mirror.apply(to: text)
232            if session?.map(mirror) == false { session = nil }
233        }
234    }
235
236    @Test func tabStopsAsAStateMachine() throws {
237        let e = try expand("a ${1:foo} b $1 c ${2:bar} $0 d")
238        var session = SnippetSession(e, at: 2)
239        var text = "x " + e.text
240        #expect(session?.selection == 4..<7)
241        type("XY", into: &text, &session)
242        #expect(text == "x a XY b XY c bar  d")
243        #expect(session?.fields[0].ranges == [4..<6, 9..<11])
244        // Typing at the end of the field goes into it.
245        let end = TextEdit(range: 6..<6, replacement: "Z")
246        text = end.apply(to: text)
247        let mapped = session?.map(end)
248        #expect(mapped == true)
249        for mirror in session!.mirrorEdits(in: text).reversed() {
250            text = mirror.apply(to: text)
251            let kept = session?.map(mirror)
252            #expect(kept == true)
253        }
254        #expect(text == "x a XYZ b XYZ c bar  d")
255        let next = session?.next()
256        #expect(next == .field(16..<19))
257        let back = session?.previous(), first = session?.previous()
258        #expect(back == 4..<7 && first == 4..<7)
259    }
260
261    @Test func leavingEndsTheSession() throws {
262        let e = try expand("${1:a} ${2:b}$0!")
263        var session = SnippetSession(e, at: 10)!
264        let second = session.next(), last = session.next()
265        #expect(second == .field(12..<13) && last == .exit(13..<13))
266        #expect(session.contains(10) && session.contains(14) && !session.contains(9) && !session.contains(15))
267        // An edit outside the snippet ends it; one inside moves it.
268        var moved = session
269        let outside = moved.map(TextEdit(range: 0..<1, replacement: ""))
270        let inside = session.map(TextEdit(range: 11..<11, replacement: "--"))
271        #expect(!outside && inside)
272        #expect(session.fields.map(\.ranges) == [[10..<11], [14..<15]] && session.exit == 15..<15)
273        #expect(SnippetSession(try expand("no fields$0"), at: 0) == nil)
274    }
275
276    @Test func mirrorsFollowAnEmptyField() throws {
277        let e = try expand("$1-$1-$1")
278        var session = SnippetSession(e, at: 0)
279        var text = e.text
280        type("ab", into: &text, &session)
281        #expect(text == "ab-ab-ab")
282        type("", into: &text, &session)
283        #expect(text == "--")
284    }
285
286    // MARK: - Completion
287
288    @Test func completionOffersSnippetsWhereOrgOffersNothing() {
289        let snippets = [Snippet(trigger: "meet", name: "Meeting notes", body: "x"), Snippet(trigger: "memo", body: "y"), Snippet(trigger: "mt", body: "z", file: true)]
290        let c = OrgCompletion.at(context("Notes me", snippets: snippets))
291        #expect(c?.kind == .snippet && c?.candidates == ["meet", "memo"] && c?.range == 6..<8)
292        #expect(c?.label("meet") == "meet  Meeting notes" && c?.label("memo") == "memo")
293        // Org's own contexts come first.
294        #expect(OrgCompletion.at(context("#+TI", snippets: snippets))?.kind == .keyword)
295        #expect(OrgCompletion.at(context("plain", snippets: snippets)) == nil)
296        #expect(OrgCompletion.at(context("me", snippets: []))  == nil)
297    }
298
299    // MARK: - yasnippet
300
301    /// yasnippet's folder, for comparing expansions with it: `ORGSTAR_YASNIPPET`, else one a
302    /// Doom or package.el install has.
303    static let yasnippet: String? = {
304        if let path = ProcessInfo.processInfo.environment["ORGSTAR_YASNIPPET"] { return path }
305        let home = FileManager.default.homeDirectoryForCurrentUser
306        for base in [".config/emacs/.local/straight", ".emacs.d/.local/straight", ".emacs.d/elpa"] {
307            let folder = home.appendingPathComponent(base)
308            for entry in (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? [] {
309                for candidate in [folder.appendingPathComponent(entry).appendingPathComponent("yasnippet"), folder.appendingPathComponent(entry)]
310                where FileManager.default.fileExists(atPath: candidate.appendingPathComponent("yasnippet.el").path) {
311                    return candidate.path
312                }
313            }
314        }
315        return nil
316    }()
317
318    static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && yasnippet != nil
319
320    static let bodies = [
321        "a ${1:foo} b $1 c ${2:bar} $0 d", "${1:x} and $2 then $1$2 end", "no fields $0 here", "plain",
322        "${2:second} ${1:first} $0", #"\$1 \\ ${1:x\}y} $1"#, "${1:a}$1", "line1 ${1:x}\nline2 $1\n$0",
323    ]
324
325    /// After expanding, after typing `XY`, and after each of two `yas-next-field`: the text and
326    /// point (0-based).
327    struct Steps: Codable, Equatable {
328        var text: [String]
329        var point: [Int]
330    }
331
332    func ours(_ body: String) throws -> Steps {
333        let e = try expand(body)
334        var session = SnippetSession(e, at: 0)
335        var text = e.text
336        var steps = Steps(text: [text], point: [session?.selection.lowerBound ?? e.exit.lowerBound])
337        type("XY", into: &text, &session, caret: e.exit.lowerBound)
338        var point = (session?.selection.lowerBound ?? e.exit.lowerBound) + 2
339        steps.text.append(text)
340        steps.point.append(point)
341        for _ in 0..<2 {
342            if var current = session {
343                switch current.next() {
344                case .field(let range):
345                    point = range.lowerBound
346                    session = current
347                case .exit(let range):
348                    point = range.lowerBound
349                    session = nil
350                }
351            }
352            steps.point.append(point)
353        }
354        return steps
355    }
356
357    @Test(.enabled(if: oracle)) func matchesYasnippet() throws {
358        func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
359        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-yas-\(UUID().uuidString)")
360        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
361        defer { try? FileManager.default.removeItem(at: folder) }
362        let output = folder.appendingPathComponent("out.json")
363        let script = folder.appendingPathComponent("yas.el")
364        try """
365            ;;; -*- lexical-binding: t -*-
366            (add-to-list 'load-path \(lisp(Self.yasnippet!)))
367            (require 'yasnippet)
368            (require 'json)
369            (setq yas-indent-line nil)
370            (let (out)
371              (dolist (body (list \(Self.bodies.map(lisp).joined(separator: " "))))
372                (with-temp-buffer
373                  (yas-minor-mode 1)
374                  (yas-expand-snippet body)
375                  (let ((texts (list (buffer-string))) (points (list (1- (point)))))
376                    (insert "XY")
377                    (run-hooks 'post-command-hook)
378                    (push (buffer-string) texts)
379                    (push (1- (point)) points)
380                    (dotimes (_ 2)
381                      (ignore-errors (yas-next-field))
382                      (push (1- (point)) points))
383                    (push `((text . ,(vconcat (nreverse texts))) (point . ,(vconcat (nreverse points)))) out))))
384              (with-temp-file \(lisp(output.path)) (insert (json-encode (nreverse out)))))
385            """.write(to: script, atomically: true, encoding: .utf8)
386        _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path])
387        let theirs = try JSONDecoder().decode([Steps].self, from: Data(contentsOf: output))
388        for (body, expected) in zip(Self.bodies, theirs) {
389            let mine = try ours(body)
390            #expect(mine == expected, "\(body): \(mine) against \(expected)")
391        }
392    }
393}
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