oc-biblatex.el 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. ;;; oc-biblatex.el --- biblatex citation processor for Org -*- 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. ;; This library registers the `biblatex' citation processor, which provides
  17. ;; the "export" capability for citations.
  18. ;; The processor relies on "biblatex" LaTeX package. As such it ensures that
  19. ;; the package is properly required in the document's preamble. More
  20. ;; accurately, it will re-use any "\usepackage{biblatex}" already present in
  21. ;; the document (e.g., through `org-latex-packages-alist'), or insert one using
  22. ;; options defined in `org-cite-biblatex-options'.
  23. ;; In any case, the library will override style-related options with those
  24. ;; specified with the citation processor, in `org-cite-export-processors' or
  25. ;; "cite_export" keyword. If you need to use different styles for bibliography
  26. ;; and citations, you can separate them with "bibstyle/citestyle" syntax. E.g.,
  27. ;;
  28. ;; #+cite_export: biblatex authortitle/authortitle-ibid
  29. ;; The library supports the following citation styles:
  30. ;;
  31. ;; - author (a), including caps (c), full (f) and caps-full (cf) variants,
  32. ;; - locators (l), including bare (b), caps (c) and bare-caps (bc) variants,
  33. ;; - noauthor (na), including bare (b) variant,
  34. ;; - nocite (n),
  35. ;; - text (t), including caps (c) variant,
  36. ;; - default style, including bare (b), caps (c) and bare-caps (bc) variants.
  37. ;; When citation and style permit, the library automatically generates
  38. ;; "multicite" versions of the commands above.
  39. ;; Bibliography is printed using "\printbibliography" command. Additional
  40. ;; options may be passed to it through a property list attached to the
  41. ;; "print_bibliography" keyword. E.g.,
  42. ;;
  43. ;; #+print_bibliography: :section 2 :heading subbibliography
  44. ;;
  45. ;; Values including spaces must be surrounded with double quotes. If you need
  46. ;; to use a key multiple times, you can separate its values with commas, but
  47. ;; without any space in-between:
  48. ;;
  49. ;; #+print_bibliography: :keyword abc,xyz :title "Primary Sources"
  50. ;;; Code:
  51. (require 'org-macs)
  52. (org-assert-version)
  53. (require 'map)
  54. (require 'org-macs)
  55. (require 'oc)
  56. (declare-function org-element-property "org-element" (property element))
  57. (declare-function org-export-data "org-export" (data info))
  58. ;;; Customization
  59. (defcustom org-cite-biblatex-options nil
  60. "Options added to \"biblatex\" package.
  61. If \"biblatex\" package is already required in the document, e.g., through
  62. `org-latex-packages-alist' variable, these options are ignored."
  63. :group 'org-cite
  64. :package-version '(Org . "9.5")
  65. :type '(choice
  66. (string :tag "Options (key=value,key2=value2...)")
  67. (const :tag "No option" nil))
  68. :safe #'string-or-null-p)
  69. (defcustom org-cite-biblatex-styles
  70. '(("author" "caps" "Citeauthor*" nil nil)
  71. ("author" "full" "citeauthor" nil nil)
  72. ("author" "caps-full" "Citeauthor" nil nil)
  73. ("author" nil "citeauthor*" nil nil)
  74. ("locators" "bare" "notecite" nil nil)
  75. ("locators" "caps" "Pnotecite" nil nil)
  76. ("locators" "bare-caps" "Notecite" nil nil)
  77. ("locators" nil "pnotecite" nil nil)
  78. ("noauthor" "bare" "cite*" nil nil)
  79. ("noauthor" nil "autocite*" nil nil)
  80. ("nocite" nil "nocite" nil t)
  81. ("text" "caps" "Textcite" "Textcites" nil)
  82. ("text" nil "textcite" "textcites" nil)
  83. (nil "bare" "cite" "cites" nil)
  84. (nil "caps" "Autocite" "Autocites" nil)
  85. (nil "bare-caps" "Cite" "Cites" nil)
  86. (nil nil "autocite" "autocites" nil))
  87. "List of styles and variants, with associated BibLaTeX commands.
  88. Each style follows the pattern
  89. (NAME VARIANT COMMAND MULTI-COMMAND NO-OPTION)
  90. where:
  91. NAME is the name of the style, as a string, or nil. The nil
  92. style is the default style. As such, it must have an entry in
  93. the list.
  94. VARIANT is the name of the style variant, as a string or nil.
  95. The nil variant is the default variant for the current style.
  96. As such, each style name must be associated to a nil variant.
  97. COMMAND is the LaTeX command to use, as a string. It should
  98. not contain the leading backslash character.
  99. MULTI-COMMAND is the LaTeX command to use when a multi-cite
  100. command is appropriate. When nil, the style is deemed
  101. inappropriate for multi-cites. The command should not contain
  102. the leading backslash character.
  103. NO-OPTION is a boolean. When non-nil, no optional argument
  104. should be added to the LaTeX command.
  105. Each NAME-VARIANT pair should be unique in the list.
  106. It is also possible to provide shortcuts for style and variant
  107. names. See `org-cite-biblatex-style-shortcuts'."
  108. :group 'org-cite
  109. :package-version '(Org . "9.6")
  110. :type '(repeat
  111. (list :tag "Style/variant combination"
  112. ;; Name part.
  113. (choice :tag "Style"
  114. (string :tag "Name")
  115. (const :tag "Default style" nil))
  116. ;; Variant part.
  117. (choice :tag "Variant"
  118. (string :tag "Name")
  119. (const :tag "Default variant" nil))
  120. ;; Command part.
  121. (string :tag "Command name")
  122. (choice :tag "Multicite command"
  123. (string :tag "Command name")
  124. (const :tag "No multicite support" nil))
  125. (choice :tag "Skip optional arguments"
  126. (const :tag "Yes" t)
  127. (const :tag "No" nil)))))
  128. (defcustom org-cite-biblatex-style-shortcuts
  129. '(("a" . "author")
  130. ("b" . "bare")
  131. ("bc" . "bare-caps")
  132. ("c" . "caps")
  133. ("cf" . "caps-full")
  134. ("f" . "full")
  135. ("l" . "locators")
  136. ("n" . "nocite")
  137. ("na" . "noauthor")
  138. ("t" . "text"))
  139. "List of shortcuts associated to style or variant names.
  140. Each entry is a pair (NAME . STYLE-NAME) where NAME is the name
  141. of the shortcut, as a string, and STYLE-NAME is the name of
  142. a style in `org-cite-biblatex-styles'."
  143. :group 'org-cite
  144. :package-version '(Org . "9.6")
  145. :type '(repeat
  146. (cons :tag "Shortcut"
  147. (string :tag "Name")
  148. (string :tag "Full name")))
  149. :safe t)
  150. ;;; Internal functions
  151. (defun org-cite-biblatex--package-options (initial style)
  152. "Return options string for \"biblatex\" package.
  153. INITIAL is an initial style of comma-separated options, as a string or nil.
  154. STYLE is the style definition as a string or nil.
  155. Return a string."
  156. (let ((options-no-style
  157. (and initial
  158. (let ((re (rx string-start (or "bibstyle" "citestyle" "style"))))
  159. (seq-filter
  160. (lambda (option) (not (string-match re option)))
  161. (split-string (org-unbracket-string "[" "]" initial)
  162. "," t " \t")))))
  163. (style-options
  164. (cond
  165. ((null style) nil)
  166. ((not (string-match "/" style)) (list (concat "style=" style)))
  167. (t
  168. (list (concat "bibstyle=" (substring style nil (match-beginning 0)))
  169. (concat "citestyle=" (substring style (match-end 0))))))))
  170. (if (or options-no-style style-options)
  171. (format "[%s]"
  172. (mapconcat #'identity
  173. (append options-no-style style-options)
  174. ","))
  175. "")))
  176. (defun org-cite-biblatex--multicite-p (citation)
  177. "Non-nil when citation could make use of a \"multicite\" command."
  178. (let ((references (org-cite-get-references citation)))
  179. (and (< 1 (length references))
  180. (seq-some (lambda (r)
  181. (or (org-element-property :prefix r)
  182. (org-element-property :suffix r)))
  183. references))))
  184. (defun org-cite-biblatex--atomic-arguments (references info &optional no-opt)
  185. "Build argument for the list of citation REFERENCES.
  186. When NO-OPT argument is non-nil, only provide mandatory arguments."
  187. (let ((mandatory
  188. (format "{%s}"
  189. (mapconcat (lambda (r) (org-element-property :key r))
  190. references
  191. ","))))
  192. (if no-opt mandatory
  193. (let* ((origin (pcase references
  194. (`(,reference) reference)
  195. (`(,reference . ,_)
  196. (org-element-property :parent reference))))
  197. (suffix (org-element-property :suffix origin))
  198. (prefix (org-element-property :prefix origin)))
  199. (concat (and prefix
  200. (format "[%s]" (org-trim (org-export-data prefix info))))
  201. (cond
  202. (suffix (format "[%s]"
  203. (org-trim (org-export-data suffix info))))
  204. (prefix "[]")
  205. (t nil))
  206. mandatory)))))
  207. (defun org-cite-biblatex--multi-arguments (citation info)
  208. "Build \"multicite\" command arguments for CITATION object.
  209. INFO is the export state, as a property list."
  210. (let ((global-prefix (org-element-property :prefix citation))
  211. (global-suffix (org-element-property :suffix citation)))
  212. (concat (and global-prefix
  213. (format "(%s)"
  214. (org-trim (org-export-data global-prefix info))))
  215. (cond
  216. ;; Global pre/post-notes.
  217. (global-suffix
  218. (format "(%s)"
  219. (org-trim (org-export-data global-suffix info))))
  220. (global-prefix "()")
  221. (t nil))
  222. ;; All arguments.
  223. (mapconcat (lambda (r)
  224. (org-cite-biblatex--atomic-arguments (list r) info))
  225. (org-cite-get-references citation)
  226. ""))))
  227. (defun org-cite-biblatex--command (citation info name &optional multi no-opt)
  228. "Return BibLaTeX command NAME for CITATION object.
  229. INFO is the export state, as a property list.
  230. When optional argument MULTI is non-nil, use it as a multicite
  231. command name when appropriate. When optional argument NO-OPT is
  232. non-nil, do not add optional arguments to the command."
  233. (if (and multi (org-cite-biblatex--multicite-p citation))
  234. (format "\\%s%s" multi (org-cite-biblatex--multi-arguments citation info))
  235. (format "\\%s%s"
  236. name
  237. (org-cite-biblatex--atomic-arguments
  238. (org-cite-get-references citation) info no-opt))))
  239. (defun org-cite-biblatex--expand-shortcuts (style)
  240. "Return STYLE pair with shortcuts expanded."
  241. (pcase style
  242. (`(,style . ,variant)
  243. (cons (or (alist-get style org-cite-biblatex-style-shortcuts
  244. nil nil #'equal)
  245. style)
  246. (or (alist-get variant org-cite-biblatex-style-shortcuts
  247. nil nil #'equal)
  248. variant)))
  249. (_ (error "This should not happen"))))
  250. (defun org-cite-biblatex-list-styles ()
  251. "List styles and variants supported in `biblatex' citation processor.
  252. The output format is appropriate as a value for `:cite-styles' keyword
  253. in `org-cite-register-processor', which see."
  254. (let ((shortcuts (make-hash-table :test #'equal))
  255. (variants (make-hash-table :test #'equal)))
  256. (pcase-dolist (`(,name . ,full-name) org-cite-biblatex-style-shortcuts)
  257. (push name (gethash full-name shortcuts)))
  258. (pcase-dolist (`(,name ,variant . ,_) org-cite-biblatex-styles)
  259. (unless (null variant) (push variant (gethash name variants))))
  260. (map-apply (lambda (style-name variants)
  261. (cons (cons (or style-name "nil")
  262. (gethash style-name shortcuts))
  263. (mapcar (lambda (v)
  264. (cons v (gethash v shortcuts)))
  265. variants)))
  266. variants)))
  267. ;;; Export capability
  268. (defun org-cite-biblatex-export-bibliography (_keys _files _style props &rest _)
  269. "Print references from bibliography.
  270. PROPS is the local properties of the bibliography, as a property list."
  271. (concat "\\printbibliography"
  272. (and props
  273. (let ((key nil)
  274. (results nil))
  275. (dolist (datum props)
  276. (cond
  277. ((keywordp datum)
  278. (when key (push key results))
  279. (setq key (substring (symbol-name datum) 1)))
  280. (t
  281. ;; Comma-separated values are associated to the
  282. ;; same keyword.
  283. (push (mapconcat (lambda (v) (concat key "=" v))
  284. (split-string datum "," t)
  285. ",")
  286. results)
  287. (setq key nil))))
  288. (format "[%s]"
  289. (mapconcat #'identity (nreverse results) ","))))))
  290. (defun org-cite-biblatex-export-citation (citation style _ info)
  291. "Export CITATION object.
  292. STYLE is the citation style, as a pair of either strings or nil.
  293. INFO is the export state, as a property list."
  294. (pcase-let* ((`(,name . ,variant) (org-cite-biblatex--expand-shortcuts style))
  295. (candidates nil)
  296. (style-match-flag nil))
  297. (catch :match
  298. ;; Walk `org-cite-biblatex-styles' and prioritize matching
  299. ;; candidates. At the end of the process, the optimal candidate
  300. ;; should appear in front of CANDIDATES.
  301. (dolist (style org-cite-biblatex-styles)
  302. (pcase style
  303. ;; A matching style-variant pair trumps anything else.
  304. ;; Return it.
  305. (`(,(pred (equal name)) ,(pred (equal variant)) . ,_)
  306. (throw :match (setq candidates (list style))))
  307. ;; nil-nil style-variant is the fallback value. Consider it
  308. ;; only if nothing else matches.
  309. (`(nil nil . ,_)
  310. (unless candidates (push style candidates)))
  311. ;; A matching style with default variant trumps a matching
  312. ;; variant without the adequate style. Ensure the former
  313. ;; appears first in the list.
  314. (`(,(pred (equal name)) nil . ,_)
  315. (push style candidates)
  316. (setq style-match-flag t))
  317. (`(nil ,(pred (equal variant)) . ,_)
  318. (unless style-match-flag (push style candidates)))
  319. ;; Discard anything else.
  320. (_ nil))))
  321. (apply
  322. #'org-cite-biblatex--command citation info
  323. (pcase (seq-elt candidates 0) ;; `seq-first' is not available in Emacs 26.
  324. (`(,_ ,_ . ,command-parameters) command-parameters)
  325. ('nil
  326. (user-error
  327. "Missing default style or variant in `org-cite-biblatex-styles'"))
  328. (other
  329. (user-error "Invalid entry %S in `org-cite-biblatex-styles'" other))))))
  330. (defun org-cite-biblatex-prepare-preamble (output _keys files style &rest _)
  331. "Prepare document preamble for \"biblatex\" usage.
  332. OUTPUT is the final output of the export process. FILES is the list of file
  333. names used as the bibliography.
  334. This function ensures \"biblatex\" package is required. It also adds resources
  335. to the document, and set styles."
  336. (with-temp-buffer
  337. (save-excursion (insert output))
  338. (when (search-forward "\\begin{document}" nil t)
  339. ;; Ensure there is a \usepackage{biblatex} somewhere or add one.
  340. ;; Then set options.
  341. (goto-char (match-beginning 0))
  342. (let ((re (rx "\\usepackage"
  343. (opt (group "[" (*? anything) "]"))
  344. "{biblatex}")))
  345. (cond
  346. ;; No "biblatex" package loaded. Insert "usepackage" command
  347. ;; with appropriate options, including style.
  348. ((not (re-search-backward re nil t))
  349. (save-excursion
  350. (insert
  351. (format "\\usepackage%s{biblatex}\n"
  352. (org-cite-biblatex--package-options
  353. org-cite-biblatex-options style)))))
  354. ;; "biblatex" package loaded, but without any option.
  355. ;; Include style only.
  356. ((not (match-beginning 1))
  357. (search-forward "{" nil t)
  358. (insert (org-cite-biblatex--package-options nil style)))
  359. ;; "biblatex" package loaded with some options set. Override
  360. ;; style-related options with ours.
  361. (t
  362. (replace-match
  363. (save-match-data
  364. (org-cite-biblatex--package-options (match-string 1) style))
  365. nil nil nil 1))))
  366. ;; Insert resources below.
  367. (forward-line)
  368. (insert (mapconcat (lambda (f)
  369. (format "\\addbibresource%s{%s}"
  370. (if (org-url-p f) "[location=remote]" "")
  371. f))
  372. files
  373. "\n")
  374. "\n"))
  375. (buffer-string)))
  376. ;;; Register `biblatex' processor
  377. (org-cite-register-processor 'biblatex
  378. :export-bibliography #'org-cite-biblatex-export-bibliography
  379. :export-citation #'org-cite-biblatex-export-citation
  380. :export-finalizer #'org-cite-biblatex-prepare-preamble
  381. :cite-styles #'org-cite-biblatex-list-styles)
  382. (provide 'oc-biblatex)
  383. ;;; oc-biblatex.el ends here