oc-biblatex.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 program is free software; you can redistribute it and/or modify
  5. ;; it under the terms of the GNU General Public License as published by
  6. ;; the Free Software Foundation, either version 3 of the License, or
  7. ;; (at your option) any later version.
  8. ;; This program is distributed in the hope that it will be useful,
  9. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. ;; GNU General Public License for more details.
  12. ;; You should have received a copy of the GNU General Public License
  13. ;; along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. ;;; Commentary:
  15. ;; This library registers the `biblatex' citation processor, which provides
  16. ;; the "export" capability for citations.
  17. ;; The processor relies on "biblatex" LaTeX package. As such it ensures that
  18. ;; the package is properly required in the document's preamble. More
  19. ;; accurately, it will re-use any "\usepackage{biblatex}" already present in
  20. ;; the document (e.g., through `org-latex-packages-alist'), or insert one using
  21. ;; options defined in `org-cite-biblatex-options'.
  22. ;; In any case, the library will override style-related options with those
  23. ;; specified with the citation processor, in `org-cite-export-processors' or
  24. ;; "cite_export" keyword. If you need to use different styles for bibliography
  25. ;; and citations, you can separate them with "bibstyle/citestyle" syntax. E.g.,
  26. ;;
  27. ;; #+cite_export: biblatex authortitle/authortitle-ibid
  28. ;; The library supports the following citation styles:
  29. ;;
  30. ;; - author (a), including caps (c), full (f) and caps-full (cf) variants,
  31. ;; - locators (l), including bare (b), caps (c) and bare-caps (bc) variants,
  32. ;; - noauthor (na),
  33. ;; - nocite (n),
  34. ;; - text (t), including caps (c) variant,
  35. ;; - default style, including bare (b), caps (c) and bare-caps (bc) variants.
  36. ;; When citation and style permit, the library automatically generates
  37. ;; "multicite" versions of the commands above.
  38. ;; Bibliography is printed using "\printbibliography" command. Additional
  39. ;; options may be passed to it through a property list attached to the
  40. ;; "print_bibliography" keyword. E.g.,
  41. ;;
  42. ;; #+print_bibliography: :section 2 :heading subbibliography
  43. ;;
  44. ;; Values including spaces must be surrounded with double quotes. If you need
  45. ;; to use a key multiple times, you can separate its values with commas, but
  46. ;; without any space in-between:
  47. ;;
  48. ;; #+print_bibliography: :keyword abc,xyz :title "Primary Sources"
  49. ;;; Code:
  50. (require 'org-macs)
  51. (require 'oc)
  52. (declare-function org-element-property "org-element" (property element))
  53. (declare-function org-export-data "org-export" (data info))
  54. (declare-function org-export-get-next-element "org-export" (blob info &optional n))
  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 t)
  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 look ahead and insert a \relax if
  146. ;; needed.
  147. (and (let ((next (org-export-get-next-element citation info)))
  148. (and next
  149. (string-match (rx string-start (or "{" "["))
  150. (org-export-data next info))))
  151. "\\relax"))))
  152. (defun org-cite-biblatex--command (citation info base &optional multi no-opt)
  153. "Return biblatex command using BASE name for CITATION object.
  154. INFO is the export state, as a property list.
  155. When optional argument MULTI is non-nil, generate a \"multicite\" command when
  156. appropriate. When optional argument NO-OPT is non-nil, do not add optional
  157. arguments to the command."
  158. (format "\\%s%s"
  159. base
  160. (if (and multi (org-cite-biblatex--multicite-p citation))
  161. (concat "s" (org-cite-biblatex--multi-arguments citation info))
  162. (org-cite-biblatex--atomic-arguments
  163. (org-cite-get-references citation) info no-opt))))
  164. ;;; Export capability
  165. (defun org-cite-biblatex-export-bibliography (_keys _files _style props &rest _)
  166. "Print references from bibliography.
  167. PROPS is the local properties of the bibliography, as a property list."
  168. (concat "\\printbibliography"
  169. (and props
  170. (let ((key nil)
  171. (results nil))
  172. (dolist (datum props)
  173. (cond
  174. ((keywordp datum)
  175. (when key (push key results))
  176. (setq key (substring (symbol-name datum) 1)))
  177. (t
  178. ;; Comma-separated values are associated to the
  179. ;; same keyword.
  180. (push (mapconcat (lambda (v) (concat key "=" v))
  181. (split-string datum "," t)
  182. ",")
  183. results)
  184. (setq key nil))))
  185. (format "[%s]"
  186. (mapconcat #'identity (nreverse results) ","))))))
  187. (defun org-cite-biblatex-export-citation (citation style _ info)
  188. "Export CITATION object.
  189. STYLE is the citation style, as a string or nil. INFO is the export state, as
  190. a property list."
  191. (apply
  192. #'org-cite-biblatex--command citation info
  193. (pcase style
  194. ;; "author" style.
  195. (`(,(or "author" "a") . ,(or "caps" "c")) '("Citeauthor*"))
  196. (`(,(or "author" "a") . ,(or "full" "f")) '("citeauthor"))
  197. (`(,(or "author" "a") . ,(or "caps-full" "cf")) '("Citeauthor"))
  198. (`(,(or "author" "a") . ,_) '("citeauthor*"))
  199. ;; "locators" style.
  200. (`(,(or "locators" "l") . ,(or "bare" "b")) '("notecite"))
  201. (`(,(or "locators" "l") . ,(or "caps" "c")) '("Pnotecite"))
  202. (`(,(or "locators" "l") . ,(or "bare-caps" "bc")) '("Notecite"))
  203. (`(,(or "locators" "l") . ,_) '("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") . ,(or "caps" "c")) '("Textcite" t))
  210. (`(,(or "text" "t") . ,_) '("textcite" t))
  211. ;; Default "nil" style.
  212. (`(,_ . ,(or "bare" "b")) '("cite" t))
  213. (`(,_ . ,(or "caps" "c")) '("Autocite" t))
  214. (`(,_ . ,(or "bare-caps" "bc")) '("Cite" t))
  215. (`(,_ . ,_) '("autocite" t))
  216. ;; This should not happen.
  217. (_ (error "Invalid style: %S" style)))))
  218. (defun org-cite-biblatex-prepare-preamble (output _keys files style &rest _)
  219. "Prepare document preamble for \"biblatex\" usage.
  220. OUTPUT is the final output of the export process. FILES is the list of file
  221. names used as the bibliography.
  222. This function ensures \"biblatex\" package is required. It also adds resources
  223. to the document, and set styles."
  224. (with-temp-buffer
  225. (save-excursion (insert output))
  226. (when (search-forward "\\begin{document}" nil t)
  227. ;; Ensure there is a \usepackage{biblatex} somewhere or add one.
  228. ;; Then set options.
  229. (goto-char (match-beginning 0))
  230. (let ((re (rx "\\usepackage"
  231. (opt (group "[" (*? anychar) "]"))
  232. "{biblatex}")))
  233. (cond
  234. ;; No "biblatex" package loaded. Insert "usepackage" command
  235. ;; with appropriate options, including style.
  236. ((not (re-search-backward re nil t))
  237. (save-excursion
  238. (insert
  239. (format "\\usepackage%s{biblatex}\n"
  240. (org-cite-biblatex--package-options
  241. org-cite-biblatex-options style)))))
  242. ;; "biblatex" package loaded, but without any option.
  243. ;; Include style only.
  244. ((not (match-beginning 1))
  245. (search-forward "{" nil t)
  246. (insert (org-cite-biblatex--package-options nil style)))
  247. ;; "biblatex" package loaded with some options set. Override
  248. ;; style-related options with ours.
  249. (t
  250. (replace-match
  251. (save-match-data
  252. (org-cite-biblatex--package-options (match-string 1) style))
  253. nil nil nil 1))))
  254. ;; Insert resources below.
  255. (forward-line)
  256. (insert (mapconcat (lambda (f)
  257. (format "\\addbibresource%s{%s}"
  258. (if (org-url-p f) "[location=remote]" "")
  259. f))
  260. files
  261. "\n")
  262. "\n"))
  263. (buffer-string)))
  264. ;;; Register `biblatex' processor
  265. (org-cite-register-processor 'biblatex
  266. :export-bibliography #'org-cite-biblatex-export-bibliography
  267. :export-citation #'org-cite-biblatex-export-citation
  268. :export-finalizer #'org-cite-biblatex-prepare-preamble
  269. :cite-styles
  270. '((("author" "a") ("caps" "c") ("full" "f") ("caps-full" "cf"))
  271. (("locators" "l") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
  272. (("noauthor" "na"))
  273. (("text" "t") ("caps" "c"))
  274. (("nil") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))))
  275. (provide 'org-cite-biblatex)
  276. (provide 'oc-biblatex)
  277. ;;; oc-biblatex.el ends here