Tests/OrgCoreTests/CompletionListTests.swift
209 lines · 12660 bytes
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// The list that opens by itself (#139), fuzzy matching (#140), word completion (#141) and
6/// completion from the index (#143).
7struct CompletionListTests {
8 func context(_ text: String, _ caret: Int? = nil, options: EditingOptions = .org) -> EditContext {
9 let caret = caret ?? text.utf16.count
10 return EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], options: options)
11 }
12
13 var fuzzy: EditingOptions {
14 var options = EditingOptions.org
15 options.completion.fuzzy = true
16 return options
17 }
18
19 // MARK: - #139
20
21 @Test func autoOpensOnlyWhenSetAndInInsertState() {
22 let off = CompletionOptions()
23 #expect(CompletionAuto.delay(off, modal: false, insertState: false, isOrg: true) == nil)
24 #expect(CompletionAuto.delay(off, modal: true, insertState: true, isOrg: true) == nil)
25 let on = CompletionOptions(auto: true, delay: 0.25, prefix: 3)
26 #expect(CompletionAuto.delay(on, modal: false, insertState: false, isOrg: true) == 0.25)
27 #expect(CompletionAuto.delay(on, modal: true, insertState: true, isOrg: true) == 0.25)
28 #expect(CompletionAuto.delay(on, modal: true, insertState: false, isOrg: true) == nil)
29 // Outside org files only words are offered.
30 #expect(CompletionAuto.delay(on, modal: false, insertState: false, isOrg: false) == nil)
31 #expect(CompletionAuto.delay(CompletionOptions(auto: true, words: true), modal: false, insertState: false, isOrg: false) == 0.4)
32 }
33
34 @Test func autoOpensOnceEnoughIsTyped() {
35 let options = CompletionOptions(auto: true, prefix: 3)
36 #expect(!CompletionAuto.opens(OrgCompletion.at(context("#+TI")), options))
37 #expect(CompletionAuto.opens(OrgCompletion.at(context("#+TIT")), options))
38 #expect(!CompletionAuto.opens(OrgCompletion.at(context("#+XYZQ")), options))
39 #expect(!CompletionAuto.opens(nil, options))
40 // An index query opens it before anything is found.
41 #expect(CompletionAuto.opens(OrgCompletion.at(context("[[id:abc")), options))
42 }
43
44 // MARK: - #140
45
46 @Test func fuzzyMatchesLettersInOrderBestFirst() {
47 #expect(OrgCompletion.at(context("#+STARTUP: lgd"))?.candidates == [])
48 let found = OrgCompletion.at(context("#+STARTUP: lgd", options: fuzzy))!.candidates
49 #expect(found.first == "logdone" && found.contains("lognotedone") && found.contains("nologdone"))
50 #expect(found.firstIndex(of: "logdone")! < found.firstIndex(of: "nologdone")!)
51 // Word starts and runs rank first; the prefix match beats one inside a word.
52 #expect(OrgCompletion.matching(["nofold", "fold", "fnadjust"], "fo", fuzzy: true) == ["fold", "nofold"])
53 // Keywords in the case typed.
54 #expect(OrgCompletion.at(context("#+ttl", options: fuzzy))!.candidates.allSatisfy { $0 == $0.lowercased() })
55 #expect(OrgCompletion.at(context("#+ttl", options: fuzzy))!.candidates.contains("title: "))
56 // Prefix matching stays as it was.
57 #expect(OrgCompletion.at(context("#+STARTUP: in"))?.candidates == ["indent", "inlineimages"])
58 }
59
60 @Test func fuzzyMatchesSnippetTriggers() {
61 var options = fuzzy
62 options.snippets = [Snippet(trigger: "meeting", name: "Meeting", body: "x"), Snippet(trigger: "todo", name: "Todo", body: "y")]
63 #expect(OrgCompletion.at(context("mtg", options: options))?.candidates == ["meeting"])
64 }
65
66 @Test func listKeysAndTheCommonPart() {
67 var list = CompletionList(OrgCompletion.at(context("#+STARTUP: entities"))!)
68 #expect(list.key(KeyChord("TAB")) == .common("entitiesp"))
69 #expect(list.key(KeyChord("n", .control)) == .shown && list.selected == "entitiesplain")
70 #expect(list.key(KeyChord("p", .control)) == .shown && list.selected == nil)
71 #expect(list.key(KeyChord("p", .control)) == .shown && list.selected == "entitiespretty")
72 #expect(list.key(KeyChord("RET")) == .insert("entitiespretty"))
73 #expect(list.key(KeyChord("g", .control)) == .close)
74 #expect(list.key(KeyChord("ESC")) == .closeAndPass)
75 // The chosen candidate stays chosen when more arrive.
76 list.update(OrgCompletion.at(context("#+STARTUP: e"))!)
77 #expect(list.selected == "entitiespretty")
78 // Fuzzy candidates that don't start alike don't shorten what's typed.
79 let spread = OrgCompletion.at(context("#+STARTUP: nd", options: fuzzy))!
80 var fuzzyList = CompletionList(spread)
81 #expect(fuzzyList.key(KeyChord("TAB")) == .shown)
82 }
83
84 // MARK: - #141
85
86 @Test func dabbrevSearchesBackThenForward() {
87 let text = "fa fb\nf fc fd"
88 let caret = 7
89 #expect(DabbrevExpansion(context(text, caret))?.expansions == ["fb", "fa", "fc", "fd"])
90 #expect(Dabbrev.completion(context(text, caret))?.candidates == ["fb", "fa", "fc", "fd"])
91 // Other buffers after this one, from their start; each word once, ignoring case.
92 let more = Dabbrev.completion(context("Foo\nf"), others: ["fun FOO fix"])!
93 #expect(more.candidates == ["foo", "fun", "fix"] && more.range == 4..<5 && more.query == .words("f"))
94 // Org's word characters.
95 #expect(DabbrevExpansion(context("fo_x fo-y fo.z fo'w fo/v fo2\nfo"))?.expansions == ["fo2", "fo/v", "fo'w", "fo-y", "fo_x"])
96 #expect(DabbrevExpansion(context("*bold*\nb"))?.expansions == [])
97 #expect(DabbrevExpansion(context("x ")) == nil)
98 }
99
100 @Test func dabbrevCyclesAndRestores() {
101 var expansion = DabbrevExpansion(context("help hello\nhe"))!
102 #expect(expansion.advance() == (TextEdit(range: 11..<13, replacement: "hello"), false))
103 #expect(expansion.advance() == (TextEdit(range: 11..<16, replacement: "help"), false))
104 expansion.add(["helmet", "Hello"])
105 #expect(expansion.advance() == (TextEdit(range: 11..<15, replacement: "helmet"), false))
106 #expect(expansion.advance() == (TextEdit(range: 11..<17, replacement: "he"), true))
107 #expect(expansion.failure == "No further dynamic expansion for `he' found")
108 }
109
110 @Test func dabbrevCase() {
111 #expect(Dabbrev.substitute("Hello", for: "he", replacing: "he") == "hello")
112 #expect(Dabbrev.substitute("hello", for: "HE", replacing: "HE") == "HELLO")
113 #expect(Dabbrev.substitute("HeLp", for: "He", replacing: "He") == "HeLp")
114 #expect(Dabbrev.substitute("hex", for: "He", replacing: "Hello") == "Hex")
115 #expect(Dabbrev.substitute("fooBar", for: "foo", replacing: "foo") == "fooBar")
116 #expect(Dabbrev.substitute("alpine", for: "Al", replacing: "Al") == "Alpine")
117 #expect(Dabbrev.substitute("12ab", for: "12", replacing: "12") == "12ab")
118 }
119
120 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
121
122 /// `dabbrev-expand` repeated in a buffer alone: each expansion, then the message.
123 static let dabbrevCases: [String] = [
124 "fa fb\nf| fc fd", "Hello help\nhe|", "Hello HELP hex\nHE|", "Hello HeLp hex\nHe|", "fooBar\nfoo|", "alpha alpine\nAl|",
125 "Foo foo FOO\nf|", "fo_x fo-y fo.z fo'w fo/v fo2\nfo|", "12ab 12cd\n12|", "*bold* =code= ~x~\nb|", "abc ab\nab|",
126 "naïve naïf\nna|", "* Heading one\n:PROPERTIES:\n:CATEGORY: head\n:END:\nHe|", "The THEME theory\nth|", "x A Apple\nA|",
127 ]
128
129 @Test(.enabled(if: oracle && EmacsOracle.isAvailable))
130 func dabbrevMatchesEmacs() throws {
131 let form = """
132 (progn (require 'dabbrev) (let ((dabbrev-check-other-buffers nil) (dabbrev-check-all-buffers nil) (start nil) (out nil) (done nil))
133 (save-excursion (setq start (progn (skip-syntax-backward "w_") (point))))
134 (setq last-command nil)
135 (while (and (not done) (< (length out) 12))
136 (condition-case e
137 (progn (setq this-command 'dabbrev-expand) (dabbrev-expand nil) (setq last-command 'dabbrev-expand)
138 (push (buffer-substring-no-properties start (point)) out))
139 (error (push (error-message-string e) out) (setq done t))))
140 (erase-buffer)
141 (insert (mapconcat #'identity (nreverse out) "\\n"))))
142 """
143 let cases = Self.dabbrevCases.map { marked -> (String, Int) in
144 let caret = (marked as NSString).range(of: "|").location
145 return (marked.replacingOccurrences(of: "|", with: ""), caret)
146 }
147 let results = try EmacsOracle.run(cases.map { EmacsOracle.Case(text: $0.0, point: EmacsOracle.point($0.1, in: $0.0) , form: form) })
148 for ((text, caret), result) in zip(cases, results) {
149 var expansion = DabbrevExpansion(context(text, caret))!
150 var ours: [String] = []
151 while true {
152 let (edit, exhausted) = expansion.advance()
153 if exhausted {
154 ours.append(expansion.failure)
155 break
156 }
157 ours.append(edit.replacement)
158 }
159 #expect(ours.joined(separator: "\n") == result.text, "\(text.debugDescription)")
160 }
161 }
162
163 // MARK: - #143
164
165 @Test func idLinksCompleteHeadingsFromTheBufferThenTheIndex() {
166 var options = fuzzy
167 options.filePath = "/notes/here.org"
168 let text = "* Alpha\n:PROPERTIES:\n:ID: a1\n:END:\n* Beta\nSee [[id:al]]"
169 let completion = OrgCompletion.at(context(text, text.utf16.count - 2, options: options))!
170 #expect(completion.kind == .idLink && completion.typed == "al" && completion.query == .linkTargets)
171 #expect(completion.candidates == ["Alpha"])
172 #expect(completion.link == 46..<55)
173 let other = CompletionItem(title: "All hands", id: nil, path: "/notes/other.org", start: 10, heading: true)
174 let twin = CompletionItem(title: "Alpha", id: "a2", path: "/notes/other.org", start: 40, heading: true)
175 let filled = OrgCompletion.filled(completion, with: CompletionResult(items: [other, twin]), fuzzy: true)
176 #expect(Set(filled.candidates) == ["Alpha (here.org)", "Alpha (other.org)", "All hands"])
177 #expect(filled.item("All hands") == other && filled.label("All hands") == "All hands other.org")
178 // A heading here without an ID gets one, and the link moves with the drawer.
179 let beta = CompletionItem(title: "Beta", id: nil, path: "/notes/here.org", start: 35, heading: true)
180 let edits = CompletionFlow.createID(beta, in: context(text, options: options), newID: "b1")!
181 let link = CompletionFlow.linkEdit(completion, beta, id: "b1", after: edits)
182 var result = text
183 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { result = edit.apply(to: result) }
184 result = link.apply(to: result)
185 #expect(result == "* Alpha\n:PROPERTIES:\n:ID: a1\n:END:\n* Beta\n:PROPERTIES:\n:ID: b1\n:END:\nSee [[id:b1][Beta]]")
186 }
187
188 @Test func denoteLinksAskTheIndex() {
189 let completion = OrgCompletion.at(context("[[denote:"))!
190 #expect(completion.kind == .denoteLink && completion.candidates.isEmpty && completion.query == .denoteNotes)
191 let note = CompletionItem(title: "Reading list", id: "20260101T090000", path: "/n/20260101T090000--reading-list.org", start: 0, heading: false)
192 let filled = OrgCompletion.filled(completion, with: CompletionResult(items: [note]), fuzzy: false)
193 #expect(filled.candidates == ["Reading list"] && filled.link(note, id: note.id!) == "[[denote:20260101T090000][Reading list]]")
194 }
195
196 @Test func propertyValuesFromTheBufferAllowedFirst() {
197 let text = "#+PROPERTY: Status_ALL todo \"in progress\" done\n* A\n:PROPERTIES:\n:Status: waiting\n:END:\n* B\n:PROPERTIES:\n:Status: i\n:END:\n"
198 let caret = (text as NSString).range(of: ":Status: i").location + 10
199 let completion = OrgCompletion.at(context(text, caret))!
200 #expect(completion.kind == .propertyValue && completion.query == .propertyValues("Status"))
201 #expect(completion.candidates == ["in progress"])
202 let all = OrgCompletion.at(context(text, caret - 1))!
203 #expect(all.candidates == ["todo", "in progress", "done", "waiting"])
204 let filled = OrgCompletion.filled(all, with: CompletionResult(strings: ["blocked", "done"]), fuzzy: false)
205 #expect(filled.candidates == ["todo", "in progress", "done", "waiting", "blocked"])
206 // Names still complete as before.
207 #expect(OrgCompletion.at(context("* H\n:PROPERTIES:\n:A: 1\n:CU\n:END:\n", 26))?.kind == .property)
208 }
209}