oc-csl.el 31 KB

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