oc-basic.el 35 KB

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