oc-csl.el 26 KB

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