oc-basic.el 32 KB

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