oc-basic.el 31 KB

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