oc-basic.el 33 KB

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