oc-basic.el 35 KB

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