oc-biblatex.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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),
  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. ;;; Internal functions
  67. (defun org-cite-biblatex--package-options (initial style)
  68. "Return options string for \"biblatex\" package.
  69. INITIAL is an initial style of comma-separated options, as a string or nil.
  70. STYLE is the style definition as a string or nil.
  71. Return a string."
  72. (let ((options-no-style
  73. (and initial
  74. (let ((re (rx string-start (or "bibstyle" "citestyle" "style"))))
  75. (seq-filter
  76. (lambda (option) (not (string-match re option)))
  77. (split-string (org-unbracket-string "[" "]" initial)
  78. "," t " \t")))))
  79. (style-options
  80. (cond
  81. ((null style) nil)
  82. ((not (string-match "/" style)) (list (concat "style=" style)))
  83. (t
  84. (list (concat "bibstyle=" (substring style nil (match-beginning 0)))
  85. (concat "citestyle=" (substring style (match-end 0))))))))
  86. (if (or options-no-style style-options)
  87. (format "[%s]"
  88. (mapconcat #'identity
  89. (append options-no-style style-options)
  90. ","))
  91. "")))
  92. (defun org-cite-biblatex--multicite-p (citation)
  93. "Non-nil when citation could make use of a \"multicite\" command."
  94. (let ((references (org-cite-get-references citation)))
  95. (and (< 1 (length references))
  96. (seq-some (lambda (r)
  97. (or (org-element-property :prefix r)
  98. (org-element-property :suffix r)))
  99. references))))
  100. (defun org-cite-biblatex--atomic-arguments (references info &optional no-opt)
  101. "Build argument for the list of citation REFERENCES.
  102. When NO-OPT argument is non-nil, only provide mandatory arguments."
  103. (let ((mandatory
  104. (format "{%s}"
  105. (mapconcat (lambda (r) (org-element-property :key r))
  106. references
  107. ","))))
  108. (if no-opt mandatory
  109. (let* ((origin (pcase references
  110. (`(,reference) reference)
  111. (`(,reference . ,_)
  112. (org-element-property :parent reference))))
  113. (suffix (org-element-property :suffix origin))
  114. (prefix (org-element-property :prefix origin)))
  115. (concat (and prefix
  116. (format "[%s]" (org-trim (org-export-data prefix info))))
  117. (cond
  118. (suffix (format "[%s]"
  119. (org-trim (org-export-data suffix info))))
  120. (prefix "[]")
  121. (t nil))
  122. mandatory)))))
  123. (defun org-cite-biblatex--multi-arguments (citation info)
  124. "Build \"multicite\" command arguments for CITATION object.
  125. INFO is the export state, as a property list."
  126. (let ((global-prefix (org-element-property :prefix citation))
  127. (global-suffix (org-element-property :suffix citation)))
  128. (concat (and global-prefix
  129. (format "(%s)"
  130. (org-trim (org-export-data global-prefix info))))
  131. (cond
  132. ;; Global pre/post-notes.
  133. (global-suffix
  134. (format "(%s)"
  135. (org-trim (org-export-data global-suffix info))))
  136. (global-prefix "()")
  137. (t nil))
  138. ;; All arguments.
  139. (mapconcat (lambda (r)
  140. (org-cite-biblatex--atomic-arguments (list r) info))
  141. (org-cite-get-references citation)
  142. "")
  143. ;; According to BibLaTeX manual, left braces or brackets
  144. ;; following a multicite command could be parsed as other
  145. ;; arguments. So we stop any further parsing by inserting
  146. ;; a \relax unconditionally.
  147. "\\relax")))
  148. (defun org-cite-biblatex--command (citation info base &optional multi no-opt)
  149. "Return biblatex command using BASE name for CITATION object.
  150. INFO is the export state, as a property list.
  151. When optional argument MULTI is non-nil, generate a \"multicite\" command when
  152. appropriate. When optional argument NO-OPT is non-nil, do not add optional
  153. arguments to the command."
  154. (format "\\%s%s"
  155. base
  156. (if (and multi (org-cite-biblatex--multicite-p citation))
  157. (concat "s" (org-cite-biblatex--multi-arguments citation info))
  158. (org-cite-biblatex--atomic-arguments
  159. (org-cite-get-references citation) info no-opt))))
  160. ;;; Export capability
  161. (defun org-cite-biblatex-export-bibliography (_keys _files _style props &rest _)
  162. "Print references from bibliography.
  163. PROPS is the local properties of the bibliography, as a property list."
  164. (concat "\\printbibliography"
  165. (and props
  166. (let ((key nil)
  167. (results nil))
  168. (dolist (datum props)
  169. (cond
  170. ((keywordp datum)
  171. (when key (push key results))
  172. (setq key (substring (symbol-name datum) 1)))
  173. (t
  174. ;; Comma-separated values are associated to the
  175. ;; same keyword.
  176. (push (mapconcat (lambda (v) (concat key "=" v))
  177. (split-string datum "," t)
  178. ",")
  179. results)
  180. (setq key nil))))
  181. (format "[%s]"
  182. (mapconcat #'identity (nreverse results) ","))))))
  183. (defun org-cite-biblatex-export-citation (citation style _ info)
  184. "Export CITATION object.
  185. STYLE is the citation style, as a string or nil. INFO is the export state, as
  186. a property list."
  187. (apply
  188. #'org-cite-biblatex--command citation info
  189. (pcase style
  190. ;; "author" style.
  191. (`(,(or "author" "a") . ,variant)
  192. (pcase variant
  193. ((or "caps" "c") '("Citeauthor*"))
  194. ((or "full" "f") '("citeauthor"))
  195. ((or "caps-full" "cf") '("Citeauthor"))
  196. (_ '("citeauthor*"))))
  197. ;; "locators" style.
  198. (`(,(or "locators" "l") . ,variant)
  199. (pcase variant
  200. ((or "bare" "b") '("notecite"))
  201. ((or "caps" "c") '("Pnotecite"))
  202. ((or "bare-caps" "bc") '("Notecite"))
  203. (_ '("pnotecite"))))
  204. ;; "noauthor" style.
  205. (`(,(or "noauthor" "na") . ,_) '("autocite*"))
  206. ;; "nocite" style.
  207. (`(,(or "nocite" "n") . ,_) '("nocite" nil t))
  208. ;; "text" style.
  209. (`(,(or "text" "t") . ,variant)
  210. (pcase variant
  211. ((or "caps" "c") '("Textcite" t))
  212. (_ '("textcite" t))))
  213. ;; Default "nil" style.
  214. (`(,_ . ,variant)
  215. (pcase variant
  216. ((or "bare" "b") '("cite" t))
  217. ((or "caps" "c") '("Autocite" t))
  218. ((or "bare-caps" "bc") '("Cite" t))
  219. (_ '("autocite" t))))
  220. ;; This should not happen.
  221. (_ (error "Invalid style: %S" style)))))
  222. (defun org-cite-biblatex-prepare-preamble (output _keys files style &rest _)
  223. "Prepare document preamble for \"biblatex\" usage.
  224. OUTPUT is the final output of the export process. FILES is the list of file
  225. names used as the bibliography.
  226. This function ensures \"biblatex\" package is required. It also adds resources
  227. to the document, and set styles."
  228. (with-temp-buffer
  229. (save-excursion (insert output))
  230. (when (search-forward "\\begin{document}" nil t)
  231. ;; Ensure there is a \usepackage{biblatex} somewhere or add one.
  232. ;; Then set options.
  233. (goto-char (match-beginning 0))
  234. (let ((re (rx "\\usepackage"
  235. (opt (group "[" (*? anything) "]"))
  236. "{biblatex}")))
  237. (cond
  238. ;; No "biblatex" package loaded. Insert "usepackage" command
  239. ;; with appropriate options, including style.
  240. ((not (re-search-backward re nil t))
  241. (save-excursion
  242. (insert
  243. (format "\\usepackage%s{biblatex}\n"
  244. (org-cite-biblatex--package-options
  245. org-cite-biblatex-options style)))))
  246. ;; "biblatex" package loaded, but without any option.
  247. ;; Include style only.
  248. ((not (match-beginning 1))
  249. (search-forward "{" nil t)
  250. (insert (org-cite-biblatex--package-options nil style)))
  251. ;; "biblatex" package loaded with some options set. Override
  252. ;; style-related options with ours.
  253. (t
  254. (replace-match
  255. (save-match-data
  256. (org-cite-biblatex--package-options (match-string 1) style))
  257. nil nil nil 1))))
  258. ;; Insert resources below.
  259. (forward-line)
  260. (insert (mapconcat (lambda (f)
  261. (format "\\addbibresource%s{%s}"
  262. (if (org-url-p f) "[location=remote]" "")
  263. f))
  264. files
  265. "\n")
  266. "\n"))
  267. (buffer-string)))
  268. ;;; Register `biblatex' processor
  269. (org-cite-register-processor 'biblatex
  270. :export-bibliography #'org-cite-biblatex-export-bibliography
  271. :export-citation #'org-cite-biblatex-export-citation
  272. :export-finalizer #'org-cite-biblatex-prepare-preamble
  273. :cite-styles
  274. '((("author" "a") ("caps" "c") ("full" "f") ("caps-full" "cf"))
  275. (("locators" "l") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
  276. (("noauthor" "na"))
  277. (("nocite" "n"))
  278. (("text" "t") ("caps" "c"))
  279. (("nil") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))))
  280. (provide 'oc-biblatex)
  281. ;;; oc-biblatex.el ends here