oc-biblatex.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. (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 look ahead and insert a \relax if
  147. ;; needed.
  148. (and (let ((next (org-export-get-next-element citation info)))
  149. (and next
  150. (string-match (rx string-start (or "{" "["))
  151. (org-export-data next info))))
  152. "\\relax"))))
  153. (defun org-cite-biblatex--command (citation info base &optional multi no-opt)
  154. "Return biblatex command using BASE name for CITATION object.
  155. INFO is the export state, as a property list.
  156. When optional argument MULTI is non-nil, generate a \"multicite\" command when
  157. appropriate. When optional argument NO-OPT is non-nil, do not add optional
  158. arguments to the command."
  159. (format "\\%s%s"
  160. base
  161. (if (and multi (org-cite-biblatex--multicite-p citation))
  162. (concat "s" (org-cite-biblatex--multi-arguments citation info))
  163. (org-cite-biblatex--atomic-arguments
  164. (org-cite-get-references citation) info no-opt))))
  165. ;;; Export capability
  166. (defun org-cite-biblatex-export-bibliography (_keys _files _style props &rest _)
  167. "Print references from bibliography.
  168. PROPS is the local properties of the bibliography, as a property list."
  169. (concat "\\printbibliography"
  170. (and props
  171. (let ((key nil)
  172. (results nil))
  173. (dolist (datum props)
  174. (cond
  175. ((keywordp datum)
  176. (when key (push key results))
  177. (setq key (substring (symbol-name datum) 1)))
  178. (t
  179. ;; Comma-separated values are associated to the
  180. ;; same keyword.
  181. (push (mapconcat (lambda (v) (concat key "=" v))
  182. (split-string datum "," t)
  183. ",")
  184. results)
  185. (setq key nil))))
  186. (format "[%s]"
  187. (mapconcat #'identity (nreverse results) ","))))))
  188. (defun org-cite-biblatex-export-citation (citation style _ info)
  189. "Export CITATION object.
  190. STYLE is the citation style, as a string or nil. INFO is the export state, as
  191. a property list."
  192. (apply
  193. #'org-cite-biblatex--command citation info
  194. (pcase style
  195. ;; "author" style.
  196. (`(,(or "author" "a") . ,variant)
  197. (pcase variant
  198. ((or "caps" "c") '("Citeauthor*"))
  199. ((or "full" "f") '("citeauthor"))
  200. ((or "caps-full" "cf") '("Citeauthor"))
  201. (_ '("citeauthor*"))))
  202. ;; "locators" style.
  203. (`(,(or "locators" "l") . ,variant)
  204. (pcase variant
  205. ((or "bare" "b") '("notecite"))
  206. ((or "caps" "c") '("Pnotecite"))
  207. ((or "bare-caps" "bc") '("Notecite"))
  208. (_ '("pnotecite"))))
  209. ;; "noauthor" style.
  210. (`(,(or "noauthor" "na") . ,_) '("autocite*"))
  211. ;; "nocite" style.
  212. (`(,(or "nocite" "n") . ,_) '("nocite" nil t))
  213. ;; "text" style.
  214. (`(,(or "text" "t") . ,variant)
  215. (pcase variant
  216. ((or "caps" "c") '("Textcite" t))
  217. (_ '("textcite" t))))
  218. ;; Default "nil" style.
  219. (`(,_ . ,variant)
  220. (pcase variant
  221. ((or "bare" "b") '("cite" t))
  222. ((or "caps" "c") '("Autocite" t))
  223. ((or "bare-caps" "bc") '("Cite" t))
  224. (_ '("autocite" t))))
  225. ;; This should not happen.
  226. (_ (error "Invalid style: %S" style)))))
  227. (defun org-cite-biblatex-prepare-preamble (output _keys files style &rest _)
  228. "Prepare document preamble for \"biblatex\" usage.
  229. OUTPUT is the final output of the export process. FILES is the list of file
  230. names used as the bibliography.
  231. This function ensures \"biblatex\" package is required. It also adds resources
  232. to the document, and set styles."
  233. (with-temp-buffer
  234. (save-excursion (insert output))
  235. (when (search-forward "\\begin{document}" nil t)
  236. ;; Ensure there is a \usepackage{biblatex} somewhere or add one.
  237. ;; Then set options.
  238. (goto-char (match-beginning 0))
  239. (let ((re (rx "\\usepackage"
  240. (opt (group "[" (*? anything) "]"))
  241. "{biblatex}")))
  242. (cond
  243. ;; No "biblatex" package loaded. Insert "usepackage" command
  244. ;; with appropriate options, including style.
  245. ((not (re-search-backward re nil t))
  246. (save-excursion
  247. (insert
  248. (format "\\usepackage%s{biblatex}\n"
  249. (org-cite-biblatex--package-options
  250. org-cite-biblatex-options style)))))
  251. ;; "biblatex" package loaded, but without any option.
  252. ;; Include style only.
  253. ((not (match-beginning 1))
  254. (search-forward "{" nil t)
  255. (insert (org-cite-biblatex--package-options nil style)))
  256. ;; "biblatex" package loaded with some options set. Override
  257. ;; style-related options with ours.
  258. (t
  259. (replace-match
  260. (save-match-data
  261. (org-cite-biblatex--package-options (match-string 1) style))
  262. nil nil nil 1))))
  263. ;; Insert resources below.
  264. (forward-line)
  265. (insert (mapconcat (lambda (f)
  266. (format "\\addbibresource%s{%s}"
  267. (if (org-url-p f) "[location=remote]" "")
  268. f))
  269. files
  270. "\n")
  271. "\n"))
  272. (buffer-string)))
  273. ;;; Register `biblatex' processor
  274. (org-cite-register-processor 'biblatex
  275. :export-bibliography #'org-cite-biblatex-export-bibliography
  276. :export-citation #'org-cite-biblatex-export-citation
  277. :export-finalizer #'org-cite-biblatex-prepare-preamble
  278. :cite-styles
  279. '((("author" "a") ("caps" "c") ("full" "f") ("caps-full" "cf"))
  280. (("locators" "l") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
  281. (("noauthor" "na"))
  282. (("text" "t") ("caps" "c"))
  283. (("nil") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))))
  284. (provide 'oc-biblatex)
  285. ;;; oc-biblatex.el ends here