oc-basic.el 35 KB

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