oc-csl.el 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. ;;; oc-csl.el --- csl citation processor for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2021-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
  4. ;; Maintainer: András Simonyi <andras.simonyi@gmail.com>
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This library registers the `csl' citation processor, which provides
  18. ;; the "export" capability for citations.
  19. ;; The processor relies on the external Citeproc Emacs library, which must be
  20. ;; available prior to loading this library.
  21. ;; By default, citations are rendered in Chicago author-date CSL style. You can
  22. ;; use another style file by specifying it in `org-cite-export-processors' or
  23. ;; from within the document by adding the file name to "cite_export" keyword
  24. ;;
  25. ;; #+cite_export: csl /path/to/style-file.csl
  26. ;; #+cite_export: csl "/path/to/style-file.csl"
  27. ;;
  28. ;; With the variable `org-cite-csl-styles-dir' set appropriately, the
  29. ;; above can even be shortened to
  30. ;;
  31. ;; #+cite_export: csl style-file.csl
  32. ;;
  33. ;; Styles can be downloaded, for instance, from the Zotero Style Repository
  34. ;; (<https://www.zotero.org/styles>). Dependent styles (which are not "unique"
  35. ;; in the Zotero Style Repository terminology) are not supported.
  36. ;; The processor uses the "en-US" CSL locale file shipped with Org for rendering
  37. ;; localized dates and terms in the references, independently of the language
  38. ;; settings of the Org document. Additional CSL locales can be made available
  39. ;; by setting `org-cite-csl-locales-dir' to a directory containing the locale
  40. ;; files in question (see <https://github.com/citation-style-language/locales>
  41. ;; for such files).
  42. ;; Bibliography is defined with the "bibliography" keyword. It supports files
  43. ;; with ".bib", ".bibtex", and ".json" extensions. References are exported using
  44. ;; the "print_bibliography" keyword.
  45. ;; The library supports the following citation styles:
  46. ;;
  47. ;; - author (a), including bare (b), caps (c), bare-caps (bc), full (f),
  48. ;; caps-full (cf), and bare-caps-full (bcf) variants,
  49. ;; - noauthor (na), including bare (b), caps (c) and bare-caps (bc) variants,
  50. ;; - nocite (n),
  51. ;; - year (y), including a bare (b) variant,
  52. ;; - text (t), including caps (c), full (f), and caps-full (cf) variants,
  53. ;; - title (ti), including a bare (b) variant,
  54. ;; - locators (l), including a bare (b) variant,
  55. ;; - bibentry (b), including a bare (b) variant,
  56. ;; - default style, including bare (b), caps (c) and bare-caps (bc) variants.
  57. ;;
  58. ;; Using "*" as a key in a nocite citation includes all available
  59. ;; items in the printed bibliography. The "bibentry" citation style,
  60. ;; similarly to biblatex's \fullcite, creates a citation which is
  61. ;; similar to the bibliography entry.
  62. ;; CSL styles recognize "locator" in citation references' suffix. For example,
  63. ;; in the citation
  64. ;;
  65. ;; [cite:see @Tarski-1965 chapter 1, for an example]
  66. ;;
  67. ;; "chapter 1" is the locator. The whole citation is rendered as
  68. ;;
  69. ;; (see Tarski 1965, chap. 1 for an example)
  70. ;;
  71. ;; in the default CSL style.
  72. ;;
  73. ;; The locator starts with a locator term, among "bk.", "bks.", "book", "chap.",
  74. ;; "chaps.", "chapter", "col.", "cols.", "column", "figure", "fig.", "figs.",
  75. ;; "folio", "fol.", "fols.", "number", "no.", "nos.", "line", "l.", "ll.",
  76. ;; "note", "n.", "nn.", "opus", "op.", "opp.", "page", "p.", "pp.", "paragraph",
  77. ;; "para.", "paras.", "¶", "¶¶", "§", "§§", "part", "pt.", "pts.", "section",
  78. ;; "sec.", "secs.", "sub verbo", "s.v.", "s.vv.", "verse", "v.", "vv.",
  79. ;; "volume", "vol.", and "vols.". It ends with the last comma or digit in the
  80. ;; suffix, whichever comes last, or runs till the end of the suffix.
  81. ;;
  82. ;; The part of the suffix before the locator is appended to reference's prefix.
  83. ;; If no locator term is used, but a number is present, then "page" is assumed.
  84. ;; Filtered sub-bibliographies can be printed by passing filtering
  85. ;; options to the "print_bibliography" keywords. E.g.,
  86. ;;
  87. ;; #+print_bibliography: :type book keyword: emacs
  88. ;;
  89. ;; If you need to use a key multiple times, you can separate its
  90. ;; values with commas, but without any space in-between:
  91. ;;
  92. ;; #+print_bibliography: :keyword abc,xyz :type article
  93. ;; This library was heavily inspired by and borrows from András Simonyi's
  94. ;; Citeproc Org (<https://github.com/andras-simonyi/citeproc-org>) library.
  95. ;; Many thanks to him!
  96. ;;; Code:
  97. (require 'cl-lib)
  98. (require 'map)
  99. (require 'bibtex)
  100. (require 'json)
  101. (require 'oc)
  102. (require 'citeproc nil t)
  103. (declare-function citeproc-style-cite-note "ext:citeproc")
  104. (declare-function citeproc-proc-style "ext:citeproc")
  105. (declare-function citeproc-bt-entry-to-csl "ext:citeproc")
  106. (declare-function citeproc-locale-getter-from-dir "ext:citeproc")
  107. (declare-function citeproc-create "ext:citeproc")
  108. (declare-function citeproc-citation-create "ext:citeproc")
  109. (declare-function citeproc-append-citations "ext:citeproc")
  110. (declare-function citeproc-add-uncited "ext:citeproc")
  111. (declare-function citeproc-render-citations "ext:citeproc")
  112. (declare-function citeproc-render-bib "ext:citeproc")
  113. (declare-function citeproc-hash-itemgetter-from-any "ext:citeproc")
  114. (declare-function citeproc-add-subbib-filters "ext:citeproc")
  115. (declare-function org-element-interpret-data "org-element" (data))
  116. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  117. (declare-function org-element-property "org-element" (property element))
  118. (declare-function org-element-put-property "org-element" (element property value))
  119. (declare-function org-export-data "org-export" (data info))
  120. (declare-function org-export-derived-backend-p "org-export" (backend &rest backends))
  121. (declare-function org-export-get-footnote-number "org-export" (footnote info &optional data body-first))
  122. ;;; Customization
  123. ;;;; Location of CSL directories
  124. (defcustom org-cite-csl-locales-dir nil
  125. "Directory of CSL locale files.
  126. If nil then only the fallback en-US locale will be available."
  127. :group 'org-cite
  128. :package-version '(Org . "9.5")
  129. :type '(choice
  130. (directory :tag "Locales directory")
  131. (const :tag "Use en-US locale only" nil))
  132. ;; It's not obvious to me that arbitrary locations are safe.
  133. ;;; :safe #'string-or-null-p
  134. )
  135. (defcustom org-cite-csl-styles-dir nil
  136. "Directory of CSL style files.
  137. Relative style file names are expanded according to document's
  138. default directory. If it fails and the variable is non-nil, Org
  139. looks for style files in this directory, too."
  140. :group 'org-cite
  141. :package-version '(Org . "9.5")
  142. :type '(choice
  143. (directory :tag "Styles directory")
  144. (const :tag "No central directory for style files" nil))
  145. ;; It's not obvious to me that arbitrary locations are safe.
  146. ;;; :safe #'string-or-null-p
  147. )
  148. ;;;; Citelinks
  149. (defcustom org-cite-csl-link-cites t
  150. "When non-nil, link cites to references."
  151. :group 'org-cite
  152. :package-version '(Org . "9.5")
  153. :type 'boolean
  154. :safe #'booleanp)
  155. (defcustom org-cite-csl-no-citelinks-backends '(ascii)
  156. "List of export back-ends for which cite linking is disabled.
  157. Cite linking for export back-ends derived from any of the back-ends listed here,
  158. is also disabled."
  159. :group 'org-cite
  160. :package-version '(Org . "9.5")
  161. :type '(repeat symbol))
  162. ;;;; Output-specific variables
  163. (defcustom org-cite-csl-html-hanging-indent "1.5em"
  164. "Size of hanging-indent for HTML output in valid CSS units."
  165. :group 'org-cite
  166. :package-version '(Org . "9.5")
  167. :type 'string
  168. :safe #'stringp)
  169. (defcustom org-cite-csl-html-label-width-per-char "0.6em"
  170. "Character width in CSS units for calculating entry label widths.
  171. Used only when `second-field-align' is activated by the used CSL style."
  172. :group 'org-cite
  173. :package-version '(Org . "9.5")
  174. :type 'string
  175. :safe #'stringp)
  176. (defcustom org-cite-csl-latex-hanging-indent "1.5em"
  177. "Size of hanging-indent for LaTeX output in valid LaTeX units."
  178. :group 'org-cite
  179. :package-version '(Org . "9.5")
  180. :type 'string
  181. :safe #'stringp)
  182. ;;; Internal variables
  183. (defconst org-cite-csl--etc-dir
  184. (let ((oc-root (file-name-directory (locate-library "oc"))))
  185. (cond
  186. ;; First check whether it looks like we're running from the main
  187. ;; Org repository.
  188. ((let ((csl-org (expand-file-name "../etc/csl/" oc-root)))
  189. (and (file-directory-p csl-org) csl-org)))
  190. ;; Next look for the directory alongside oc.el because package.el
  191. ;; and straight will put all of org-mode/lisp/ in org-mode/.
  192. ((let ((csl-pkg (expand-file-name "etc/csl/" oc-root)))
  193. (and (file-directory-p csl-pkg) csl-pkg)))
  194. ;; Finally fall back the location used by shared system installs
  195. ;; and when running directly from Emacs repository.
  196. (t
  197. (expand-file-name "org/csl/" data-directory))))
  198. "Directory containing CSL-related data files.")
  199. (defconst org-cite-csl--fallback-locales-dir org-cite-csl--etc-dir
  200. "Fallback CSL locale files directory.")
  201. (defconst org-cite-csl--fallback-style-file
  202. (expand-file-name "chicago-author-date.csl"
  203. org-cite-csl--etc-dir)
  204. "Default CSL style file, or nil.
  205. If nil then the Chicago author-date style is used as a fallback.")
  206. (defconst org-cite-csl--label-alist
  207. '(("bk." . "book")
  208. ("bks." . "book")
  209. ("book" . "book")
  210. ("chap." . "chapter")
  211. ("chaps." . "chapter")
  212. ("chapter" . "chapter")
  213. ("col." . "column")
  214. ("cols." . "column")
  215. ("column" . "column")
  216. ("figure" . "figure")
  217. ("fig." . "figure")
  218. ("figs." . "figure")
  219. ("folio" . "folio")
  220. ("fol." . "folio")
  221. ("fols." . "folio")
  222. ("number" . "number")
  223. ("no." . "number")
  224. ("nos." . "number")
  225. ("line" . "line")
  226. ("l." . "line")
  227. ("ll." . "line")
  228. ("note" . "note")
  229. ("n." . "note")
  230. ("nn." . "note")
  231. ("opus" . "opus")
  232. ("op." . "opus")
  233. ("opp." . "opus")
  234. ("page" . "page")
  235. ("p" . "page")
  236. ("p." . "page")
  237. ("pp." . "page")
  238. ("paragraph" . "paragraph")
  239. ("para." . "paragraph")
  240. ("paras." . "paragraph")
  241. ("¶" . "paragraph")
  242. ("¶¶" . "paragraph")
  243. ("part" . "part")
  244. ("pt." . "part")
  245. ("pts." . "part")
  246. ("§" . "section")
  247. ("§§" . "section")
  248. ("section" . "section")
  249. ("sec." . "section")
  250. ("secs." . "section")
  251. ("sub verbo" . "sub verbo")
  252. ("s.v." . "sub verbo")
  253. ("s.vv." . "sub verbo")
  254. ("verse" . "verse")
  255. ("v." . "verse")
  256. ("vv." . "verse")
  257. ("volume" . "volume")
  258. ("vol." . "volume")
  259. ("vols." . "volume"))
  260. "Alist mapping locator names to locators.")
  261. (defconst org-cite-csl--label-regexp
  262. ;; Prior to Emacs-27.1 argument of `regexp' form must be a string literal.
  263. ;; It is the reason why `rx' is avoided here.
  264. (rx-to-string
  265. `(seq (or line-start space)
  266. (regexp ,(regexp-opt (mapcar #'car org-cite-csl--label-alist) t))
  267. (0+ digit)
  268. (or word-end line-end space " "))
  269. t)
  270. "Regexp matching a label in a citation reference suffix.
  271. Label is in match group 1.")
  272. ;;; Internal functions
  273. (defun org-cite-csl--barf-without-citeproc ()
  274. "Raise an error if Citeproc library is not loaded."
  275. (unless (featurep 'citeproc)
  276. (error "Citeproc library is not loaded")))
  277. (defun org-cite-csl--note-style-p (info)
  278. "Non-nil when bibliography style implies wrapping citations in footnotes.
  279. INFO is the export state, as a property list."
  280. (citeproc-style-cite-note
  281. (citeproc-proc-style
  282. (org-cite-csl--processor info))))
  283. (defun org-cite-csl--nocite-p (citation info)
  284. "Non-nil when CITATION object's style is nocite.
  285. INFO is the export state, as a property list."
  286. (member (car (org-cite-citation-style citation info))
  287. '("nocite" "n")))
  288. (defun org-cite-csl--create-structure-params (citation info)
  289. "Return citeproc structure creation params for CITATION object.
  290. STYLE is the citation style, as a string or nil. INFO is the export state, as
  291. a property list."
  292. (let ((style (org-cite-citation-style citation info)))
  293. (pcase style
  294. ;; "author" style.
  295. (`(,(or "author" "a") . ,variant)
  296. (pcase variant
  297. ((or "bare" "b") '(:mode author-only :suppress-affixes t))
  298. ((or "caps" "c") '(:mode author-only :capitalize-first t))
  299. ((or "full" "f") '(:mode author-only :ignore-et-al t))
  300. ((or "bare-caps" "bc") '(:mode author-only :suppress-affixes t :capitalize-first t))
  301. ((or "bare-full" "bf") '(:mode author-only :suppress-affixes t :ignore-et-al t))
  302. ((or "caps-full" "cf") '(:mode author-only :capitalize-first t :ignore-et-al t))
  303. ((or "bare-caps-full" "bcf") '(:mode author-only :suppress-affixes t :capitalize-first t :ignore-et-al t))
  304. (_ '(:mode author-only))))
  305. ;; "noauthor" style.
  306. (`(,(or "noauthor" "na") . ,variant)
  307. (pcase variant
  308. ((or "bare" "b") '(:mode suppress-author :suppress-affixes t))
  309. ((or "caps" "c") '(:mode suppress-author :capitalize-first t))
  310. ((or "bare-caps" "bc")
  311. '(:mode suppress-author :suppress-affixes t :capitalize-first t))
  312. (_ '(:mode suppress-author))))
  313. ;; "year" style.
  314. (`(,(or "year" "y") . ,variant)
  315. (pcase variant
  316. ((or "bare" "b") '(:mode year-only :suppress-affixes t))
  317. (_ '(:mode year-only))))
  318. ;; "bibentry" style.
  319. (`(,(or "bibentry" "b") . ,variant)
  320. (pcase variant
  321. ((or "bare" "b") '(:mode bib-entry :suppress-affixes t))
  322. (_ '(:mode bib-entry))))
  323. ;; "locators" style.
  324. (`(,(or "locators" "l") . ,variant)
  325. (pcase variant
  326. ((or "bare" "b") '(:mode locator-only :suppress-affixes t))
  327. (_ '(:mode locator-only))))
  328. ;; "title" style.
  329. (`(,(or "title" "ti") . ,variant)
  330. (pcase variant
  331. ((or "bare" "b") '(:mode title-only :suppress-affixes t))
  332. (_ '(:mode title-only))))
  333. ;; "text" style.
  334. (`(,(or "text" "t") . ,variant)
  335. (pcase variant
  336. ((or "caps" "c") '(:mode textual :capitalize-first t))
  337. ((or "full" "f") '(:mode textual :ignore-et-al t))
  338. ((or "caps-full" "cf") '(:mode textual :ignore-et-al t :capitalize-first t))
  339. (_ '(:mode textual))))
  340. ;; Default "nil" style.
  341. (`(,_ . ,variant)
  342. (pcase variant
  343. ((or "caps" "c") '(:capitalize-first t))
  344. ((or "bare" "b") '(:suppress-affixes t))
  345. ((or "bare-caps" "bc") '(:suppress-affixes t :capitalize-first t))
  346. (_ nil)))
  347. ;; This should not happen.
  348. (_ (error "Invalid style: %S" style)))))
  349. (defun org-cite-csl--no-citelinks-p (info)
  350. "Non-nil when export BACKEND should not create cite-reference links."
  351. (or (not org-cite-csl-link-cites)
  352. (and org-cite-csl-no-citelinks-backends
  353. (apply #'org-export-derived-backend-p
  354. (plist-get info :back-end)
  355. org-cite-csl-no-citelinks-backends))
  356. ;; No references are being exported anyway.
  357. (not (org-element-map (plist-get info :parse-tree) 'keyword
  358. (lambda (k)
  359. (equal "PRINT_BIBLIOGRAPHY" (org-element-property :key k)))
  360. info t))))
  361. (defun org-cite-csl--output-format (info)
  362. "Return expected Citeproc's output format.
  363. INFO is the export state, as a property list. The return value is a symbol
  364. corresponding to one of the output formats supported by Citeproc: `html',
  365. `latex', or `org'."
  366. (let ((backend (plist-get info :back-end)))
  367. (cond
  368. ((org-export-derived-backend-p backend 'html) 'html)
  369. ((org-export-derived-backend-p backend 'latex) 'latex)
  370. (t 'org))))
  371. (defun org-cite-csl--style-file (info)
  372. "Return style file associated to current export process.
  373. INFO is the export state, as a property list.
  374. When file name is relative, look for it in buffer's default
  375. directory, failing that in `org-cite-csl-styles-dir' if non-nil.
  376. Raise an error if no style file can be found."
  377. (pcase (org-cite-bibliography-style info)
  378. ('nil org-cite-csl--fallback-style-file)
  379. ((and (pred file-name-absolute-p) file) file)
  380. ((and (pred file-exists-p) file) (expand-file-name file))
  381. ((and (guard org-cite-csl-styles-dir)
  382. (pred (lambda (f)
  383. (file-exists-p
  384. (expand-file-name f org-cite-csl-styles-dir))))
  385. file)
  386. (expand-file-name file org-cite-csl-styles-dir))
  387. (other
  388. (user-error "CSL style file not found: %S" other))))
  389. (defun org-cite-csl--locale-getter ()
  390. "Return a locale getter.
  391. The getter looks for locales in `org-cite-csl-locales-dir' directory. If it
  392. cannot find them, it retrieves the default \"en_US\" from
  393. `org-cite-csl--fallback-locales-dir'."
  394. (lambda (loc)
  395. (or (and org-cite-csl-locales-dir
  396. (ignore-errors
  397. (funcall (citeproc-locale-getter-from-dir org-cite-csl-locales-dir)
  398. loc)))
  399. (funcall (citeproc-locale-getter-from-dir
  400. org-cite-csl--fallback-locales-dir)
  401. loc))))
  402. (defun org-cite-csl--processor (info)
  403. "Return Citeproc processor reading items from current bibliography.
  404. INFO is the export state, as a property list.
  405. Newly created processor is stored as the value of the `:cite-citeproc-processor'
  406. property in INFO."
  407. (or (plist-get info :cite-citeproc-processor)
  408. (let* ((bibliography (plist-get info :bibliography))
  409. (locale (or (plist-get info :language) "en_US"))
  410. (processor
  411. (citeproc-create
  412. (org-cite-csl--style-file info)
  413. (citeproc-hash-itemgetter-from-any bibliography)
  414. (org-cite-csl--locale-getter)
  415. locale)))
  416. (plist-put info :cite-citeproc-processor processor)
  417. processor)))
  418. (defun org-cite-csl--parse-reference (reference info)
  419. "Return Citeproc's structure associated to citation REFERENCE.
  420. INFO is the export state, as a property list.
  421. The result is a association list. Keys are: `id', `prefix',`suffix',
  422. `location', `locator' and `label'."
  423. (let (label location-start locator-start location locator prefix suffix)
  424. ;; Parse suffix. Insert it in a temporary buffer to find
  425. ;; different parts: pre-label, label, locator, location (label +
  426. ;; locator), and suffix.
  427. (with-temp-buffer
  428. (save-excursion
  429. (insert (org-element-interpret-data
  430. (org-element-property :suffix reference))))
  431. (cond
  432. ((re-search-forward org-cite-csl--label-regexp nil t)
  433. (setq location-start (match-beginning 0))
  434. (setq label (cdr (assoc (match-string 1) org-cite-csl--label-alist)))
  435. (goto-char (match-end 1))
  436. (skip-chars-forward "[:space:] ")
  437. (setq locator-start (point)))
  438. ((re-search-forward (rx digit) nil t)
  439. (setq location-start (match-beginning 0))
  440. (setq label "page")
  441. (setq locator-start location-start))
  442. (t
  443. (setq suffix (org-element-property :suffix reference))))
  444. ;; Find locator's end, and suffix, if any. To that effect, look
  445. ;; for the last comma or digit after label, whichever comes
  446. ;; last.
  447. (unless suffix
  448. (goto-char (point-max))
  449. (let ((re (rx (or "," (group digit)))))
  450. (when (re-search-backward re location-start t)
  451. (goto-char (or (match-end 1) (match-beginning 0)))
  452. (setq location (buffer-substring location-start (point)))
  453. (setq locator (org-trim (buffer-substring locator-start (point))))
  454. ;; Skip comma in suffix.
  455. (setq suffix
  456. (org-cite-parse-objects
  457. (buffer-substring (match-end 0) (point-max))
  458. t)))))
  459. (setq prefix
  460. (org-cite-concat
  461. (org-element-property :prefix reference)
  462. (and location-start
  463. (org-cite-parse-objects
  464. (buffer-substring 1 location-start)
  465. t)))))
  466. ;; Return value.
  467. (let ((export
  468. (lambda (data)
  469. (org-string-nw-p
  470. (org-trim
  471. ;; When Citeproc exports to Org syntax, avoid mix and
  472. ;; matching output formats by also generating Org
  473. ;; syntax for prefix and suffix.
  474. (if (eq 'org (org-cite-csl--output-format info))
  475. (org-element-interpret-data data)
  476. (org-export-data data info)))))))
  477. `((id . ,(org-element-property :key reference))
  478. (prefix . ,(funcall export prefix))
  479. (suffix . ,(funcall export suffix))
  480. (locator . ,locator)
  481. (label . ,label)
  482. (location . ,location)))))
  483. (defun org-cite-csl--create-structure (citation info)
  484. "Create Citeproc structure for CITATION object.
  485. INFO is the export state, as a property list."
  486. (let* ((cites (mapcar (lambda (r)
  487. (org-cite-csl--parse-reference r info))
  488. (org-cite-get-references citation)))
  489. (footnote (org-cite-inside-footnote-p citation)))
  490. ;; Global prefix is inserted in front of the prefix of the first
  491. ;; reference.
  492. (let ((global-prefix (org-element-property :prefix citation)))
  493. (when global-prefix
  494. (let* ((first (car cites))
  495. (prefix-item (assq 'prefix first)))
  496. (setcdr prefix-item
  497. (concat (org-element-interpret-data global-prefix)
  498. " "
  499. (cdr prefix-item))))))
  500. ;; Global suffix is appended to the suffix of the last reference.
  501. (let ((global-suffix (org-element-property :suffix citation)))
  502. (when global-suffix
  503. (let* ((last (org-last cites))
  504. (suffix-item (assq 'suffix last)))
  505. (setcdr suffix-item
  506. (concat (cdr suffix-item)
  507. " "
  508. (org-element-interpret-data global-suffix))))))
  509. ;; Check if CITATION needs wrapping, i.e., it should be wrapped in
  510. ;; a footnote, but isn't yet.
  511. (when (and (not footnote) (org-cite-csl--note-style-p info))
  512. (org-cite-adjust-note citation info)
  513. (setq footnote (org-cite-wrap-citation citation info)))
  514. ;; Return structure.
  515. (apply #'citeproc-citation-create
  516. `(:note-index
  517. ,(and footnote (org-export-get-footnote-number footnote info))
  518. :cites ,cites
  519. ,@(org-cite-csl--create-structure-params citation info)))))
  520. (defun org-cite-csl--rendered-citations (info)
  521. "Return the rendered citations as an association list.
  522. INFO is the export state, as a property list.
  523. Return an alist (CITATION . OUTPUT) where CITATION object has been rendered as
  524. OUTPUT using Citeproc."
  525. (or (plist-get info :cite-citeproc-rendered-citations)
  526. (let ((citations (org-cite-list-citations info))
  527. (processor (org-cite-csl--processor info))
  528. normal-citations nocite-ids)
  529. (dolist (citation citations)
  530. (if (org-cite-csl--nocite-p citation info)
  531. (setq nocite-ids (append (org-cite-get-references citation t) nocite-ids))
  532. (push citation normal-citations)))
  533. (let ((structures
  534. (mapcar (lambda (c) (org-cite-csl--create-structure c info))
  535. (nreverse normal-citations))))
  536. (citeproc-append-citations structures processor))
  537. (when nocite-ids
  538. (citeproc-add-uncited nocite-ids processor))
  539. ;; All bibliographies have to be rendered in order to have
  540. ;; correct citation numbers even if there are several
  541. ;; sub-bibliograhies.
  542. (org-cite-csl--rendered-bibliographies info)
  543. (let (result
  544. (rendered (citeproc-render-citations
  545. processor
  546. (org-cite-csl--output-format info)
  547. (org-cite-csl--no-citelinks-p info))))
  548. (dolist (citation citations)
  549. (push (cons citation
  550. (if (org-cite-csl--nocite-p citation info) "" (pop rendered)))
  551. result))
  552. (setq result (nreverse result))
  553. (plist-put info :cite-citeproc-rendered-citations result)
  554. result))))
  555. (defun org-cite-csl--bibliography-filter (bib-props)
  556. "Return the sub-bibliography filter corresponding to bibliography properties.
  557. BIB-PROPS should be a plist representing the properties
  558. associated with a \"print_bibliography\" keyword, as returned by
  559. `org-cite-bibliography-properties'."
  560. (let (result
  561. (remove-keyword-colon (lambda (x) (intern (substring (symbol-name x) 1)))))
  562. (map-do
  563. (lambda (key value)
  564. (pcase key
  565. ((or :keyword :notkeyword :nottype :notcsltype :filter)
  566. (dolist (v (split-string value ","))
  567. (push (cons (funcall remove-keyword-colon key) v) result)))
  568. ((or :type :csltype)
  569. (if (string-match-p "," value)
  570. (user-error "The \"%s\" print_bibliography option does not support comma-separated values" key)
  571. (push (cons (funcall remove-keyword-colon key) value) result)))))
  572. bib-props)
  573. result))
  574. (defun org-cite-csl--rendered-bibliographies (info)
  575. "Return the rendered bibliographies.
  576. INFO is the export state, as a property list.
  577. Return an (OUTPUTS PARAMETERS) list where OUTPUTS is an alist
  578. of (BIB-PROPS . OUTPUT) pairs where each key is a property list
  579. of a \"print_bibliography\" keyword and the corresponding OUTPUT
  580. value is the bibliography as rendered by Citeproc."
  581. (or (plist-get info :cite-citeproc-rendered-bibliographies)
  582. (let (bib-plists bib-filters)
  583. ;; Collect bibliography property lists and the corresponding
  584. ;; Citeproc sub-bib filters.
  585. (org-element-map (plist-get info :parse-tree) 'keyword
  586. (lambda (keyword)
  587. (when (equal "PRINT_BIBLIOGRAPHY" (org-element-property :key keyword))
  588. (let ((bib-plist (org-cite-bibliography-properties keyword)))
  589. (push bib-plist bib-plists)
  590. (push (org-cite-csl--bibliography-filter bib-plist) bib-filters)))))
  591. (setq bib-filters (nreverse bib-filters)
  592. bib-plists (nreverse bib-plists))
  593. ;; Render and return all bibliographies.
  594. (let ((processor (org-cite-csl--processor info)))
  595. (citeproc-add-subbib-filters bib-filters processor)
  596. (pcase-let* ((format (org-cite-csl--output-format info))
  597. (`(,rendered-bibs . ,parameters)
  598. (citeproc-render-bib
  599. (org-cite-csl--processor info)
  600. format
  601. (org-cite-csl--no-citelinks-p info)))
  602. (outputs (cl-mapcar #'cons bib-plists rendered-bibs))
  603. (result (list outputs parameters)))
  604. (plist-put info :cite-citeproc-rendered-bibliographies result)
  605. result)))))
  606. ;;; Export capability
  607. (defun org-cite-csl-render-citation (citation _style _backend info)
  608. "Export CITATION object.
  609. INFO is the export state, as a property list."
  610. (org-cite-csl--barf-without-citeproc)
  611. (let ((output (cdr (assq citation (org-cite-csl--rendered-citations info)))))
  612. (if (not (eq 'org (org-cite-csl--output-format info)))
  613. output
  614. ;; Parse Org output to re-export it during the regular export
  615. ;; process.
  616. (org-cite-parse-objects output))))
  617. (defun org-cite-csl-render-bibliography (_keys _files _style props _backend info)
  618. "Export bibliography.
  619. INFO is the export state, as a property list."
  620. (org-cite-csl--barf-without-citeproc)
  621. (pcase-let* ((format (org-cite-csl--output-format info))
  622. (`(,outputs ,parameters) (org-cite-csl--rendered-bibliographies info))
  623. (output (cdr (assoc props outputs))))
  624. (pcase format
  625. ('html
  626. (concat
  627. (and (cdr (assq 'second-field-align parameters))
  628. (let* ((max-offset (cdr (assq 'max-offset parameters)))
  629. (char-width
  630. (string-to-number org-cite-csl-html-label-width-per-char))
  631. (char-width-unit
  632. (progn
  633. (string-match (number-to-string char-width)
  634. org-cite-csl-html-label-width-per-char)
  635. (substring org-cite-csl-html-label-width-per-char
  636. (match-end 0)))))
  637. (format
  638. "<style>.csl-left-margin{float: left; padding-right: 0em;}
  639. .csl-right-inline{margin: 0 0 0 %d%s;}</style>"
  640. (* max-offset char-width)
  641. char-width-unit)))
  642. (and (cdr (assq 'hanging-indent parameters))
  643. (format
  644. "<style>.csl-entry{text-indent: -%s; margin-left: %s;}</style>"
  645. org-cite-csl-html-hanging-indent
  646. org-cite-csl-html-hanging-indent))
  647. output))
  648. ('latex
  649. (if (cdr (assq 'hanging-indent parameters))
  650. (format "\\begin{hangparas}{%s}{1}\n%s\n\\end{hangparas}"
  651. org-cite-csl-latex-hanging-indent
  652. output)
  653. output))
  654. (_
  655. ;; Parse Org output to re-export it during the regular export
  656. ;; process.
  657. (org-cite-parse-elements output)))))
  658. (defun org-cite-csl-finalizer (output _keys _files _style _backend info)
  659. "Add \"hanging\" package if missing from LaTeX output.
  660. OUTPUT is the export document, as a string. INFO is the export state, as a
  661. property list."
  662. (org-cite-csl--barf-without-citeproc)
  663. (if (not (eq 'latex (org-cite-csl--output-format info)))
  664. output
  665. (with-temp-buffer
  666. (save-excursion (insert output))
  667. (when (search-forward "\\begin{document}" nil t)
  668. (goto-char (match-beginning 0))
  669. ;; Ensure that \citeprocitem is defined for citeproc-el.
  670. (insert "\\makeatletter\n\\newcommand{\\citeprocitem}[2]{\\hyper@linkstart{cite}{citeproc_bib_item_#1}#2\\hyper@linkend}\n\\makeatother\n\n")
  671. ;; Ensure there is a \usepackage{hanging} somewhere or add one.
  672. (let ((re (rx "\\usepackage" (opt "[" (*? nonl) "]") "{hanging}")))
  673. (unless (re-search-backward re nil t)
  674. (insert "\\usepackage[notquote]{hanging}\n"))))
  675. (buffer-string))))
  676. ;;; Register `csl' processor
  677. (org-cite-register-processor 'csl
  678. :export-citation #'org-cite-csl-render-citation
  679. :export-bibliography #'org-cite-csl-render-bibliography
  680. :export-finalizer #'org-cite-csl-finalizer
  681. :cite-styles
  682. '((("author" "a") ("bare" "b") ("caps" "c") ("full" "f") ("bare-caps" "bc") ("caps-full" "cf") ("bare-caps-full" "bcf"))
  683. (("noauthor" "na") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
  684. (("year" "y") ("bare" "b"))
  685. (("text" "t") ("caps" "c") ("full" "f") ("caps-full" "cf"))
  686. (("nil") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
  687. (("nocite" "n"))
  688. (("title" "ti") ("bare" "b"))
  689. (("bibentry" "b") ("bare" "b"))
  690. (("locators" "l") ("bare" "b"))))
  691. (provide 'oc-csl)
  692. ;;; oc-csl.el ends here