oc-basic.el 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. ;;; oc-basic.el --- basic back-end for citations -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2021 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
  4. ;; This program is free software; you can redistribute it and/or modify
  5. ;; it under the terms of the GNU General Public License as published by
  6. ;; the Free Software Foundation, either version 3 of the License, or
  7. ;; (at your option) any later version.
  8. ;; This program is distributed in the hope that it will be useful,
  9. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. ;; GNU General Public License for more details.
  12. ;; You should have received a copy of the GNU General Public License
  13. ;; along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. ;;; Commentary:
  15. ;; The `basic' citation processor provides "activate", "follow", "export" and
  16. ;; "insert" capabilities.
  17. ;; "activate" capability re-uses default fontification, but provides additional
  18. ;; features on both correct and wrong keys according to the bibliography
  19. ;; defined in the document.
  20. ;; When the mouse is over a known key, it displays the corresponding
  21. ;; bibliography entry. Any wrong key, however, is highlighted with `error'
  22. ;; face. Moreover, moving the mouse onto it displays a list of suggested correct
  23. ;; keys, and pressing <mouse-1> on the faulty key will try to fix it according to
  24. ;; those suggestions.
  25. ;; On a citation key, "follow" capability moves point to the corresponding entry
  26. ;; in the current bibliography. Elsewhere on the citation, it asks the user to
  27. ;; follow any of the keys cited there, with completion.
  28. ;; "export" capability supports the following citation styles:
  29. ;;
  30. ;; - author (a), including caps (c) variant,
  31. ;; - noauthor (na) including bare (b) variant,
  32. ;; - text (t), including bare (b), caps (c), and bare-caps (bc) variants,
  33. ;; - note (ft, including bare (b), caps (c), and bare-caps (bc) variants,
  34. ;; - nocite (n)
  35. ;; - numeric (nb),
  36. ;; - default, including bare (b), caps (c), and bare-caps (bc) variants.
  37. ;;
  38. ;; It also supports the following styles for bibliography:
  39. ;; - plain
  40. ;; - numeric
  41. ;; - author-year (default)
  42. ;; "insert" capability inserts or edits (with completion) citation style or
  43. ;; citation reference keys. In an appropriate place, it offers to insert a new
  44. ;; citation. With a prefix argument, it removes the one at point.
  45. ;; It supports bibliography files in BibTeX (".bibtex"), biblatex (".bib") and
  46. ;; JSON (".json") format.
  47. ;; Disclaimer: this citation processor is meant to be a proof of concept, and
  48. ;; possibly a fall-back mechanism when nothing else is available. It is too
  49. ;; limited for any serious use case.
  50. ;;; Code:
  51. (require 'bibtex)
  52. (require 'oc)
  53. (declare-function org-open-at-point "org" (&optional arg))
  54. (declare-function org-element-interpret-data "org-element" (data))
  55. (declare-function org-element-property "org-element" (property element))
  56. (declare-function org-element-type "org-element" (element))
  57. (declare-function org-export-data "org-export" (data info))
  58. (declare-function org-export-derived-backend-p "org-export" (backend &rest backends))
  59. (declare-function org-export-raw-string "org-export" (contents))
  60. ;;; Customization
  61. (defcustom org-cite-basic-sorting-field 'author
  62. "Field used to sort bibliography items as a symbol, or nil."
  63. :group 'org-cite
  64. :package-version '(Org . "9.5")
  65. :type 'symbol
  66. :safe t)
  67. (defcustom org-cite-basic-author-year-separator ", "
  68. "String used to separate cites in an author-year configuration."
  69. :group 'org-cite
  70. :package-version '(Org . "9.5")
  71. :type 'string
  72. :safe t)
  73. (defcustom org-cite-basic-max-key-distance 2
  74. "Maximum (Levenshtein) distance between a wrong key and its suggestions."
  75. :group 'org-cite
  76. :package-version '(Org . "9.5")
  77. :type 'integer
  78. :safe t)
  79. (defcustom org-cite-basic-author-column-end 25
  80. "Column where author field ends in completion table, as an integer."
  81. :group 'org-cite
  82. :package-version '(Org . "9.5")
  83. :type 'integer
  84. :safe t)
  85. (defcustom org-cite-basic-column-separator " "
  86. "Column separator in completion table, as a string."
  87. :group 'org-cite
  88. :package-version '(Org . "9.5")
  89. :type 'string
  90. :safe t)
  91. (defcustom org-cite-basic-mouse-over-key-face 'highlight
  92. "Face used when mouse is over a citation key."
  93. :group 'org-cite
  94. :package-version '(Org . "9.5")
  95. :type 'face
  96. :safe t)
  97. ;;; Internal variables
  98. (defvar org-cite-basic--bibliography-cache nil
  99. "Cache for parsed bibliography files.
  100. This is an association list following the pattern:
  101. (FILE-ID . ENTRIES)
  102. FILE-ID is a cons cell (FILE . HASH), with FILE being the absolute file name of
  103. the bibliography file, and HASH a hash of its contents.
  104. ENTRIES is a hash table with citation references as keys and fields alist as
  105. values.")
  106. (defvar org-cite-basic--completion-cache (make-hash-table :test #'equal)
  107. "Cache for key completion table.
  108. This is an a hash-table.")
  109. ;;; Internal functions
  110. (defun org-cite-basic--parse-json ()
  111. "Parse JSON entries in the current buffer.
  112. Return a hash table with citation references as keys and fields alist as values."
  113. (let ((entries (make-hash-table :test #'equal)))
  114. (let ((json-array-type 'list)
  115. (json-key-type 'symbol))
  116. (dolist (item (json-read))
  117. (puthash (cdr (assq 'id item))
  118. (mapcar (pcase-lambda (`(,field . ,value))
  119. (pcase field
  120. ('author
  121. ;; Author is an array of objects, each
  122. ;; of them designing a person. These
  123. ;; objects may contain multiple
  124. ;; properties, but for this basic
  125. ;; processor, we'll focus on `given' and
  126. ;; `family'.
  127. ;;
  128. ;; For compatibility with BibTeX, add
  129. ;; "and" between authors.
  130. (cons 'author
  131. (mapconcat
  132. (lambda (alist)
  133. (concat (alist-get 'family alist)
  134. " "
  135. (alist-get 'given alist)))
  136. value
  137. " and ")))
  138. ('issued
  139. ;; Date are expressed as an array
  140. ;; (`date-parts') or a "string (`raw').
  141. ;; In both cases, extract the year and
  142. ;; associate it to `year' field, for
  143. ;; compatibility with BibTeX format.
  144. (let ((date (or (alist-get 'date-parts value)
  145. (alist-get 'raw value))))
  146. (cons 'year
  147. (cond
  148. ((consp date)
  149. (caar date))
  150. ((stringp date)
  151. (car (split-string date "-")))
  152. (t
  153. (error "Unknown CSL-JSON date format: %S"
  154. date))))))
  155. (_
  156. (cons field value))))
  157. item)
  158. entries))
  159. entries)))
  160. (defun org-cite-basic--parse-bibtex (dialect)
  161. "Parse BibTeX entries in the current buffer.
  162. DIALECT is the BibTeX dialect used. See `bibtex-dialect'.
  163. Return a hash table with citation references as keys and fields alist as values."
  164. (let ((entries (make-hash-table :test #'equal))
  165. (bibtex-sort-ignore-string-entries t))
  166. (bibtex-set-dialect dialect t)
  167. (bibtex-map-entries
  168. (lambda (key &rest _)
  169. ;; Normalize entries: field names are turned into symbols
  170. ;; including special "=key=" and "=type=", and consecutive
  171. ;; white spaces are removed from values.
  172. (puthash key
  173. (mapcar
  174. (pcase-lambda (`(,field . ,value))
  175. (pcase field
  176. ("=key=" (cons 'id key))
  177. ("=type=" (cons 'type value))
  178. (_
  179. (cons
  180. (intern (downcase field))
  181. (replace-regexp-in-string "[ \t\n]+" " " value)))))
  182. (bibtex-parse-entry t))
  183. entries)))
  184. entries))
  185. (defun org-cite-basic--parse-bibliography (&optional info)
  186. "List all entries available in the buffer.
  187. Each association follows the pattern
  188. (FILE . ENTRIES)
  189. where FILE is the absolute file name of the BibTeX file, and ENTRIES is a hash
  190. table where keys are references and values are association lists between fields,
  191. as symbols, and values as strings or nil.
  192. Optional argument INFO is the export state, as a property list."
  193. (if (plist-member info :cite-basic/bibliography)
  194. (plist-get info :cite-basic/bibliography)
  195. (let ((results nil))
  196. (dolist (file (org-cite-list-bibliography-files))
  197. (when (file-readable-p file)
  198. (with-temp-buffer
  199. (insert-file-contents file)
  200. (let* ((file-id (cons file (buffer-hash)))
  201. (entries
  202. (or (cdr (assoc file-id org-cite-basic--bibliography-cache))
  203. (let ((table
  204. (pcase (file-name-extension file)
  205. ("json" (org-cite-basic--parse-json))
  206. ("bib" (org-cite-basic--parse-bibtex 'biblatex))
  207. ("bibtex" (org-cite-basic--parse-bibtex 'BibTeX))
  208. (ext
  209. (user-error "Unknown bibliography extension: %S"
  210. ext)))))
  211. (push (cons file-id table) org-cite-basic--bibliography-cache)
  212. table))))
  213. (push (cons file entries) results)))))
  214. (when info (plist-put info :cite-basic/bibliography results))
  215. results)))
  216. (defun org-cite-basic--key-number (key info)
  217. "Return number associated to cited KEY.
  218. INFO is the export state, as a property list."
  219. (let ((predicate
  220. (org-cite-basic--field-less-p org-cite-basic-sorting-field info)))
  221. (org-cite-key-number key info predicate)))
  222. (defun org-cite-basic--all-keys ()
  223. "List all keys available in current bibliography."
  224. (seq-mapcat (pcase-lambda (`(,_ . ,entries))
  225. (map-keys entries))
  226. (org-cite-basic--parse-bibliography)))
  227. (defun org-cite-basic--get-entry (key &optional info)
  228. "Return BibTeX entry for KEY, as an association list.
  229. When non-nil, INFO is the export state, as a property list."
  230. (catch :found
  231. (pcase-dolist (`(,_ . ,entries) (org-cite-basic--parse-bibliography info))
  232. (let ((entry (gethash key entries)))
  233. (when entry (throw :found entry))))
  234. nil))
  235. (defun org-cite-basic--get-field (field entry-or-key &optional info raw)
  236. "Return FIELD value for ENTRY-OR-KEY, or nil.
  237. FIELD is a symbol. ENTRY-OR-KEY is either an association list, as returned by
  238. `org-cite-basic--get-entry', or a string representing a citation key.
  239. Optional argument INFO is the export state, as a property list.
  240. Return value may be nil or a string. If current export back-end is derived
  241. from `latex', return a raw string instead, unless optional argument RAW is
  242. non-nil."
  243. (let ((value
  244. (cdr
  245. (assq field
  246. (pcase entry-or-key
  247. ((pred stringp)
  248. (org-cite-basic--get-entry entry-or-key info))
  249. ((pred consp)
  250. entry-or-key)
  251. (_
  252. (error "Wrong value for ENTRY-OR-KEY: %S" entry-or-key)))))))
  253. (if (and value
  254. (not raw)
  255. (org-export-derived-backend-p (plist-get info :back-end) 'latex))
  256. (org-export-raw-string value)
  257. value)))
  258. (defun org-cite-basic--number-to-suffix (n)
  259. "Compute suffix associated to number N.
  260. This is used for disambiguation."
  261. (let ((result nil))
  262. (apply #'string
  263. (mapcar (lambda (n) (+ 97 n))
  264. (catch :complete
  265. (while t
  266. (push (% n 26) result)
  267. (setq n (/ n 26))
  268. (cond
  269. ((= n 0) (throw :complete result))
  270. ((< n 27) (throw :complete (cons (1- n) result)))
  271. ((= n 27) (throw :complete (cons 0 (cons 0 result))))
  272. (t nil))))))))
  273. (defun org-cite-basic--get-year (entry-or-key info)
  274. "Return year associated to ENTRY-OR-KEY.
  275. ENTRY-OR-KEY is either an association list, as returned by
  276. `org-cite-basic--get-entry', or a string representing a citation key. INFO is
  277. the export state, as a property list.
  278. Unlike `org-cite-basic--get-field', this function disambiguates author-year
  279. patterns."
  280. ;; The cache is an association list with the following structure:
  281. ;;
  282. ;; (AUTHOR-YEAR . KEY-SUFFIX-ALIST).
  283. ;;
  284. ;; AUTHOR-YEAR is the author year pair associated to current entry
  285. ;; or key.
  286. ;;
  287. ;; KEY-SUFFIX-ALIST is an association (KEY . SUFFIX), where KEY is
  288. ;; the cite key, as a string, and SUFFIX is the generated suffix
  289. ;; string, or the empty string.
  290. (let* ((author (org-cite-basic--get-field 'author entry-or-key info 'raw))
  291. (year (org-cite-basic--get-field 'year entry-or-key info 'raw))
  292. (cache-key (cons author year))
  293. (key
  294. (pcase entry-or-key
  295. ((pred stringp) entry-or-key)
  296. ((pred consp) (cdr (assq 'id entry-or-key)))
  297. (_ (error "Wrong value for ENTRY-OR-KEY: %S" entry-or-key))))
  298. (cache (plist-get info :cite-basic/author-date-cache)))
  299. (pcase (assoc cache-key cache)
  300. ('nil
  301. (let ((value (cons cache-key (list (cons key "")))))
  302. (plist-put info :cite-basic/author-date-cache (cons value cache))
  303. year))
  304. (`(,_ . ,alist)
  305. (concat year
  306. (or (cdr (assoc key alist))
  307. (let ((new (org-cite-basic--number-to-suffix (1- (length alist)))))
  308. (push (cons key new) alist)
  309. new)))))))
  310. (defun org-cite-basic--print-entry (entry style &optional info)
  311. "Format ENTRY according to STYLE string.
  312. ENTRY is an alist, as returned by `org-cite-basic--get-entry'.
  313. Optional argument INFO is the export state, as a property list."
  314. (let ((author (org-cite-basic--get-field 'author entry info))
  315. (title (org-cite-basic--get-field 'title entry info))
  316. (year (org-cite-basic--get-field 'year entry info))
  317. (from
  318. (or (org-cite-basic--get-field 'publisher entry info)
  319. (org-cite-basic--get-field 'journal entry info)
  320. (org-cite-basic--get-field 'institution entry info)
  321. (org-cite-basic--get-field 'school entry info))))
  322. (pcase style
  323. ("plain"
  324. (org-cite-concat
  325. author ". " title (and from (list ", " from)) ", " year "."))
  326. ("numeric"
  327. (let ((n (org-cite-basic--key-number (cdr (assq 'id entry)) info)))
  328. (org-cite-concat
  329. (format "[%d] " n) author ", "
  330. (org-cite-emphasize 'italic title)
  331. (and from (list ", " from)) ", "
  332. year ".")))
  333. ;; Default to author-year. Use year disambiguation there.
  334. (_
  335. (let ((year (org-cite-basic--get-year entry info)))
  336. (org-cite-concat
  337. author " (" year "). "
  338. (org-cite-emphasize 'italic title)
  339. (and from (list ", " from)) "."))))))
  340. ;;; "Activate" capability
  341. (defun org-cite-basic--close-keys (key keys)
  342. "List cite keys close to KEY in terms of string distance."
  343. (seq-filter (lambda (k)
  344. (>= org-cite-basic-max-key-distance
  345. (org-string-distance k key)))
  346. keys))
  347. (defun org-cite-basic--set-keymap (beg end suggestions)
  348. "Set keymap on citation key between BEG and END positions.
  349. When the key is know, SUGGESTIONS is nil. Otherwise, it may be
  350. a list of replacement keys, as strings, which will be offered as
  351. substitutes for the unknown key. Finally, it may be the symbol
  352. `all'."
  353. (let ((km (make-sparse-keymap)))
  354. (define-key km (kbd "<mouse-1>")
  355. (pcase suggestions
  356. ('nil #'org-open-at-point)
  357. ('all #'org-cite-insert)
  358. (_
  359. (lambda ()
  360. (interactive)
  361. (setf (buffer-substring beg end)
  362. (concat "@"
  363. (if (= 1 (length suggestions))
  364. (car suggestions)
  365. (completing-read "Did you mean: "
  366. suggestions nil t))))))))
  367. (put-text-property beg end 'keymap km)))
  368. (defun org-cite-basic-activate (citation)
  369. "Set various text properties on CITATION object.
  370. Fontify whole citation with `org-cite' face. Fontify key with `error' face
  371. when it does not belong to known keys. Otherwise, use `org-cite-key' face.
  372. Moreover, when mouse is on a known key, display the corresponding bibliography.
  373. On a wrong key, suggest a list of possible keys, and offer to substitute one of
  374. them with a mouse click."
  375. (pcase-let ((`(,beg . ,end) (org-cite-boundaries citation))
  376. (keys (org-cite-basic--all-keys)))
  377. (put-text-property beg end 'font-lock-multiline t)
  378. (add-face-text-property beg end 'org-cite)
  379. (dolist (reference (org-cite-get-references citation))
  380. (pcase-let* ((`(,beg . ,end) (org-cite-key-boundaries reference))
  381. (key (org-element-property :key reference)))
  382. ;; Highlight key on mouse over.
  383. (put-text-property beg end
  384. 'mouse-face
  385. org-cite-basic-mouse-over-key-face)
  386. (if (member key keys)
  387. ;; Activate a correct key. Face is `org-cite-key' and
  388. ;; `help-echo' displays bibliography entry, for reference.
  389. ;; <mouse-1> calls `org-open-at-point'.
  390. (let* ((entry (org-cite-basic--get-entry key))
  391. (bibliography-entry
  392. (org-element-interpret-data
  393. (org-cite-basic--print-entry entry "plain"))))
  394. (add-face-text-property beg end 'org-cite-key)
  395. (put-text-property beg end 'help-echo bibliography-entry)
  396. (org-cite-basic--set-keymap beg end nil))
  397. ;; Activate a wrong key. Face is `error', `help-echo'
  398. ;; displays possible suggestions.
  399. (add-face-text-property beg end 'error)
  400. (let ((close-keys (org-cite-basic--close-keys key keys)))
  401. (when close-keys
  402. (put-text-property beg end 'help-echo
  403. (concat "Suggestions (mouse-1 to substitute): "
  404. (mapconcat #'identity close-keys " "))))
  405. ;; When the are close know keys, <mouse-1> provides
  406. ;; completion to fix the current one. Otherwise, call
  407. ;; `org-cite-insert'.
  408. (org-cite-basic--set-keymap beg end (or close-keys 'all))))))))
  409. ;;; "Export" capability
  410. (defun org-cite-basic--format-author-year (citation format-cite format-ref info)
  411. "Format CITATION object according to author-year format.
  412. FORMAT-CITE is a function of three arguments: the global prefix, the contents,
  413. and the global suffix. All arguments can be strings or secondary strings.
  414. FORMAT-REF is a function of four arguments: the reference prefix, as a string or
  415. secondary string, the author, the year, and the reference suffix, as a string or
  416. secondary string.
  417. INFO is the export state, as a property list."
  418. (org-export-data
  419. (funcall format-cite
  420. (org-element-property :prefix citation)
  421. (org-cite-mapconcat
  422. (lambda (ref)
  423. (let ((k (org-element-property :key ref))
  424. (prefix (org-element-property :prefix ref))
  425. (suffix (org-element-property :suffix ref)))
  426. (funcall format-ref
  427. prefix
  428. (org-cite-basic--get-field 'author k info)
  429. (org-cite-basic--get-year k info)
  430. suffix)))
  431. (org-cite-get-references citation)
  432. org-cite-basic-author-year-separator)
  433. (org-element-property :suffix citation))
  434. info))
  435. (defun org-cite-basic--citation-numbers (citation info)
  436. "Return numbers associated to references in CITATION object.
  437. INFO is the export state as a property list."
  438. (let* ((numbers
  439. (sort (mapcar (lambda (k) (org-cite-basic--key-number k info))
  440. (org-cite-get-references citation t))
  441. #'<))
  442. (last (car numbers))
  443. (result (list (number-to-string (pop numbers)))))
  444. ;; Use compact number references, i.e., "1, 2, 3" becomes "1-3".
  445. (while numbers
  446. (let ((current (pop numbers))
  447. (next (car numbers)))
  448. (cond
  449. ((and next
  450. (= current (1+ last))
  451. (= current (1- next)))
  452. (unless (equal "-" (car result))
  453. (push "-" result)))
  454. ((equal "-" (car result))
  455. (push (number-to-string current) result))
  456. (t
  457. (push (format ", %d" current) result)))
  458. (setq last current)))
  459. (apply #'concat (nreverse result))))
  460. (defun org-cite-basic--field-less-p (field info)
  461. "Return a sort predicate comparing FIELD values for two citation keys.
  462. INFO is the export state, as a property list."
  463. (and field
  464. (lambda (a b)
  465. (org-string-collate-lessp
  466. (org-cite-basic--get-field field a info 'raw)
  467. (org-cite-basic--get-field field b info 'raw)
  468. nil t))))
  469. (defun org-cite-basic--sort-keys (keys info)
  470. "Sort KEYS by author name.
  471. INFO is the export communication channel, as a property list."
  472. (let ((predicate (org-cite-basic--field-less-p org-cite-basic-sorting-field info)))
  473. (if predicate
  474. (sort keys predicate)
  475. keys)))
  476. (defun org-cite-basic-export-citation (citation style _ info)
  477. "Export CITATION object.
  478. STYLE is the expected citation style, as a pair of strings or nil. INFO is the
  479. export communication channel, as a property list."
  480. (let ((has-variant-p
  481. (lambda (variant type)
  482. ;; Non-nil when style VARIANT has TYPE. TYPE is either
  483. ;; `bare' or `caps'.
  484. (member variant
  485. (pcase type
  486. ('bare '("bare" "bare-caps" "b" "bc"))
  487. ('caps '("caps" "bare-caps" "c" "bc"))
  488. (_ (error "Invalid variant type: %S" type)))))))
  489. (pcase style
  490. ;; "author" style.
  491. (`(,(or "author" "a") . ,variant)
  492. (let ((caps (member variant '("caps" "c"))))
  493. (org-export-data
  494. (mapconcat
  495. (lambda (key)
  496. (let ((author (org-cite-basic--get-field 'author key info)))
  497. (if caps (capitalize author) author)))
  498. (org-cite-get-references citation t)
  499. org-cite-basic-author-year-separator)
  500. info)))
  501. ;; "noauthor" style.
  502. (`(,(or "noauthor" "na") . ,variant)
  503. (format (if (funcall has-variant-p variant 'bare) "%s" "(%s)")
  504. (mapconcat (lambda (key) (org-cite-basic--get-year key info))
  505. (org-cite-get-references citation t)
  506. org-cite-basic-author-year-separator)))
  507. ;; "nocite" style.
  508. (`(,(or "nocite" "n") . ,_) nil)
  509. ;; "text" and "note" styles.
  510. (`(,(and (or "text" "note" "t" "ft") style) . ,variant)
  511. (when (and (member style '("note" "ft"))
  512. (not (org-cite-inside-footnote-p citation)))
  513. (org-cite-adjust-note citation info)
  514. (org-cite-wrap-citation citation info))
  515. (let ((bare (funcall has-variant-p variant 'bare))
  516. (caps (funcall has-variant-p variant 'caps)))
  517. (org-cite-basic--format-author-year
  518. citation
  519. (lambda (p c s) (org-cite-concat p c s))
  520. (lambda (p a y s)
  521. (org-cite-concat p
  522. (if caps (capitalize a) a)
  523. (if bare " " " (")
  524. y s
  525. (and (not bare) ")")))
  526. info)))
  527. ;; "numeric" style.
  528. ;;
  529. ;; When using this style on citations with multiple references,
  530. ;; use global affixes and ignore local ones.
  531. (`(,(or "numeric" "nb") . ,_)
  532. (let* ((references (org-cite-get-references citation))
  533. (prefix
  534. (or (org-element-property :prefix citation)
  535. (and (= 1 (length references))
  536. (org-element-property :prefix (car references)))))
  537. (suffix
  538. (or (org-element-property :suffix citation)
  539. (and (= 1 (length references))
  540. (org-element-property :suffix (car references))))))
  541. (org-export-data
  542. (org-cite-concat
  543. "(" prefix (org-cite-basic--citation-numbers citation info) suffix ")")
  544. info)))
  545. ;; Default ("nil") style.
  546. (`(,_ . ,variant)
  547. (let ((bare (funcall has-variant-p variant 'bare))
  548. (caps (funcall has-variant-p variant 'caps)))
  549. (org-cite-basic--format-author-year
  550. citation
  551. (lambda (p c s)
  552. (org-cite-concat (and (not bare) "(") p c s (and (not bare) ")")))
  553. (lambda (p a y s)
  554. (org-cite-concat p (if caps (capitalize a) a) ", " y s))
  555. info)))
  556. ;; This should not happen.
  557. (_ (error "Invalid style: %S" style)))))
  558. (defun org-cite-basic-export-bibliography (keys _files style _props backend info)
  559. "Generate bibliography.
  560. KEYS is the list of cited keys, as strings. STYLE is the expected bibliography
  561. style, as a string. BACKEND is the export back-end, as a symbol. INFO is the
  562. export state, as a property list."
  563. (mapconcat
  564. (lambda (k)
  565. (let ((entry (org-cite-basic--get-entry k info)))
  566. (org-export-data
  567. (org-cite-make-paragraph
  568. (and (org-export-derived-backend-p backend 'latex)
  569. (org-export-raw-string "\\noindent\n"))
  570. (org-cite-basic--print-entry entry style info))
  571. info)))
  572. (org-cite-basic--sort-keys keys info)
  573. "\n"))
  574. ;;; "Follow" capability
  575. (defun org-cite-basic-goto (datum _)
  576. "Follow citation or citation reference DATUM.
  577. When DATUM is a citation reference, open bibliography entry referencing
  578. the citation key. Otherwise, select which key to follow among all keys
  579. present in the citation."
  580. (let* ((key
  581. (if (eq 'citation-reference (org-element-type datum))
  582. (org-element-property :key datum)
  583. (pcase (org-cite-get-references datum t)
  584. (`(,key) key)
  585. (keys
  586. (or (completing-read "Select citation key: " keys nil t)
  587. (user-error "Aborted"))))))
  588. (file
  589. (pcase (seq-find (pcase-lambda (`(,_ . ,entries))
  590. (gethash key entries))
  591. (org-cite-basic--parse-bibliography))
  592. (`(,f . ,_) f)
  593. (_ (user-error "Cannot find citation key: %S" key)))))
  594. (org-open-file file '(4))
  595. (pcase (file-name-extension file)
  596. ("json"
  597. (let ((regexp (rx "\"id\":" (0+ (any "[ \t]")) "\"" (literal key) "\"")))
  598. (goto-char (point-min))
  599. (re-search-forward regexp)
  600. (search-backward "{")))
  601. (_
  602. (bibtex-set-dialect)
  603. (bibtex-search-entry key)))))
  604. ;;; "Insert" capability
  605. (defun org-cite-basic--complete-style ()
  606. "Offer completion for style.
  607. Return chosen style as a string."
  608. (let* ((styles
  609. (mapcar (pcase-lambda (`((,style . ,_) . ,_))
  610. style)
  611. (org-cite-supported-styles))))
  612. (pcase styles
  613. (`(,style) style)
  614. (_ (completing-read "Style (\"\" for default): " styles nil t)))))
  615. (defun org-cite-basic--key-completion-table ()
  616. "Return completion table for cite keys, as a hash table.
  617. In this hash table, keys are a strings with author, date, and title of the
  618. reference. Values are the cite key."
  619. (let ((cache-key (mapcar #'car org-cite-basic--bibliography-cache)))
  620. (if (gethash cache-key org-cite-basic--completion-cache)
  621. org-cite-basic--completion-cache
  622. (clrhash org-cite-basic--completion-cache)
  623. (dolist (key (org-cite-basic--all-keys))
  624. (let ((completion
  625. (concat
  626. (let ((author (org-cite-basic--get-field 'author key nil t)))
  627. (if author
  628. (truncate-string-to-width
  629. (replace-regexp-in-string " and " "; " author)
  630. org-cite-basic-author-column-end nil ?\s)
  631. (make-string org-cite-basic-author-column-end ?\s)))
  632. org-cite-basic-column-separator
  633. (let ((date (org-cite-basic--get-field 'year key nil t)))
  634. (format "%4s" (or date "")))
  635. org-cite-basic-column-separator
  636. (org-cite-basic--get-field 'title key nil t))))
  637. (puthash completion key org-cite-basic--completion-cache)))
  638. (puthash cache-key t org-cite-basic--completion-cache)
  639. org-cite-basic--completion-cache)))
  640. (defun org-cite-basic--complete-key (&optional multiple)
  641. "Prompt for a reference key and return a citation reference string.
  642. When optional argument MULTIPLE is non-nil, prompt for multiple keys, until one
  643. of them is nil. Then return the list of reference strings selected.
  644. Raise an error when no bibliography is set in the buffer."
  645. (let* ((table
  646. (or (org-cite-basic--key-completion-table)
  647. (user-error "No bibliography set")))
  648. (prompt
  649. (lambda (text)
  650. (completing-read text table nil t))))
  651. (if (null multiple)
  652. (let ((key (gethash (funcall prompt "Key: ") table)))
  653. (org-string-nw-p key))
  654. (let* ((keys nil)
  655. (build-prompt
  656. (lambda ()
  657. (if keys
  658. (format "Key (\"\" to exit) %s: "
  659. (mapconcat #'identity (reverse keys) ";"))
  660. "Key (\"\" to exit): "))))
  661. (let ((key (funcall prompt (funcall build-prompt))))
  662. (while (org-string-nw-p key)
  663. (push (gethash key table) keys)
  664. (setq key (funcall prompt (funcall build-prompt)))))
  665. keys))))
  666. ;;; Register processor
  667. (org-cite-register-processor 'basic
  668. :activate #'org-cite-basic-activate
  669. :export-citation #'org-cite-basic-export-citation
  670. :export-bibliography #'org-cite-basic-export-bibliography
  671. :follow #'org-cite-basic-goto
  672. :insert (org-cite-make-insert-processor #'org-cite-basic--complete-key
  673. #'org-cite-basic--complete-style)
  674. :cite-styles
  675. '((("author" "a") ("caps" "c"))
  676. (("noauthor" "na") ("bare" "b"))
  677. (("nocite" "n"))
  678. (("note" "ft") ("bare-caps" "bc") ("caps" "c"))
  679. (("numeric" "nb"))
  680. (("text" "t") ("bare-caps" "bc") ("caps" "c"))
  681. (("nil") ("bare" "b") ("bare-caps" "bc") ("caps" "c"))))
  682. (provide 'org-cite-basic)
  683. ;;; oc-default.el ends here