oc-biblatex.el 13 KB

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