import Foundation import Testing @testable import OrgCore struct SnippetTests { static let utc: Calendar = { var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(identifier: "UTC")! return calendar }() /// Wednesday 2026-11-25 09:30 UTC. static let now = Date(timeIntervalSince1970: 1_795_599_000) func capture() -> CaptureContext { CaptureContext(now: Self.now, calendar: Self.utc) } func expand(_ body: String, answers: [String] = [], indentation: String = "") throws -> SnippetExpansion { try Snippets.expand(Snippet(trigger: "t", body: body), context: capture(), answers: answers, indentation: indentation).get() } func text(_ expansion: SnippetExpansion, _ range: Range) -> String { (expansion.text as NSString).substring(with: NSRange(range)) } // MARK: - snippets.toml @Test func readsAFile() throws { let (snippets, problems) = try Snippets.parse(#""" # Comments are fine. [[snippet]] trigger = "meet" description = "Meeting notes" body = """ * Meeting with ${1:someone} %U - $0 """ [[snippet]] trigger = "day" body = '%<%A>' [[snippet]] trigger = "weekly" description = "Weekly review" file = true body = ''' #+title: Week of %t ''' """#) #expect(problems.isEmpty) #expect(snippets == [ Snippet(trigger: "meet", name: "Meeting notes", body: "* Meeting with ${1:someone} %U\n- $0\n"), Snippet(trigger: "day", body: "%<%A>"), Snippet(trigger: "weekly", name: "Weekly review", body: "#+title: Week of %t\n", file: true), ]) #expect(snippets[2].commandID == "org.snippet:weekly" && Snippets.trigger(ofCommand: "org.snippet:weekly") == "weekly") } @Test func reportsWhereAFileIsWrong() throws { #expect(throws: TOML.ParseError(line: 3, message: "unclosed string")) { try Snippets.parse("[[snippet]]\ntrigger = \"a\"\nbody = \"\"\"\nnever closed\n") } #expect(throws: TOML.ParseError(line: 2, message: "unclosed string")) { try Snippets.parse("[[snippet]]\ntrigger = \"a\n") } let (snippets, problems) = try Snippets.parse(""" [[snippet]] trigger = "ok" body = "fine" [[snippet]] body = "no trigger" [[snippet]] trigger = "two words" body = "x" [[snippet]] trigger = "lisp" body = "${1:$(upcase yas-text)}" [[snippet]] trigger = "open" body = "${1:never closed" [[snippet]] trigger = "ok" body = "again" [snippets] """) #expect(snippets.map(\.trigger) == ["ok"]) #expect(problems == [ "line 4: a snippet needs trigger and body", "line 6: a trigger has no spaces", "line 9: Emacs Lisp in a field isn't supported", "line 12: a ${ isn't closed", "line 15: trigger ok is used twice", "line 18: expected [[snippet]]", ]) } @Test func multilineStringsFollowTOML() throws { let tables = try TOML.parse("a = \"\"\"\none \\\n two\\tthree\"\"\"\nb = '''x\\n'''\nc = \"\"\"same line\"\"\" # note\n") #expect(tables[0].values["a"] == .string("one two\tthree")) #expect(tables[0].values["b"] == .string("x\\n")) #expect(tables[0].values["c"] == .string("same line")) } // MARK: - Bodies @Test func fieldsDefaultsAndMirrors() throws { let e = try expand("a ${1:foo} b $1 c ${2:bar} $0 d") #expect(e.text == "a foo b foo c bar d") #expect(e.fields.map(\.number) == [1, 2]) #expect(e.fields[0].ranges.map { text(e, $0) } == ["foo", "foo"]) #expect(e.fields[0].ranges[0] == 2..<5 && e.fields[0].ranges[1] == 8..<11) #expect(text(e, e.fields[1].ranges[0]) == "bar" && e.fields[1].ranges.count == 1) #expect(e.exit == 18..<18) } @Test func theFieldIsTheOccurrenceWithADefault() throws { // As yasnippet: `$1` before `${1:x}` mirrors it. let e = try expand("$1 then ${1:x}") #expect(e.text == "x then x") #expect(e.fields[0].ranges == [7..<8, 0..<1]) let empty = try expand("$2 and $2") #expect(empty.text == " and " && empty.fields[0].ranges == [0..<0, 5..<5]) } @Test func escapesAndExits() throws { #expect(try expand(#"cost \$1 \\ ${1:x\}y} $1"#).text == #"cost $1 \ x}y x}y"#) #expect(try expand("no fields").exit == 9..<9) let selected = try expand("${0:end} $1") #expect(text(selected, selected.exit) == "end") // `%?` of capture is the exit too. #expect(try expand("ab%?cd").exit == 2..<2) // Tabs and blank lines stay as written. #expect(try expand("\n\tx $1\n\n").text == "\n\tx \n\n") } @Test func captureEscapesFill() throws { #expect(try expand("%t %U %<%A>").text == "<2026-11-25 Wed> [2026-11-25 Wed 09:30] Wednesday") #expect(try expand("${1:%u} $1").text == "[2026-11-25 Wed] [2026-11-25 Wed]") // An escaped escape stays. #expect(try expand(#"\%t"#).text == "%t") } @Test func promptsAreAskedInOrder() throws { let snippet = Snippet(trigger: "p", body: "* %^{Title} $1\n%^{Where|home|home|work} %^t %\\1") let questions = Snippets.questions(snippet, context: capture()) #expect(questions.map(\.prompt) == ["Title", "Where", "Date"]) #expect(questions[1].defaultValue == "home" && questions[1].choices == ["home", "work"]) #expect(Snippets.prompt(questions[2], key: "snippet-2").date == .init(defaultDate: nil)) let e = try Snippets.expand(snippet, context: capture(), answers: ["Plan", "", "+1d"]).get() #expect(e.text == "* Plan \nhome <2026-11-26 Thu> Plan") #expect(e.fields[0].ranges == [7..<7]) } @Test func linesAfterTheFirstTakeTheIndentation() throws { let e = try expand("- ${1:a}\n- $1", indentation: " ") #expect(e.text == "- a\n - a") #expect(e.fields[0].ranges == [2..<3, 8..<9]) } // MARK: - Triggers @Test func triggerBeforeTheCaret() { let snippets = [Snippet(trigger: "date", body: "%t"), Snippet(trigger: " String? { Snippets.trigger(before: text.utf16.count, in: text, snippets: snippets).map { "\($0.snippet.trigger)@\($0.range.lowerBound)" } } #expect(found("today date") == "date@6") #expect(found("(date") == "date@1") #expect(found("x? = nil, snippets: [Snippet], answers: [String: String] = [:]) -> EditContext { var options = EditingOptions.org options.snippets = snippets let caret = caret ?? text.utf16.count return EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection ?? caret.. Steps { let e = try expand(body) var session = SnippetSession(e, at: 0) var text = e.text var steps = Steps(text: [text], point: [session?.selection.lowerBound ?? e.exit.lowerBound]) type("XY", into: &text, &session, caret: e.exit.lowerBound) var point = (session?.selection.lowerBound ?? e.exit.lowerBound) + 2 steps.text.append(text) steps.point.append(point) for _ in 0..<2 { if var current = session { switch current.next() { case .field(let range): point = range.lowerBound session = current case .exit(let range): point = range.lowerBound session = nil } } steps.point.append(point) } return steps } @Test(.enabled(if: oracle)) func matchesYasnippet() throws { func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" } let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-yas-\(UUID().uuidString)") try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: folder) } let output = folder.appendingPathComponent("out.json") let script = folder.appendingPathComponent("yas.el") try """ ;;; -*- lexical-binding: t -*- (add-to-list 'load-path \(lisp(Self.yasnippet!))) (require 'yasnippet) (require 'json) (setq yas-indent-line nil) (let (out) (dolist (body (list \(Self.bodies.map(lisp).joined(separator: " ")))) (with-temp-buffer (yas-minor-mode 1) (yas-expand-snippet body) (let ((texts (list (buffer-string))) (points (list (1- (point))))) (insert "XY") (run-hooks 'post-command-hook) (push (buffer-string) texts) (push (1- (point)) points) (dotimes (_ 2) (ignore-errors (yas-next-field)) (push (1- (point)) points)) (push `((text . ,(vconcat (nreverse texts))) (point . ,(vconcat (nreverse points)))) out)))) (with-temp-file \(lisp(output.path)) (insert (json-encode (nreverse out))))) """.write(to: script, atomically: true, encoding: .utf8) _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path]) let theirs = try JSONDecoder().decode([Steps].self, from: Data(contentsOf: output)) for (body, expected) in zip(Self.bodies, theirs) { let mine = try ours(body) #expect(mine == expected, "\(body): \(mine) against \(expected)") } } }