oc-csl.el 25 KB

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