oc-basic.el 32 KB

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