Tests/OrgCoreTests/CitationInsertTests.swift
288 lines · 15176 bytes
23 symbols in this file
CitationInsertTestsfolderreadsBibTeXWithBracesStringsAndCrossrefsreadsCSLJSONlistsTheFilesBibliographyKeywordsAndTheGlobalSettingNamefindsTheLineAnEntryStartsOncachesFilesByModificationDateDiskloadsOffTheMainThreadSeenloadOnMaininsertinsertsAsOrgCiteInsertinsertionMatchesEmacsputsThePrefixAndSuffixAroundTheKeykeysRunInsertCitationtellsWhereTheCaretIsplacefollowsTheReferenceOrEveryKeylinkcompletesKeysAfterTheAtSigncompleteexportReadsTheGlobalBibliography
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// Bibliography files as Insert Citation… reads them, `org-cite-insert`'s edits, key
6/// completion and following citations.
7struct CitationInsertTests {
8 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
9
10 static let bib = #"""
11 % A comment line.
12 @String{jos = "Journal of " # "Stuff"}
13 @Article{doe2020,
14 Author = {Doe, Jane and {Roe and Sons}},
15 title = {A {Study} of {{Nested}} Things},
16 journal = jos,
17 year = 2020,
18 doi = {https://doi.org/10.1000/xyz},
19 file = {Full Text:papers/doe.pdf:application/pdf;/abs/other.pdf}
20 }
21 @comment{@book{hidden, title = {No}}}
22 @book(smith1999,
23 author = "Smith, John",
24 title = "The {"}Book{"}",
25 url = {https://example.org/book},
26 date = {1999-04-01}
27 )
28 @proceedings{conf2021,
29 title = {Proceedings of the Conference},
30 editor = {Park, Min},
31 publisher = {ACM},
32 year = {2021}
33 }
34 @inproceedings{talk,
35 author = {Lee, Kim},
36 title = {A Talk},
37 crossref = {Conf2021}
38 }
39 """#
40
41 static let json = #"""
42 [{"id": "csl1", "author": [{"family": "Zed", "given": "Ann"}], "title": "From JSON", "issued": {"date-parts": [[2018]]}, "DOI": "10.1/j", "URL": "https://j.example"}]
43 """#
44
45 func folder() throws -> URL {
46 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-bib-\(UUID().uuidString)")
47 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
48 try Self.bib.write(to: folder.appendingPathComponent("refs.bib"), atomically: true, encoding: .utf8)
49 try Self.json.write(to: folder.appendingPathComponent("more.json"), atomically: true, encoding: .utf8)
50 return folder
51 }
52
53 // MARK: - Reading
54
55 @Test func readsBibTeXWithBracesStringsAndCrossrefs() throws {
56 let entries = Bibliography.entries(Data(Self.bib.utf8), path: "/refs/refs.bib")
57 #expect(entries.map(\.key) == ["conf2021", "doe2020", "smith1999", "talk"])
58 let doe = try #require(entries.first { $0.key == "doe2020" })
59 #expect(doe.fields["author"] == "Doe, Jane and {Roe and Sons}")
60 #expect(doe.author == "Doe, Jane and Roe and Sons")
61 #expect(doe.fields["title"] == "A {Study} of {{Nested}} Things")
62 #expect(doe.title == "A Study of Nested Things")
63 #expect(doe.fields["journal"] == "Journal of Stuff")
64 #expect(doe.year == "2020")
65 #expect(doe.doi == "10.1000/xyz")
66 #expect(doe.files == ["/refs/papers/doe.pdf", "/abs/other.pdf"])
67 #expect(doe.label == "doe2020 Doe, Jane; Roe and Sons 2020 A Study of Nested Things")
68 #expect(doe.summary == "Doe, Jane and Roe and Sons (2020). A Study of Nested Things. Journal of Stuff.")
69 let smith = try #require(entries.first { $0.key == "smith1999" })
70 #expect(smith.title == "The \"Book\"")
71 #expect(smith.year == "1999")
72 #expect(smith.url == "https://example.org/book")
73 // Fields the entry lacks come from the one it cross-references; its title is the book's.
74 let talk = try #require(entries.first { $0.key == "talk" })
75 #expect(talk.title == "A Talk")
76 #expect(talk.field("booktitle") == "Proceedings of the Conference")
77 #expect(talk.field("publisher") == "ACM")
78 #expect(talk.year == "2021")
79 #expect(talk.fields["crossref"] == "Conf2021")
80 }
81
82 @Test func readsCSLJSON() throws {
83 let entries = Bibliography.entries(Data(Self.json.utf8), path: "/refs/more.json")
84 let entry = try #require(entries.first)
85 #expect(entry.key == "csl1")
86 #expect(entry.author == "Zed Ann")
87 #expect(entry.year == "2018")
88 #expect(entry.doi == "10.1/j")
89 #expect(entry.url == "https://j.example")
90 }
91
92 @Test func listsTheFilesBibliographyKeywordsAndTheGlobalSettingName() {
93 let text = "#+BIBLIOGRAPHY: refs.bib\n#+bibliography: \"with space.bib\"\n#+bibliography: /abs/a.bib\n #+bibliography: refs.bib\n"
94 #expect(Bibliography.files(in: text, directory: "/notes", global: ["/abs/a.bib", "/g/global.json"])
95 == ["/notes/refs.bib", "/notes/with space.bib", "/abs/a.bib", "/g/global.json"])
96 #expect(Bibliography.files(in: "No keywords\n", directory: "/notes", global: ["~/g.bib"]) == [OrgPaths.home + "/g.bib"])
97 }
98
99 @Test func findsTheLineAnEntryStartsOn() {
100 #expect(Bibliography.line(of: "smith1999", in: Self.bib, json: false) == 12)
101 #expect(Bibliography.line(of: "doe2020", in: Self.bib, json: false) == 3)
102 #expect(Bibliography.line(of: "csl1", in: Self.json, json: true) == 1)
103 #expect(Bibliography.line(of: "hidden2", in: Self.bib, json: false) == nil)
104 }
105
106 /// A file is parsed again only when its modification date changes; the first file wins
107 /// for a key in two.
108 @Test func cachesFilesByModificationDate() throws {
109 final class Disk: @unchecked Sendable {
110 var dates: [String: Date] = [:]
111 var texts: [String: String] = [:]
112 var reads = 0
113 }
114 let disk = Disk()
115 disk.dates = ["/a.bib": Date(timeIntervalSince1970: 1), "/b.bib": Date(timeIntervalSince1970: 1)]
116 disk.texts = ["/a.bib": "@misc{one, title = {A}}", "/b.bib": "@misc{one, title = {B}}\n@misc{two, title = {Two}}"]
117 let cache = BibliographyCache(modified: { disk.dates[$0] }, read: { disk.reads += 1; return disk.texts[$0].map { Data($0.utf8) } })
118 #expect(cache.entries(["/a.bib", "/b.bib", "/missing.bib"]).map { "\($0.key) \($0.title ?? "")" } == ["one A", "two Two"])
119 #expect(disk.reads == 2)
120 _ = cache.entries(["/a.bib", "/b.bib"])
121 #expect(disk.reads == 2)
122 disk.texts["/a.bib"] = "@misc{three, title = {C}}"
123 disk.dates["/a.bib"] = Date(timeIntervalSince1970: 2)
124 #expect(cache.entries(["/a.bib"]).map(\.key) == ["three"])
125 #expect(disk.reads == 3)
126 }
127
128 @Test func loadsOffTheMainThread() async throws {
129 let folder = try folder()
130 defer { try? FileManager.default.removeItem(at: folder) }
131 final class Seen: @unchecked Sendable { var main: Bool? }
132 let seen = Seen()
133 let cache = BibliographyCache(read: { seen.main = Thread.isMainThread; return FileManager.default.contents(atPath: $0) })
134 let entries = await Self.loadOnMain(cache, [folder.appendingPathComponent("refs.bib").path])
135 #expect(entries.count == 4)
136 #expect(seen.main == false)
137 }
138
139 @MainActor
140 static func loadOnMain(_ cache: BibliographyCache, _ paths: [String]) async -> [BibEntry] {
141 await cache.load(paths)
142 }
143
144 // MARK: - Inserting
145
146 /// Text with `|` at the caret, Insert Citation… of `key` with `style`, and the result
147 /// with `|` at the caret.
148 func insert(_ marked: String, key: String? = "k2", style: String? = nil, prefix: String = "", suffix: String = "") -> String {
149 let caret = (marked as NSString).range(of: "|").location
150 let text = marked.replacingOccurrences(of: "|", with: "")
151 let result = runCommand(InsertCitation(key: key, style: style, prefix: prefix, suffix: suffix), text, caret: caret)
152 if let failure = result.failure { return "failed: " + failure }
153 return (result.text as NSString).replacingCharacters(in: NSRange(location: result.caret, length: 0), with: "|")
154 }
155
156 /// Cases where orgstar and `org-cite-insert` do the same, with the style asked (Emacs's
157 /// prefix argument) or not.
158 static let cases: [(text: String, styled: Bool, expected: String)] = [
159 ("Text | more", false, "Text [cite:@k2]| more"),
160 ("Text |", true, "Text [cite/text:@k2]|"),
161 ("|[cite:@a]", false, "[cite:@k2]|[cite:@a]"),
162 ("[cite:@a] |", false, "[cite:@a] [cite:@k2]|"),
163 ("[cite:@a|]", false, "[cite:@a;@k2|]"),
164 ("[cite:|@a]", false, "[cite:|@k2;@a]"),
165 ("[cite:@a|b]", false, "[cite:|@k2]"),
166 ("[cite:see @a p. |4; @b]", false, "[cite:see @a p. |4;@k2; @b]"),
167 ("[cite:@a; @b|]", false, "[cite:@a; @b;@k2|]"),
168 ("[cite:@a;| @b]", false, "[cite:@a;|@k2; @b]"),
169 ("[cite:pre|; @a; post]", false, "[cite:pre|;@k2; @a; post]"),
170 ("[cite:pre; @a; po|st]", false, "[cite:pre; @a;@k2; po|st]"),
171 ("[cite/t|:@a]", true, "[cite|/text:@a]"),
172 ("[ci|te:@a]", true, "[ci|te/text:@a]"),
173 ]
174
175 @Test func insertsAsOrgCiteInsert() {
176 for c in Self.cases {
177 #expect(insert(c.text, style: c.styled ? "text" : nil) == c.expected, "\(c.text)")
178 }
179 }
180
181 @Test(.enabled(if: oracle))
182 func insertionMatchesEmacs() throws {
183 let oracleCases = Self.cases.map { c in
184 let caret = (c.text as NSString).range(of: "|").location
185 let text = c.text.replacingOccurrences(of: "|", with: "")
186 let form = """
187 (progn (require 'oc-basic)
188 (let ((org-cite-insert-processor 'basic))
189 (cl-letf (((symbol-function 'org-cite-basic--complete-key) (lambda (&optional multiple) (if multiple (list "k2") "k2")))
190 ((symbol-function 'org-cite-basic--complete-style) (lambda (_) "text")))
191 (org-cite-insert \(c.styled && Citations.place(at: caret, tree: OrgParser.parse(text)) == .new ? "'(4)" : "nil")))))
192 """
193 return EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: form)
194 }
195 let results = try EmacsOracle.run(oracleCases)
196 for (c, result) in zip(Self.cases, results) {
197 let emacs = (result.text as NSString).replacingCharacters(in: NSRange(location: EmacsOracle.offset(result.point, in: result.text), length: 0), with: "|")
198 #expect(result.error.isEmpty, "\(c.text): \(result.error)")
199 #expect(insert(c.text, style: c.styled ? "text" : nil) == emacs, "\(c.text)")
200 }
201 }
202
203 @Test func putsThePrefixAndSuffixAroundTheKey() {
204 #expect(insert("A |", prefix: "see", suffix: "p. 4") == "A [cite:see @k2 p. 4]|")
205 #expect(insert("A |", style: "t", prefix: "see ", suffix: ", ch. 2") == "A [cite/t:see @k2, ch. 2]|")
206 #expect(insert("[cite:@a|]", prefix: "cf.") == "[cite:@a;cf. @k2|]")
207 // A key replaced keeps the reference's own prefix and suffix.
208 #expect(insert("[cite:see @a|b p. 4]", prefix: "x", suffix: "y") == "[cite:see |@k2 p. 4]")
209 // An empty style is the default.
210 #expect(insert("[cite/t|:@a]", style: "") == "[cite|:@a]")
211 #expect(insert("[cite/t|:@a]", key: nil, style: nil) == "failed: Aborted")
212 #expect(insert("A |", key: nil) == "failed: Aborted")
213 }
214
215 @Test func keysRunInsertCitation() {
216 #expect(KeymapPreset.emacs.keymap.candidates(for: KeySequence.parse("C-c C-x @")!).first?.command == "app.cite.insert")
217 #expect(KeymapPreset.doom.keymap.candidates(for: KeySequence.parse("SPC m @")!, mode: "normal").first?.command == "app.cite.insert")
218 }
219
220 @Test func tellsWhereTheCaretIs() {
221 func place(_ marked: String) -> Citations.Place {
222 let caret = (marked as NSString).range(of: "|").location
223 return Citations.place(at: caret, tree: OrgParser.parse(marked.replacingOccurrences(of: "|", with: "")))
224 }
225 #expect(place("x |") == .new)
226 #expect(place("|[cite:@a]") == .new)
227 #expect(place("[cite:@a]|") == .new)
228 #expect(place("[|cite:@a]") == .style)
229 #expect(place("[cite/t|:@a]") == .style)
230 #expect(place("[cite:|@a]") == .reference)
231 #expect(place("[cite:@|a]") == .key)
232 #expect(place("[cite:@a|]") == .reference)
233 #expect(place("* Heading [cite:@a|b]") == .key)
234 }
235
236 // MARK: - Following and completing
237
238 @Test func followsTheReferenceOrEveryKey() {
239 func link(_ marked: String) -> OrgLink? {
240 let caret = (marked as NSString).range(of: "|").location
241 let text = marked.replacingOccurrences(of: "|", with: "")
242 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
243 guard case .external(.openLink(let link)) = OpenLinkAtPoint().run(in: context) else { return nil }
244 return link
245 }
246 #expect(link("See [cite:@a; @|b]")?.raw == "cite:b")
247 #expect(link("See [cite:pre; @a; @b; @a; po|st]")?.raw == "cite:a;b")
248 #expect(link("See |[cite/t:@a]")?.path == "a")
249 #expect(link("See [cite:@a]| x") == nil)
250 let text = "x [cite:@a]"
251 #expect(OrgDwim().run(in: EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [4..<4])) == .external(.openLink(OrgLink(type: "cite", path: "a", raw: "cite:a"))))
252 }
253
254 @Test func completesKeysAfterTheAtSign() throws {
255 func complete(_ text: String, path: String? = "/notes/doc.org", global: [String] = []) -> Completion? {
256 var options = EditingOptions.org
257 options.filePath = path
258 var settings = OrgSettings.default
259 settings.citeGlobalBibliography = global
260 let tree = OrgParser.parse(text, defaults: settings)
261 return OrgCompletion.at(EditContext(revision: 0, text: text, tree: tree, selection: [text.utf16.count..<text.utf16.count], options: options))
262 }
263 let completion = try #require(complete("#+bibliography: refs.bib\nSee [cite:@do"))
264 #expect(completion.kind == .citationKey)
265 #expect(completion.typed == "do")
266 #expect(completion.range == 36..<38)
267 #expect(completion.query == .citationKeys(["/notes/refs.bib"]))
268 #expect(complete("[cite/t:see @a; @", global: ["/g.bib"])?.query == .citationKeys(["/g.bib"]))
269 #expect(complete("[cite:@")?.typed == "")
270 #expect(complete("[cite:@a] and @b")?.kind != .citationKey)
271 #expect(complete("mail me@ho")?.kind != .citationKey)
272
273 let entries = Bibliography.entries(Data(Self.bib.utf8), path: "/notes/refs.bib")
274 let filled = OrgCompletion.filled(completion, with: CompletionResult(entries: entries), fuzzy: false)
275 #expect(filled.candidates == ["doe2020"])
276 #expect(filled.label("doe2020") == "doe2020 Doe, Jane; Roe and Sons 2020 A Study of Nested Things")
277 #expect(OrgCompletion.filled(completion, with: CompletionResult(entries: entries), fuzzy: true).candidates.first == "doe2020")
278 }
279
280 @Test func exportReadsTheGlobalBibliography() throws {
281 let folder = try folder()
282 defer { try? FileManager.default.removeItem(at: folder) }
283 var settings = OrgSettings.default
284 settings.citeGlobalBibliography = [folder.appendingPathComponent("refs.bib").path]
285 let markdown = MarkdownExport.document("See [cite/t:@smith1999].\n", settings: settings, path: folder.appendingPathComponent("doc.org").path)
286 #expect(markdown.contains("See Smith, John (1999)."))
287 }
288}