oc-biblatex.el 17 KB

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