oc-csl.el 25 KB

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