oc-csl.el 26 KB

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