oc.el 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. ;;; oc.el --- Org Cite library -*- 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 provides tooling to handle citations in Org, e.g,
  17. ;; activate, follow, insert, and export them, respectively called
  18. ;; "activate", "follow", "insert" and "export" capabilities.
  19. ;; Libraries responsible for providing some, or all, of these
  20. ;; capabilities are called "citation processors".
  21. ;; Such processors are defined using `org-cite-register-processor'.
  22. ;; Using this function, it is possible, in addition to giving it a
  23. ;; name, to attach functions associated to capabilities. As such, a
  24. ;; processor handling citation export must set the `:export-citation'
  25. ;; property to an appropriate function. Likewise, "activate"
  26. ;; capability requires an appropriate `:activate' property, "insert"
  27. ;; requires `:insert' property and, unsurprisingly, "follow"
  28. ;; capability implies `:follow' property.
  29. ;; As a user, the first thing to do is setting a bibliography, either
  30. ;; globally with `org-cite-global-bibliography', or locally using one
  31. ;; or more "bibliography" keywords. Then one can select any
  32. ;; registered processor for each capability by providing a processor
  33. ;; name to the variables `org-cite-activate-processor' and
  34. ;; `org-cite-follow-processor'.
  35. ;; The "export" capability is slightly more involved as one need to
  36. ;; select the processor providing it, but may also provide a default
  37. ;; style for citations and bibliography. Also, the choice of an
  38. ;; export processor may depend of the current export back-end. The
  39. ;; association between export back-ends and triplets of parameters can
  40. ;; be set in `org-cite-export-processors' variable, or in a document,
  41. ;; through the "cite_export" keyword.
  42. ;; Eventually, this library provides some tools, mainly targeted at
  43. ;; processor implementors. Most are export-specific and are located
  44. ;; in the "Tools only available during export" and "Tools generating
  45. ;; or operating on parsed data" sections.
  46. ;; The few others can be used directly from an Org buffer, or operate
  47. ;; on processors. See "Generic tools" section.
  48. ;;; Code:
  49. (require 'org-compat)
  50. (require 'org-macs)
  51. (require 'seq)
  52. (declare-function org-at-heading-p "org" (&optional _))
  53. (declare-function org-collect-keywords "org" (keywords &optional unique directory))
  54. (declare-function org-element-adopt-elements "org-element" (parent &rest children))
  55. (declare-function org-element-citation-parser "org-element" ())
  56. (declare-function org-element-citation-reference-parser "org-element" ())
  57. (declare-function org-element-class "org-element" (datum &optional parent))
  58. (declare-function org-element-contents "org-element" (element))
  59. (declare-function org-element-create "org-element" (type &optional props &rest children))
  60. (declare-function org-element-extract-element "org-element" (element))
  61. (declare-function org-element-insert-before "org-element" (element location))
  62. (declare-function org-element-lineage "org-element" (datum &optional types with-self))
  63. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  64. (declare-function org-element-normalize-string "org-element" (s))
  65. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  66. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  67. (declare-function org-element-context "org-element" (&optional element))
  68. (declare-function org-element-property "org-element" (property element))
  69. (declare-function org-element-put-property "org-element" (element property value))
  70. (declare-function org-element-restriction "org-element" (element))
  71. (declare-function org-element-set-element "org-element" (old new))
  72. (declare-function org-element-type "org-element" (element))
  73. (declare-function org-export-derived-backend-p "org-export" (backend &rest backends))
  74. (declare-function org-export-get-next-element "org-export" (blob info &optional n))
  75. (declare-function org-export-get-previous-element "org-export" (blob info &optional n))
  76. (declare-function org-export-raw-string "org-export" (s))
  77. (defvar org-complex-heading-regexp)
  78. (defvar org-element-all-objects)
  79. (defvar org-element-citation-key-re)
  80. (defvar org-element-citation-prefix-re)
  81. (defvar org-element-parsed-keywords)
  82. ;;; Constants
  83. ;; Borrowed from "citeproc.el" library.
  84. (defconst org-cite--default-region-alist
  85. '(("af" . "za") ("ca" . "ad") ("cs" . "cz") ("cy" . "gb")
  86. ("da" . "dk") ("el" . "gr") ("et" . "ee") ("fa" . "ir")
  87. ("he" . "ir") ("ja" . "jp") ("km" . "kh") ("ko" . "kr")
  88. ("nb" . "no") ("nn" . "no") ("sl" . "si") ("sr" . "rs")
  89. ("sv" . "se") ("uk" . "ua") ("vi" . "vn") ("zh" . "cn"))
  90. "Alist mapping those languages to their default region.
  91. Only those languages are given for which the default region is not simply the
  92. result of duplicating the language part.")
  93. ;;; Configuration variables
  94. (defgroup org-cite nil
  95. "Options concerning citations in Org mode."
  96. :group 'org
  97. :tag "Org Cite")
  98. (defcustom org-cite-global-bibliography nil
  99. "List of bibliography files available in all documents.
  100. File names must be absolute."
  101. :group 'org-cite
  102. :package-version '(Org . "9.5")
  103. :type '(choice (const :tag "No global bibliography" nil)
  104. (repeat :tag "List of bibliography files"
  105. (file :tag "Bibliography"))))
  106. (defcustom org-cite-activate-processor 'basic
  107. "Processor used for activating citations, as a symbol."
  108. :group 'org-cite
  109. :package-version '(Org . "9.5")
  110. :type '(choice (const :tag "Default fontification" nil)
  111. (symbol :tag "Citation processor")))
  112. (defcustom org-cite-export-processors '((t basic))
  113. "Processor used for exporting citations, as a triplet, or nil.
  114. When nil, citations and bibliography are not exported.
  115. When non-nil, the value is an association list between export back-ends and
  116. citation export processors:
  117. (BACK-END . PROCESSOR)
  118. where BACK-END is the name of an export back-end or t, and PROCESSOR is a
  119. triplet following the pattern
  120. (NAME BIBLIOGRAPHY-STYLE CITATION-STYLE)
  121. There, NAME is the name of a registered citation processor providing export
  122. functionality, as a symbol. BIBLIOGRAPHY-STYLE (respectively CITATION-STYLE)
  123. is the desired default style to use when printing a bibliography (respectively
  124. exporting a citation), as a string or nil. Both BIBLIOGRAPHY-STYLE and
  125. CITATION-STYLE are optional. NAME is mandatory.
  126. The export process selects the citation processor associated to the current
  127. export back-end, or the most specific back-end the current one is derived from,
  128. or, if all are inadequate, to the processor associated to t. For example, with
  129. the following value
  130. ((beamer natbib)
  131. (latex biblatex)
  132. (t csl))
  133. exporting with `beamer' or any back-end derived from it will use `natbib',
  134. whereas exporting with `latex' or any back-end derived from it but different
  135. from `beamer' will use `biblatex' processor. Any other back-end, such as
  136. `html', will use `csl' processor.
  137. CITATION-STYLE is overridden by adding a style to any citation object. A nil
  138. style lets the export processor choose the default output. Any style not
  139. recognized by the export processor is equivalent to nil.
  140. The citation triplet can also be set with the CITE_EXPORT keyword.
  141. E.g.,
  142. #+CITE_EXPORT: basic note numeric
  143. or
  144. #+CITE_EXPORT: basic
  145. In that case, `basic' processor is used on every export, independently on the
  146. back-end."
  147. :group 'org-cite
  148. :package-version '(Org . "9.5")
  149. :type '(choice (const :tag "No export" nil)
  150. (alist :key-type symbol
  151. :value-type
  152. (list :tag "Citation processor"
  153. (symbol :tag "Processor name")
  154. (choice
  155. (const :tag "Default bibliography style" nil)
  156. (string :tag "Use specific bibliography style"))
  157. (choice
  158. (const :tag "Default citation style" nil)
  159. (string :tag "Use specific citation style"))))))
  160. (defcustom org-cite-follow-processor 'basic
  161. "Processor used for following citations, as a symbol."
  162. :group 'org-cite
  163. :package-version '(Org . "9.5")
  164. :type '(choice (const :tag "No following" nil)
  165. (symbol :tag "Citation processor")))
  166. (defcustom org-cite-insert-processor 'basic
  167. "Processor used for inserting citations, as a symbol."
  168. :group 'org-cite
  169. :package-version '(Org . "9.5")
  170. :type '(choice (const :tag "No insertion" nil)
  171. (symbol :tag "Citation processor")))
  172. (defcustom org-cite-adjust-note-numbers t
  173. "When non-nil, allow process to modify location of note numbers.
  174. When this variable is non-nil, it is possible to swap between author-date and
  175. note style without modifying the document. To that effect, citations should
  176. always be located as in an author-date style. Prior to turning the citation
  177. into a footnote, the citation processor moves the citation (i.e., the future
  178. note number), and the surrounding punctuation, according to rules defined in
  179. `org-cite-note-rules'.
  180. When nil, the note number is not moved."
  181. :group 'org-cite
  182. :package-version '(Org . "9.5")
  183. :type '(choice (const :tag "Automatic note number location" t)
  184. (const :tag "Place note numbers manually" nil))
  185. :safe #'booleanp)
  186. (defcustom org-cite-note-rules
  187. '(("en-us" inside outside after)
  188. ("fr" adaptive same before))
  189. "Alist between languages and typographic rules for citations in note style.
  190. When `org-cite-adjust-note-numbers' is non-nil, and note style is requested,
  191. citation processor is allowed to move the note marker according to some specific
  192. rules, detailed here. More accurately, a rule is a list following the pattern
  193. (LANGUAGE-TAG . RULE)
  194. LANGUAGE-TAG is a down-cased string representing a language tag as defined in
  195. RFC 4646. It may constituted of a language and a region separated with an
  196. hyphen (e.g., \"en-us\"), or the language alone (e.g., \"fr\"). A language
  197. without a region applies to all regions.
  198. RULE is a triplet
  199. (PUNCTUATION NUMBER ORDER)
  200. PUNCTUATION is the desired location of the punctuation with regards to the
  201. quotation, if any. It may be `inside', `outside', or `adaptive'. The latter
  202. permits subtler control over the punctuation: when there is no space between
  203. the quotation mark and the punctuation, it is equivalent to `inside'.
  204. Otherwise, it means `outside', as illustrated in the following examples:
  205. \"A quotation ending without punctuation\" [cite:@org21].
  206. \"A quotation ending with a period\"[cite:@org21].
  207. Notwithstanding the above, a space always appear before the citation when it
  208. is to become anything else than a note.
  209. NUMBER is the desired location of the note number with regards to the
  210. quotation mark, if any. It may be `inside', `outside', or `same'. When set
  211. to `same', the number appears on the same side as the punctuation, unless
  212. there is punctuation on both sides or on none.
  213. ORDER is the relative position of the citation with regards to the closest
  214. punctuation. It may be `after' or `before'.
  215. For example (adaptive same before) corresponds to French typography.
  216. When the locale is unknown to this variable, the default rule is:
  217. (adaptive outside after)
  218. This roughly follows the Oxford Guide to Style recommendations."
  219. :group 'org-cite
  220. :package-version '(Org . "9.5")
  221. :type
  222. '(repeat
  223. (list :tag "Typographic rule"
  224. (string :tag "Language code")
  225. (choice :tag "Location of punctuation"
  226. (const :tag "Punctuation inside quotation" inside)
  227. (const :tag "Punctuation outside quotation" outside)
  228. (const :tag "Location depends on spacing" adaptive))
  229. (choice :tag "Location of citation"
  230. (const :tag "Citation inside quotation" inside)
  231. (const :tag "Citation outside quotation" outside)
  232. (const :tag "Citation next to punctuation" same))
  233. (choice :tag "Order of citation and punctuation"
  234. (const :tag "Citation first" before)
  235. (const :tag "Citation last" after)))))
  236. (defcustom org-cite-punctuation-marks '("." "," ";" ":" "!" "?")
  237. "List of strings that can be moved around when placing note numbers.
  238. When `org-cite-adjust-note-numbers' is non-nil, the citation processor is
  239. allowed to shuffle punctuation marks specified in this list in order to
  240. place note numbers according to rules defined in `org-cite-note-rules'."
  241. :group 'org-cite
  242. :package-version '(Org . "9.5")
  243. :type '(repeat string))
  244. ;;; Citation processors
  245. (cl-defstruct (org-cite-processor (:constructor org-cite--make-processor)
  246. (:copier nil))
  247. (name nil :read-only t)
  248. (activate nil :read-only t)
  249. (cite-styles nil :read-only t)
  250. (export-bibliography nil :read-only t)
  251. (export-citation nil :read-only t)
  252. (export-finalizer nil :read-only t)
  253. (follow nil :read-only t)
  254. (insert nil :read-only t))
  255. (defvar org-cite--processors nil
  256. "List of registered citation processors.
  257. See `org-cite-register-processor' for more information about
  258. processors.")
  259. (defun org-cite--get-processor (name)
  260. "Return citation processor named after symbol NAME.
  261. Return nil if no such processor is found."
  262. (seq-find (lambda (p) (eq name (org-cite-processor-name p)))
  263. org-cite--processors))
  264. (defun org-cite-register-processor (name &rest body)
  265. "Mark citation processor NAME as available.
  266. NAME is a symbol. BODY is a property list, where the following
  267. optional keys can be set:
  268. `:activate'
  269. Function activating a citation. It is called with a single
  270. argument: a citation object extracted from the current
  271. buffer. It may add text properties to the buffer. If it is
  272. not provided, `org-cite-fontify-default' is used.
  273. `:export-bibliography'
  274. Function rendering a bibliography. It is called with six
  275. arguments: the list of citation keys used in the document, as
  276. strings, a list of bibliography files, the style, as a string
  277. or nil, the local properties, as a property list, the export
  278. back-end, as a symbol, and the communication channel, as a
  279. property list.
  280. It is called at each \"print_bibliography\" keyword in the
  281. parse tree. It may return a string, a parsed element, a list
  282. of parsed elements, or nil. When it returns nil, the keyword
  283. is ignored. Otherwise, the value it returns replaces the
  284. keyword in the export output.
  285. `:export-citation' (mandatory for \"export\" capability)
  286. Function rendering citations. It is called with four
  287. arguments: a citation object, the style, as a pair, the
  288. export back-end, as a symbol, and the communication channel,
  289. as a property list.
  290. It is called on each citation object in the parse tree. It
  291. may return a string, a parsed object, a secondary string, or
  292. nil. When it returns nil, the citation is ignored.
  293. Otherwise, the value it returns replaces the citation object
  294. in the export output.
  295. `:export-finalizer'
  296. Function called at the end of export process. It must accept
  297. six arguments: the output, as a string, a list of citation
  298. keys used in the document, a list of bibliography files, the
  299. expected bibliography style, as a string or nil, the export
  300. back-end, as a symbol, and the communication channel, as a
  301. property list.
  302. It must return a string, which will become the final output
  303. from the export process, barring subsequent modifications
  304. from export filters.
  305. `:follow'
  306. Function called to follow a citation. It accepts two
  307. arguments, the citation or citation reference object at
  308. point, and any prefix argument received during interactive
  309. call of `org-open-at-point'.
  310. `:insert'
  311. Function called to insert a citation. It accepts two
  312. arguments, the citation or citation reference object at point
  313. or nil, and any prefix argument received.
  314. `:cite-styles'
  315. When the processor has export capability, the value can
  316. specify what cite styles, variants, and their associated
  317. shortcuts are supported. It can be useful information for
  318. completion or linting.
  319. The expected format is
  320. ((STYLE . SHORTCUTS) . VARIANTS))
  321. where STYLE is a string, SHORTCUTS a list of strings or nil,
  322. and VARIANTS is a list of pairs (VARIANT . SHORTCUTS),
  323. VARIANT being a string and SHORTCUTS a list of strings or
  324. nil.
  325. The \"nil\" style denotes the processor fall-back style. It
  326. should have a corresponding entry in the value.
  327. Return a non-nil value on a successful operation."
  328. (declare (indent 1))
  329. (unless (and name (symbolp name))
  330. (error "Invalid processor name: %S" name))
  331. (when (org-cite--get-processor name)
  332. (org-cite-unregister-processor name))
  333. (push (apply #'org-cite--make-processor :name name body)
  334. org-cite--processors))
  335. (defun org-cite-unregister-processor (name)
  336. "Unregister citation processor NAME.
  337. NAME is a symbol. Raise an error if processor is not registered.
  338. Return a non-nil value on a successful operation."
  339. (unless (and name (symbolp name))
  340. (error "Invalid processor name: %S" name))
  341. (pcase (org-cite--get-processor name)
  342. ('nil (error "Processor %S not registered" name))
  343. (processor
  344. (setq org-cite--processors (delete processor org-cite--processors))))
  345. t)
  346. (defun org-cite-processor-has-capability-p (processor capability)
  347. "Return non-nil if PROCESSOR is able to handle CAPABILITY.
  348. PROCESSOR is the name of a cite processor, as a symbol. CAPABILITY is
  349. `activate', `export', `follow', or `insert'."
  350. (let ((p (org-cite--get-processor processor)))
  351. (pcase capability
  352. ((guard (not p)) nil) ;undefined processor
  353. ('activate (functionp (org-cite-processor-activate p)))
  354. ('export (functionp (org-cite-processor-export-citation p)))
  355. ('follow (functionp (org-cite-processor-follow p)))
  356. ('insert (functionp (org-cite-processor-insert p)))
  357. (other (error "Invalid capability: %S" other)))))
  358. ;;; Internal functions
  359. (defun org-cite--set-post-blank (datum blanks)
  360. "Set `:post-blank' property from element or object before DATUM to BLANKS.
  361. DATUM is an element or object. BLANKS is an integer. DATUM is modified
  362. by side-effect."
  363. (if (not (eq 'plain-text (org-element-type datum)))
  364. (org-element-put-property datum :post-blank blanks)
  365. ;; Remove any blank from string before DATUM so it is exported
  366. ;; with exactly BLANKS white spaces.
  367. (org-element-set-element
  368. datum
  369. (replace-regexp-in-string
  370. "[ \t\n]*\\'" (make-string blanks ?\s) datum))))
  371. (defun org-cite--set-previous-post-blank (datum blanks info)
  372. "Set `:post-blank' property from element or object before DATUM to BLANKS.
  373. DATUM is an element or object. BLANKS is an integer. INFO is the export
  374. state, as a property list. Previous element or object, if any, is modified by
  375. side-effect."
  376. (let ((previous (org-export-get-previous-element datum info)))
  377. (when previous
  378. (org-cite--set-post-blank previous blanks))))
  379. (defun org-cite--insert-at-split (s citation n regexp)
  380. "Split string S and insert CITATION object between the two parts.
  381. S is split at beginning of match group N upon matching REGEXP against it.
  382. This function assumes S precedes CITATION."
  383. ;; When extracting the citation, remove white spaces before it, but
  384. ;; preserve those after it.
  385. (let ((post-blank (org-element-property :post-blank citation)))
  386. (when (and post-blank (> post-blank 0))
  387. (org-element-insert-before (make-string post-blank ?\s) citation)))
  388. (org-element-insert-before
  389. (org-element-put-property (org-element-extract-element citation)
  390. :post-blank 0)
  391. s)
  392. (string-match regexp s)
  393. (let* ((split (match-beginning n))
  394. (first-part (substring s nil split))
  395. ;; Remove trailing white spaces as they are before the
  396. ;; citation.
  397. (last-part
  398. (replace-regexp-in-string (rx (1+ (any blank ?\n)) string-end)
  399. ""
  400. (substring s split))))
  401. (when (org-string-nw-p first-part)
  402. (org-element-insert-before first-part citation))
  403. (org-element-set-element s last-part)))
  404. (defun org-cite--move-punct-before (punct citation s info)
  405. "Move punctuation PUNCT before CITATION object.
  406. String S contains PUNCT. INFO is the export state, as a property list.
  407. The function assumes S follows CITATION. Parse tree is modified by side-effect."
  408. (if (equal s punct)
  409. (org-element-extract-element s) ;it would be empty anyway
  410. (org-element-set-element s (substring s (length punct))))
  411. ;; Remove blanks before citation.
  412. (org-cite--set-previous-post-blank citation 0 info)
  413. (org-element-insert-before
  414. ;; Blanks between citation and punct are now before punct and
  415. ;; citation.
  416. (concat (make-string (or (org-element-property :post-blank citation) 0) ?\s)
  417. punct)
  418. citation))
  419. (defun org-cite--parse-as-plist (s)
  420. "Parse string S as a property list.
  421. Values are always strings. Return nil if S is nil."
  422. (cond
  423. ((null s) nil)
  424. ((stringp s)
  425. (with-temp-buffer
  426. (save-excursion (insert s))
  427. (skip-chars-forward " \t")
  428. (let ((results nil)
  429. (value-flag nil))
  430. (while (not (eobp))
  431. (pcase (char-after)
  432. (?:
  433. (push (read (current-buffer)) results)
  434. (setq value-flag t))
  435. ((guard (not value-flag))
  436. (skip-chars-forward "^ \t"))
  437. (?\"
  438. (let ((origin (point)))
  439. (condition-case _
  440. (progn
  441. (read (current-buffer))
  442. (push (buffer-substring (1+ origin) (1- (point))) results))
  443. (end-of-file
  444. (goto-char origin)
  445. (skip-chars-forward "^ \t")
  446. (push (buffer-substring origin (point)) results)))
  447. (setq value-flag nil)))
  448. (_
  449. (let ((origin (point)))
  450. (skip-chars-forward "^ \t")
  451. (push (buffer-substring origin (point)) results)
  452. (setq value-flag nil))))
  453. (skip-chars-forward " \t"))
  454. (nreverse results))))
  455. (t (error "Invalid argument type: %S" s))))
  456. (defun org-cite--get-note-rule (info)
  457. "Return punctuation rule according to language used for export.
  458. INFO is the export state, as a property list.
  459. Rule is found according to the language used for export and
  460. `org-cite-note-rules', which see.
  461. If there is no rule matching current language, the rule defaults
  462. to (adaptive outside after)."
  463. (let* ((language-tags
  464. ;; Normalize language as a language-region tag, as described
  465. ;; in RFC 4646.
  466. (pcase (split-string (plist-get info :language) "[-_]")
  467. (`(,language)
  468. (list language
  469. (or (cdr (assoc language org-cite--default-region-alist))
  470. language)))
  471. (`(,language ,region)
  472. (list language region))
  473. (other
  474. (error "Invalid language identifier: %S" other))))
  475. (language-region (mapconcat #'downcase language-tags "-"))
  476. (language (car language-tags)))
  477. (or (cdr (assoc language-region org-cite-note-rules))
  478. (cdr (assoc language org-cite-note-rules))
  479. '(adaptive outside after))))
  480. ;;; Generic tools
  481. (defun org-cite-list-bibliography-files ()
  482. "List all bibliography files defined in the buffer."
  483. (delete-dups
  484. (append (mapcar (lambda (value)
  485. (pcase value
  486. (`(,f . ,d)
  487. (expand-file-name (org-strip-quotes f) d))))
  488. (pcase (org-collect-keywords
  489. '("BIBLIOGRAPHY") nil '("BIBLIOGRAPHY"))
  490. (`(("BIBLIOGRAPHY" . ,pairs)) pairs)))
  491. org-cite-global-bibliography)))
  492. (defun org-cite-get-references (citation &optional keys-only)
  493. "Return citations references contained in CITATION object.
  494. When optional argument KEYS-ONLY is non-nil, return the references' keys, as a
  495. list of strings.
  496. Assume CITATION object comes from either a full parse tree, e.g., during export,
  497. or from the current buffer."
  498. (let ((contents (org-element-contents citation)))
  499. (cond
  500. ((null contents)
  501. (org-with-point-at (org-element-property :contents-begin citation)
  502. (narrow-to-region (point) (org-element-property :contents-end citation))
  503. (let ((references nil))
  504. (while (not (eobp))
  505. (let ((reference (org-element-citation-reference-parser)))
  506. (goto-char (org-element-property :end reference))
  507. (push (if keys-only
  508. (org-element-property :key reference)
  509. reference)
  510. references)))
  511. (nreverse references))))
  512. (keys-only (mapcar (lambda (r) (org-element-property :key r)) contents))
  513. (t contents))))
  514. (defun org-cite-boundaries (citation)
  515. "Return the beginning and end strict position of CITATION.
  516. Returns a (BEG . END) pair."
  517. (let ((beg (org-element-property :begin citation))
  518. (end (org-with-point-at (org-element-property :end citation)
  519. (skip-chars-backward " \t")
  520. (point))))
  521. (cons beg end)))
  522. (defun org-cite-key-boundaries (reference)
  523. "Return citation REFERENCE's key boundaries as buffer positions.
  524. The function returns a pair (START . END) where START and END denote positions
  525. in the current buffer. Positions include leading \"@\" character."
  526. (org-with-point-at (org-element-property :begin reference)
  527. (let ((end (org-element-property :end reference)))
  528. (re-search-forward org-element-citation-key-re end t)
  529. (cons (match-beginning 0) (match-end 0)))))
  530. (defun org-cite-main-affixes (citation)
  531. "Return main affixes for CITATION object.
  532. Some export back-ends only support a single pair of affixes per
  533. citation, even if it contains multiple keys. This function
  534. decides what affixes are the most appropriate.
  535. Return a pair (PREFIX . SUFFIX) where PREFIX and SUFFIX are
  536. parsed data."
  537. (let ((source
  538. ;; When there are multiple references, use global affixes.
  539. ;; Otherwise, local affixes have priority.
  540. (pcase (org-cite-get-references citation)
  541. (`(,reference) reference)
  542. (_ citation))))
  543. (cons (org-element-property :prefix source)
  544. (org-element-property :suffix source))))
  545. (defun org-cite-supported-styles (&optional processors)
  546. "List of supported citation styles and variants.
  547. Supported styles are those handled by export processors from
  548. `org-cite-export-processors', or in PROCESSORS, as a list of symbols,
  549. when non-nil.
  550. Return value is a list with the following items:
  551. ((STYLE . SHORTCUTS) . VARIANTS))
  552. where STYLE is a string, SHORTCUTS a list of strings, and VARIANTS is a list of
  553. pairs (VARIANT . SHORTCUTS), VARIANT being a string and SHORTCUTS a list of
  554. strings."
  555. (let ((collection
  556. (seq-mapcat
  557. (lambda (name)
  558. (org-cite-processor-cite-styles (org-cite--get-processor name)))
  559. (or processors
  560. (mapcar (pcase-lambda (`(,_ . (,name . ,_))) name)
  561. org-cite-export-processors))))
  562. (result nil))
  563. ;; Merge duplicate styles. Each style full name is guaranteed to
  564. ;; be unique, and associated to all shortcuts and all variants in
  565. ;; the initial collection.
  566. (pcase-dolist (`((,style . ,shortcuts) . ,variants) collection)
  567. (let ((entry (assoc style result)))
  568. (if (not entry)
  569. (push (list style shortcuts variants) result)
  570. (setf (nth 1 entry)
  571. (seq-uniq (append shortcuts (nth 1 entry))))
  572. (setf (nth 2 entry)
  573. (append variants (nth 2 entry))))))
  574. ;; Return value with the desired format.
  575. (nreverse
  576. (mapcar (pcase-lambda (`(,style ,shortcuts ,variants))
  577. (cons (cons style (nreverse shortcuts))
  578. ;; Merge variant shortcuts.
  579. (let ((result nil))
  580. (pcase-dolist (`(,variant . ,shortcuts) variants)
  581. (let ((entry (assoc variant result)))
  582. (if (not entry)
  583. (push (cons variant shortcuts) result)
  584. (setf (cdr entry)
  585. (seq-uniq (append shortcuts (cdr entry)))))))
  586. result)))
  587. result))))
  588. (defun org-cite-delete-citation (datum)
  589. "Delete citation or citation reference DATUM.
  590. When removing the last reference, also remove the whole citation."
  591. (pcase (org-element-type datum)
  592. ('citation
  593. (pcase-let* ((`(,begin . ,end) (org-cite-boundaries datum))
  594. (pos-before-blank
  595. (org-with-point-at begin
  596. (skip-chars-backward " \t")
  597. (point)))
  598. (pos-after-blank (org-element-property :end datum))
  599. (first-on-line?
  600. (= pos-before-blank (line-beginning-position)))
  601. (last-on-line?
  602. (= pos-after-blank (line-end-position))))
  603. (cond
  604. ;; The citation is alone on its line. Remove the whole line.
  605. ;; Do not leave it blank as it might break a surrounding
  606. ;; paragraph.
  607. ((and first-on-line? last-on-line?)
  608. (delete-region (line-beginning-position) (line-beginning-position 2)))
  609. ;; When the citation starts the line, preserve indentation.
  610. (first-on-line? (delete-region begin pos-after-blank))
  611. ;; When the citation ends the line, remove any trailing space.
  612. (last-on-line? (delete-region pos-before-blank (line-end-position)))
  613. ;; Otherwise, delete blanks before the citation.
  614. ;; Nevertheless, make sure there is at least one blank left,
  615. ;; so as to not splice unrelated surroundings.
  616. (t
  617. (delete-region pos-before-blank end)
  618. (when (= pos-after-blank end)
  619. (org-with-point-at pos-before-blank (insert " ")))))))
  620. ('citation-reference
  621. (let* ((citation (org-element-property :parent datum))
  622. (references (org-cite-get-references citation))
  623. (begin (org-element-property :begin datum))
  624. (end (org-element-property :end datum)))
  625. (cond
  626. ;; Single reference.
  627. ((= 1 (length references))
  628. (org-cite-delete-citation citation))
  629. ;; First reference, no prefix.
  630. ((and (= begin (org-element-property :contents-begin citation))
  631. (not (org-element-property :prefix citation)))
  632. (org-with-point-at (org-element-property :begin datum)
  633. (skip-chars-backward " \t")
  634. (delete-region (point) end)))
  635. ;; Last reference, no suffix.
  636. ((and (= end (org-element-property :contents-end citation))
  637. (not (org-element-property :suffix citation)))
  638. (delete-region (1- begin) (1- (cdr (org-cite-boundaries citation)))))
  639. ;; Somewhere in-between.
  640. (t
  641. (delete-region begin end)))))
  642. (other
  643. (error "Invalid object type: %S" other))))
  644. ;;; Tools only available during export
  645. (defun org-cite-citation-style (citation info)
  646. "Return citation style used for CITATION object.
  647. Style is a pair (NAME . VARIANT) where NAME and VARIANT are strings or nil.
  648. A nil NAME means the default style for the current processor should be used.
  649. INFO is a plist used as a communication channel."
  650. (let* ((separate
  651. (lambda (s)
  652. (cond
  653. ((null s) (cons nil nil))
  654. ((not (string-match "/" s)) (cons s nil))
  655. (t (cons (substring s nil (match-beginning 0))
  656. (org-string-nw-p (substring s (match-end 0))))))))
  657. (local (funcall separate (org-element-property :style citation)))
  658. (global
  659. (funcall separate (pcase (plist-get info :cite-export)
  660. (`(,_ ,_ ,style) style)
  661. (_ nil)))))
  662. (cond
  663. ((org-string-nw-p (car local))
  664. (cons (org-not-nil (car local)) (cdr local)))
  665. (t
  666. (cons (org-not-nil (car global))
  667. (or (cdr local) (cdr global)))))))
  668. (defun org-cite-bibliography-style (info)
  669. "Return expected bibliography style.
  670. INFO is a plist used as a communication channel."
  671. (pcase (plist-get info :cite-export)
  672. (`(,_ ,style ,_) style)
  673. (_ nil)))
  674. (defun org-cite-bibliography-properties (keyword)
  675. "Return properties associated to \"print_bibliography\" KEYWORD object.
  676. Return value is a property list."
  677. (org-cite--parse-as-plist (org-element-property :value keyword)))
  678. (defun org-cite-list-citations (info)
  679. "List citations in the exported document.
  680. Citations are ordered by appearance in the document, when following footnotes.
  681. INFO is the export communication channel, as a property list."
  682. (or (plist-get info :citations)
  683. (letrec ((cites nil)
  684. (tree (plist-get info :parse-tree))
  685. (definition-cache (make-hash-table :test #'equal))
  686. (definition-list nil)
  687. (find-definition
  688. ;; Find definition for standard reference LABEL. At
  689. ;; this point, it is impossible to rely on
  690. ;; `org-export-get-footnote-definition' because the
  691. ;; function caches results that could contain
  692. ;; un-processed citation objects. So we use
  693. ;; a simplified version of the function above.
  694. (lambda (label)
  695. (or (gethash label definition-cache)
  696. (org-element-map
  697. (or definition-list
  698. (setq definition-list
  699. (org-element-map
  700. tree
  701. 'footnote-definition
  702. #'identity info)))
  703. 'footnote-definition
  704. (lambda (d)
  705. (and (equal label (org-element-property :label d))
  706. (puthash label
  707. (or (org-element-contents d) "")
  708. definition-cache)))
  709. info t))))
  710. (search-cites
  711. (lambda (data)
  712. (org-element-map data '(citation footnote-reference)
  713. (lambda (datum)
  714. (pcase (org-element-type datum)
  715. ('citation (push datum cites))
  716. ;; Do not force entering inline definitions, since
  717. ;; `org-element-map' is going to enter it anyway.
  718. ((guard (eq 'inline (org-element-property :type datum))))
  719. ;; Walk footnote definition.
  720. (_
  721. (let ((label (org-element-property :label datum)))
  722. (funcall search-cites
  723. (funcall find-definition label)))))
  724. nil)
  725. info nil 'footnote-definition t))))
  726. (funcall search-cites tree)
  727. (let ((result (nreverse cites)))
  728. (plist-put info :citations result)
  729. result))))
  730. (defun org-cite-list-keys (info)
  731. "List citation keys in the exported document.
  732. Keys are ordered by first appearance in the document, when following footnotes.
  733. Duplicate keys are removed. INFO is the export communication channel, as a
  734. property list."
  735. (delete-dups
  736. (org-element-map (org-cite-list-citations info) 'citation-reference
  737. (lambda (r) (org-element-property :key r))
  738. info)))
  739. (defun org-cite-key-number (key info &optional predicate)
  740. "Return number associated to string KEY.
  741. INFO is the export communication channel, as a property list.
  742. Optional argument PREDICATE is called with two keys, and returns non-nil
  743. if the first reference should sort before the second. When nil, references
  744. are sorted in order cited."
  745. (let* ((keys (org-cite-list-keys info))
  746. (sorted-keys (if (functionp predicate)
  747. (sort keys predicate)
  748. keys))
  749. (position (seq-position sorted-keys key #'string-equal)))
  750. (and (integerp position)
  751. (1+ position))))
  752. (defun org-cite-inside-footnote-p (citation &optional strict)
  753. "Non-nil when CITATION object is contained within a footnote.
  754. When optional argument STRICT is non-nil, return t only if CITATION represents
  755. the sole contents of the footnote, e.g., after calling `org-cite-wrap-citation'.
  756. When non-nil, the return value if the footnote container."
  757. (let ((footnote
  758. (org-element-lineage citation
  759. '(footnote-definition footnote-reference))))
  760. (and footnote
  761. (or (not strict)
  762. (equal (org-element-contents (org-element-property :parent citation))
  763. (list citation)))
  764. ;; Return value.
  765. footnote)))
  766. (defun org-cite-wrap-citation (citation info)
  767. "Wrap an anonymous inline footnote around CITATION object in the parse tree.
  768. INFO is the export state, as a property list.
  769. White space before the citation, if any, are removed. The parse tree is
  770. modified by side-effect.
  771. Return newly created footnote object."
  772. (let ((footnote
  773. (list 'footnote-reference
  774. (list :label nil
  775. :type 'inline
  776. :contents-begin (org-element-property :begin citation)
  777. :contents-end (org-element-property :end citation)
  778. :post-blank (org-element-property :post-blank citation)))))
  779. ;; Remove any white space before citation.
  780. (org-cite--set-previous-post-blank citation 0 info)
  781. ;; Footnote swallows citation.
  782. (org-element-insert-before footnote citation)
  783. (org-element-adopt-elements footnote
  784. (org-element-extract-element citation))))
  785. (defun org-cite-adjust-note (citation info &optional rule punct)
  786. "Adjust note number location for CITATION object, and punctuation around it.
  787. INFO is the export state, as a property list.
  788. Optional argument RULE is the punctuation rule used, as a triplet. When nil,
  789. rule is determined according to `org-cite-note-rules', which see.
  790. Optional argument PUNCT is a list of punctuation marks to be considered.
  791. When nil, it defaults to `org-cite-punctuation-marks'.
  792. Parse tree is modified by side-effect.
  793. Note: when calling both `org-cite-adjust-note' and `org-cite-wrap-citation' on
  794. the same object, call `org-cite-adjust-note' first."
  795. (when org-cite-adjust-note-numbers
  796. (pcase-let* ((rule (or rule (org-cite--get-note-rule info)))
  797. (punct-re (regexp-opt (or punct org-cite-punctuation-marks)))
  798. ;; with Emacs <27.1. Argument of `regexp' form (PUNCT-RE this case)
  799. ;; must be a string literal.
  800. (previous-punct-re
  801. (rx-to-string `(seq (opt (group (regexp ,(rx (0+ (any blank ?\n))))
  802. (regexp ,punct-re)))
  803. (regexp ,(rx (opt (0+ (any blank ?\n)) (group ?\"))
  804. (opt (group (1+ (any blank ?\n))))
  805. string-end)))
  806. t))
  807. (next-punct-re
  808. (rx-to-string `(seq string-start
  809. (group (0+ (any blank ?\n)) (regexp ,punct-re)))
  810. t))
  811. (next (org-export-get-next-element citation info))
  812. (final-punct
  813. (and (stringp next)
  814. (string-match next-punct-re next)
  815. (match-string 1 next)))
  816. (previous
  817. ;; Find the closest terminal object. Consider
  818. ;; citation, subscript and superscript objects as
  819. ;; terminal.
  820. (org-last
  821. (org-element-map (org-export-get-previous-element citation info)
  822. '(citation code entity export-snippet footnote-reference
  823. line-break latex-fragment link plain-text
  824. radio-target statistics-cookie timestamp
  825. verbatim)
  826. #'identity info nil '(citation subscript superscript))))
  827. (`(,punct ,quote ,spacing)
  828. (and (stringp previous)
  829. (string-match previous-punct-re previous)
  830. (list (match-string 1 previous)
  831. (match-string 2 previous)
  832. (match-string 3 previous)))))
  833. ;; Bail you when there is no quote and either no punctuation, or
  834. ;; punctuation on both sides.
  835. (when (or quote (org-xor punct final-punct))
  836. ;; Phase 1: handle punctuation rule.
  837. (pcase rule
  838. ((guard (not quote)) nil)
  839. ;; Move punctuation inside.
  840. (`(,(or `inside (and `adaptive (guard (not spacing)))) . ,_)
  841. ;; This only makes sense if there is a quotation before the
  842. ;; citation that does not end with some punctuation.
  843. (when (and (not punct) final-punct)
  844. ;; Quote guarantees there is a string object before
  845. ;; citation. Likewise, any final punctuation guarantees
  846. ;; there is a string object following citation.
  847. (let ((new-prev
  848. (replace-regexp-in-string
  849. previous-punct-re
  850. (concat final-punct "\"") previous nil nil 2))
  851. (new-next
  852. (replace-regexp-in-string
  853. ;; Before Emacs-27.1 `literal' `rx' form with a variable
  854. ;; as an argument is not available.
  855. (rx-to-string `(seq string-start ,final-punct) t)
  856. "" next)))
  857. (org-element-set-element previous new-prev)
  858. (org-element-set-element next new-next)
  859. (setq previous new-prev)
  860. (setq next new-next)
  861. (setq punct final-punct)
  862. (setq final-punct nil))))
  863. ;; Move punctuation outside.
  864. (`(,(or `outside (and `adaptive (guard spacing))) . ,_)
  865. ;; This is only meaningful if there is some inner
  866. ;; punctuation and no final punctuation already.
  867. (when (and punct (not final-punct))
  868. ;; Inner punctuation guarantees there is text object
  869. ;; before the citation. However, there is no information
  870. ;; about the object following citation, if any.
  871. ;; Therefore, we handle all the possible cases (string,
  872. ;; other type, or none).
  873. (let ((new-prev
  874. (replace-regexp-in-string
  875. previous-punct-re "" previous nil nil 1))
  876. (new-next (if (stringp next) (concat punct next) punct)))
  877. (org-element-set-element previous new-prev)
  878. (cond
  879. ((stringp next)
  880. (org-element-set-element next new-next))
  881. (next
  882. (org-element-insert-before new-next next))
  883. (t
  884. (org-element-adopt-elements
  885. (org-element-property :parent citation)
  886. new-next)))
  887. (setq previous new-prev)
  888. (setq next new-next)
  889. (setq final-punct punct)
  890. (setq punct nil))))
  891. (_
  892. (error "Invalid punctuation rule: %S" rule))))
  893. ;; Phase 2: move citation to its appropriate location.
  894. ;;
  895. ;; First transform relative citation location into a definitive
  896. ;; location, according to the surrounding punctuation.
  897. (pcase rule
  898. (`(,punctuation same ,order)
  899. (setf rule
  900. (list punctuation
  901. (cond
  902. ;; When there is punctuation on both sides, the
  903. ;; citation is necessarily on the outside.
  904. ((and punct final-punct) 'outside)
  905. (punct 'inside)
  906. (final-punct 'outside)
  907. ;; No punctuation: bail out on next step.
  908. (t nil))
  909. order))))
  910. (pcase rule
  911. (`(,_ nil ,_) nil)
  912. (`(,_ inside after)
  913. ;; Citation has to be moved after punct, if there is
  914. ;; a quotation mark, or after final punctuation.
  915. (cond
  916. (quote
  917. (org-cite--insert-at-split previous citation 2 previous-punct-re))
  918. (final-punct
  919. (org-cite--move-punct-before final-punct citation next info))
  920. ;; There is only punct, and we're already after it.
  921. (t nil)))
  922. (`(,_ inside before)
  923. ;; Citation is already behind final-punct, so only consider
  924. ;; other locations.
  925. (when (or punct quote)
  926. (org-cite--insert-at-split previous citation 0 previous-punct-re)))
  927. (`(,_ outside after)
  928. ;; Citation is already after any punct or quote. It can only
  929. ;; move past final punctuation, if there is one.
  930. (when final-punct
  931. (org-cite--move-punct-before final-punct citation next info)))
  932. (`(,_ outside before)
  933. ;; The only non-trivial case is when citation follows punct
  934. ;; without a quote.
  935. (when (and punct (not quote))
  936. (org-cite--insert-at-split previous citation 0 previous-punct-re)))
  937. (_
  938. (error "Invalid punctuation rule: %S" rule))))))
  939. ;;; Tools generating or operating on parsed data
  940. (defun org-cite-parse-elements (s)
  941. "Parse string S as a list of Org elements.
  942. The return value is suitable as a replacement for a
  943. \"print_bibliography\" keyword. As a consequence, the function
  944. raises an error if S contains a headline."
  945. (with-temp-buffer
  946. (insert s)
  947. (pcase (org-element-contents (org-element-parse-buffer))
  948. ('nil nil)
  949. (`(,(and section (guard (eq 'section (org-element-type section)))))
  950. (org-element-contents section))
  951. (_
  952. (error "Headlines cannot replace a keyword")))))
  953. (defun org-cite-parse-objects (s &optional affix)
  954. "Parse string S as a secondary string.
  955. The return value is suitable as a replacement for a citation object.
  956. When optional argument AFFIX is non-nil, restrict the set of allowed object
  957. types to match the contents of a citation affix."
  958. (org-element-parse-secondary-string
  959. s (org-element-restriction (if affix 'citation-reference 'paragraph))))
  960. (defun org-cite-make-paragraph (&rest data)
  961. "Return a paragraph element containing DATA.
  962. DATA are strings, objects or secondary strings."
  963. (apply #'org-element-create 'paragraph nil (apply #'org-cite-concat data)))
  964. (defun org-cite-emphasize (type &rest data)
  965. "Apply emphasis TYPE on DATA.
  966. TYPE is a symbol among `bold', `italic', `strike-through' and `underline'.
  967. DATA are strings, objects or secondary strings. Return an object of type TYPE."
  968. (declare (indent 1))
  969. (unless (memq type '(bold italic strike-through underline))
  970. (error "Wrong emphasis type: %S" type))
  971. (apply #'org-element-create type nil (apply #'org-cite-concat data)))
  972. (defun org-cite-concat (&rest data)
  973. "Concatenate all the DATA arguments and make the result a secondary string.
  974. Each argument may be a string, an object, or a secondary string."
  975. (let ((results nil))
  976. (dolist (datum (reverse data))
  977. (pcase datum
  978. ('nil nil)
  979. ;; Element or object.
  980. ((pred org-element-type) (push datum results))
  981. ;; Secondary string.
  982. ((pred consp) (setq results (append datum results)))
  983. (_
  984. (signal
  985. 'wrong-type-argument
  986. (list (format "Argument is not a string or a secondary string: %S"
  987. datum))))))
  988. results))
  989. (defun org-cite-mapconcat (function data separator)
  990. "Apply FUNCTION to each element of DATA, and return a secondary string.
  991. In between each pair of results, stick SEPARATOR, which may be a string,
  992. an object, or a secondary string. FUNCTION must be a function of one argument,
  993. and must return either a string, an object, or a secondary string."
  994. (and data
  995. (let ((result (list (funcall function (car data)))))
  996. (dolist (datum (cdr data))
  997. (setq result
  998. (org-cite-concat result separator (funcall function datum))))
  999. result)))
  1000. ;;; Internal interface with fontification (activate capability)
  1001. (defun org-cite-fontify-default (cite)
  1002. "Fontify CITE with `org-cite' and `org-cite-key' faces.
  1003. CITE is a citation object. The function applies `org-cite' face
  1004. on the whole citation, and `org-cite-key' face on each key."
  1005. (let ((beg (org-element-property :begin cite))
  1006. (end (org-with-point-at (org-element-property :end cite)
  1007. (skip-chars-backward " \t")
  1008. (point))))
  1009. (add-text-properties beg end '(font-lock-multiline t))
  1010. (add-face-text-property beg end 'org-cite)
  1011. (dolist (reference (org-cite-get-references cite))
  1012. (let ((boundaries (org-cite-key-boundaries reference)))
  1013. (add-face-text-property (car boundaries) (cdr boundaries)
  1014. 'org-cite-key)))))
  1015. (defun org-cite-activate (limit)
  1016. "Activate citations from up to LIMIT buffer position.
  1017. Each citation encountered is activated using the appropriate function
  1018. from the processor set in `org-cite-activate-processor'."
  1019. (let* ((name org-cite-activate-processor)
  1020. (activate
  1021. (or (and name
  1022. (org-cite-processor-has-capability-p name 'activate)
  1023. (org-cite-processor-activate (org-cite--get-processor name)))
  1024. #'org-cite-fontify-default)))
  1025. (when (re-search-forward org-element-citation-prefix-re limit t)
  1026. (let ((cite (org-with-point-at (match-beginning 0)
  1027. (org-element-citation-parser))))
  1028. (when cite
  1029. (funcall activate cite)
  1030. ;; Move after cite object and make sure to return
  1031. ;; a non-nil value.
  1032. (goto-char (org-element-property :end cite)))))))
  1033. ;;; Internal interface with Org Export library (export capability)
  1034. (defun org-cite-store-bibliography (info)
  1035. "Store bibliography in the communication channel.
  1036. Bibliography is stored as a list of absolute file names in the `:bibliography'
  1037. property.
  1038. INFO is the communication channel, as a plist. It is modified by side-effect."
  1039. (plist-put info :bibliography (org-cite-list-bibliography-files)))
  1040. (defun org-cite-store-export-processor (info)
  1041. "Store export processor in the `:cite-export' property during export.
  1042. Export processor is stored as a triplet, or nil.
  1043. When non-nil, it is defined as (NAME BIBLIOGRAPHY-STYLE CITATION-STYLE) where
  1044. NAME is a symbol, whereas BIBLIOGRAPHY-STYLE and CITATION-STYLE are strings,
  1045. or nil.
  1046. INFO is the communication channel, as a plist. It is modified by side-effect."
  1047. (let* ((err
  1048. (lambda (s)
  1049. (user-error "Invalid cite export processor definition: %S" s)))
  1050. (processor
  1051. (pcase (plist-get info :cite-export)
  1052. ((or "" `nil) nil)
  1053. ;; Value is a string. It comes from a "cite_export"
  1054. ;; keyword. It may contain between 1 and 3 tokens, the
  1055. ;; first one being a symbol and the other (optional) two,
  1056. ;; strings.
  1057. ((and (pred stringp) s)
  1058. (with-temp-buffer
  1059. (save-excursion (insert s))
  1060. (let ((result (list (read (current-buffer)))))
  1061. (dotimes (_ 2)
  1062. (skip-chars-forward " \t")
  1063. (cond
  1064. ((eobp) (push nil result))
  1065. ((char-equal ?\" (char-after))
  1066. (condition-case _
  1067. (push (org-not-nil (read (current-buffer))) result)
  1068. (error (funcall err s))))
  1069. (t
  1070. (let ((origin (point)))
  1071. (skip-chars-forward "^ \t")
  1072. (push (org-not-nil (buffer-substring origin (point)))
  1073. result)))))
  1074. (unless (eobp) (funcall err s))
  1075. (nreverse result))))
  1076. ;; Value is an alist. It must come from
  1077. ;; `org-cite-export-processors' variable. Find the most
  1078. ;; appropriate processor according to current export
  1079. ;; back-end.
  1080. ((and (pred consp) alist)
  1081. (let* ((backend (plist-get info :back-end))
  1082. (candidates
  1083. ;; Limit candidates to processors associated to
  1084. ;; back-ends derived from or equal to the current
  1085. ;; one.
  1086. (sort (seq-filter
  1087. (pcase-lambda (`(,key . ,_))
  1088. (org-export-derived-backend-p backend key))
  1089. alist)
  1090. (lambda (a b)
  1091. (org-export-derived-backend-p (car a) (car b))))))
  1092. ;; Select the closest candidate, or fallback to t.
  1093. (pcase (or (car candidates) (assq t alist))
  1094. ('nil nil)
  1095. (`(,_ . ,p)
  1096. ;; Normalize value by turning it into a triplet.
  1097. (pcase p
  1098. (`(,(pred symbolp))
  1099. (append p (list nil nil)))
  1100. (`(,(pred symbolp) ,(pred string-or-null-p))
  1101. (append p (list nil)))
  1102. (`(,(pred symbolp)
  1103. ,(pred string-or-null-p)
  1104. ,(pred string-or-null-p))
  1105. p)
  1106. (_ (funcall err p))))
  1107. (other (funcall err (cdr other))))))
  1108. (other (funcall err other)))))
  1109. (pcase processor
  1110. ('nil nil)
  1111. (`(,name . ,_)
  1112. (cond
  1113. ((not (org-cite--get-processor name))
  1114. (user-error "Unknown processor %S" name))
  1115. ((not (org-cite-processor-has-capability-p name 'export))
  1116. (user-error "Processor %S is unable to handle citation export" name)))))
  1117. (plist-put info :cite-export processor)))
  1118. (defun org-cite-export-citation (citation _ info)
  1119. "Export CITATION object according to INFO property list.
  1120. This function delegates the export of the current citation to the
  1121. selected citation processor."
  1122. (pcase (plist-get info :cite-export)
  1123. ('nil nil)
  1124. (`(,p ,_ ,_)
  1125. (funcall (org-cite-processor-export-citation (org-cite--get-processor p))
  1126. citation
  1127. (org-cite-citation-style citation info)
  1128. (plist-get info :back-end)
  1129. info))
  1130. (other (error "Invalid `:cite-export' value: %S" other))))
  1131. (defun org-cite-export-bibliography (keyword _ info)
  1132. "Return bibliography associated to \"print_bibliography\" KEYWORD.
  1133. BACKEND is the export back-end, as a symbol. INFO is a plist
  1134. used as a communication channel."
  1135. (pcase (plist-get info :cite-export)
  1136. ('nil nil)
  1137. (`(,p ,_ ,_)
  1138. (let ((export-bibilography
  1139. (org-cite-processor-export-bibliography
  1140. (org-cite--get-processor p))))
  1141. (when export-bibilography
  1142. (funcall export-bibilography
  1143. (org-cite-list-keys info)
  1144. (plist-get info :bibliography)
  1145. (org-cite-bibliography-style info)
  1146. (org-cite-bibliography-properties keyword)
  1147. (plist-get info :back-end)
  1148. info))))
  1149. (other (error "Invalid `:cite-export' value: %S" other))))
  1150. (defun org-cite-process-citations (info)
  1151. "Replace all citations in the parse tree.
  1152. INFO is the communication channel, as a plist. Parse tree is modified
  1153. by side-effect."
  1154. (dolist (cite (org-cite-list-citations info))
  1155. (let ((replacement (org-cite-export-citation cite nil info))
  1156. (blanks (or (org-element-property :post-blank cite) 0)))
  1157. (if (null replacement)
  1158. ;; Before removing the citation, transfer its `:post-blank'
  1159. ;; property to the object before, if any.
  1160. (org-cite--set-previous-post-blank cite blanks info)
  1161. ;; Make sure there is a space between a quotation mark and
  1162. ;; a citation. This is particularly important when using
  1163. ;; `adaptive' note rule. See `org-cite-note-rules'.
  1164. (let ((previous (org-export-get-previous-element cite info)))
  1165. (when (and (org-string-nw-p previous)
  1166. (string-suffix-p "\"" previous))
  1167. (org-cite--set-previous-post-blank cite 1 info)))
  1168. (pcase replacement
  1169. ;; String.
  1170. ((pred stringp)
  1171. ;; Handle `:post-blank' before replacing value.
  1172. (let ((output (concat (org-trim replacement)
  1173. (make-string blanks ?\s))))
  1174. (org-element-insert-before (org-export-raw-string output) cite)))
  1175. ;; Single element.
  1176. (`(,(pred symbolp) . ,_)
  1177. (org-cite--set-post-blank replacement blanks)
  1178. (org-element-insert-before replacement cite))
  1179. ;; Secondary string: splice objects at cite's place.
  1180. ;; Transfer `:post-blank' to the last object.
  1181. ((pred consp)
  1182. (let ((last nil))
  1183. (dolist (datum replacement)
  1184. (setq last datum)
  1185. (org-element-insert-before datum cite))
  1186. (org-cite--set-post-blank last blanks)))
  1187. (_
  1188. (error "Invalid return value from citation export processor: %S"
  1189. replacement))))
  1190. (org-element-extract-element cite))))
  1191. (defun org-cite-process-bibliography (info)
  1192. "Replace all \"print_bibliography\" keywords in the parse tree.
  1193. INFO is the communication channel, as a plist. Parse tree is modified
  1194. by side effect."
  1195. (org-element-map (plist-get info :parse-tree) 'keyword
  1196. (lambda (keyword)
  1197. (when (equal "PRINT_BIBLIOGRAPHY" (org-element-property :key keyword))
  1198. (let ((replacement (org-cite-export-bibliography keyword nil info))
  1199. (blanks (or (org-element-property :post-blank keyword) 0)))
  1200. (pcase replacement
  1201. ;; Before removing the citation, transfer its
  1202. ;; `:post-blank' property to the element before, if any.
  1203. ('nil
  1204. (org-cite--set-previous-post-blank keyword blanks info)
  1205. (org-element-extract-element keyword))
  1206. ;; Handle `:post-blank' before replacing keyword with string.
  1207. ((pred stringp)
  1208. (let ((output (concat (org-element-normalize-string replacement)
  1209. (make-string blanks ?\n))))
  1210. (org-element-set-element keyword (org-export-raw-string output))))
  1211. ;; List of elements: splice contents before keyword and
  1212. ;; remove the latter. Transfer `:post-blank' to last
  1213. ;; element.
  1214. ((and `(,(pred listp) . ,_) contents)
  1215. (let ((last nil))
  1216. (dolist (datum contents)
  1217. (setq last datum)
  1218. (org-element-insert-before datum keyword))
  1219. (org-cite--set-post-blank last blanks)
  1220. (org-element-extract-element keyword)))
  1221. ;; Single element: replace the keyword.
  1222. (`(,(pred symbolp) . ,_)
  1223. (org-cite--set-post-blank replacement blanks)
  1224. (org-element-set-element keyword replacement))
  1225. (_
  1226. (error "Invalid return value from citation export processor: %S"
  1227. replacement))))))
  1228. info))
  1229. (defun org-cite-finalize-export (output info)
  1230. "Finalizer for export process.
  1231. OUTPUT is the full output of the export process. INFO is the communication
  1232. channel, as a property list."
  1233. (pcase (plist-get info :cite-export)
  1234. ('nil output)
  1235. (`(,p ,_ ,_)
  1236. (let ((finalizer
  1237. (org-cite-processor-export-finalizer (org-cite--get-processor p))))
  1238. (if (not finalizer)
  1239. output
  1240. (funcall finalizer
  1241. output
  1242. (org-cite-list-keys info)
  1243. (plist-get info :bibliography)
  1244. (org-cite-bibliography-style info)
  1245. (plist-get info :back-end)
  1246. info))))
  1247. (other (error "Invalid `:cite-export' value: %S" other))))
  1248. ;;; Internal interface with `org-open-at-point' (follow capability)
  1249. (defun org-cite-follow (datum arg)
  1250. "Follow citation or citation-reference DATUM.
  1251. Following is done according to the processor set in `org-cite-follow-processor'.
  1252. ARG is the prefix argument received when calling `org-open-at-point', or nil."
  1253. (let ((name org-cite-follow-processor))
  1254. (cond
  1255. ((null name)
  1256. (user-error "No processor set to follow citations"))
  1257. ((not (org-cite--get-processor name))
  1258. (user-error "Unknown processor %S" name))
  1259. ((not (org-cite-processor-has-capability-p name 'follow))
  1260. (user-error "Processor %S cannot follow citations" name))
  1261. (t
  1262. (let ((follow (org-cite-processor-follow (org-cite--get-processor name))))
  1263. (funcall follow datum arg))))))
  1264. ;;; Meta-command for citation insertion (insert capability)
  1265. (defun org-cite--allowed-p (context)
  1266. "Non-nil when a citation can be inserted at point.
  1267. CONTEXT is the element or object at point, as returned by `org-element-context'."
  1268. (let ((type (org-element-type context)))
  1269. (cond
  1270. ;; No citation in attributes, except in parsed ones.
  1271. ;;
  1272. ;; XXX: Inserting citation in a secondary value is not allowed
  1273. ;; yet. Is it useful?
  1274. ((let ((post (org-element-property :post-affiliated context)))
  1275. (and post (< (point) post)))
  1276. (let ((case-fold-search t))
  1277. (looking-back
  1278. (rx-to-string
  1279. `(seq line-start (0+ (any " \t"))
  1280. "#+"
  1281. (or ,@org-element-parsed-keywords)
  1282. ":"
  1283. (0+ nonl))
  1284. t)
  1285. (line-beginning-position))))
  1286. ;; Paragraphs and blank lines at top of document are fine.
  1287. ((memq type '(nil paragraph)))
  1288. ;; So are contents of verse blocks.
  1289. ((eq type 'verse-block)
  1290. (and (>= (point) (org-element-property :contents-begin context))
  1291. (< (point) (org-element-property :contents-end context))))
  1292. ;; In an headline or inlinetask, point must be either on the
  1293. ;; heading itself or on the blank lines below.
  1294. ((memq type '(headline inlinetask))
  1295. (or (not (org-at-heading-p))
  1296. (and (save-excursion
  1297. (beginning-of-line)
  1298. (and (let ((case-fold-search t))
  1299. (not (looking-at-p "\\*+ END[ \t]*$")))
  1300. (let ((case-fold-search nil))
  1301. (looking-at org-complex-heading-regexp))))
  1302. (match-beginning 4)
  1303. (>= (point) (match-beginning 4))
  1304. (or (not (match-beginning 5))
  1305. (< (point) (match-beginning 5))))))
  1306. ;; White spaces after an object or blank lines after an element
  1307. ;; are OK.
  1308. ((>= (point)
  1309. (save-excursion (goto-char (org-element-property :end context))
  1310. (skip-chars-backward " \r\t\n")
  1311. (if (eq (org-element-class context) 'object) (point)
  1312. (line-beginning-position 2)))))
  1313. ;; At the beginning of a footnote definition, right after the
  1314. ;; label, is OK.
  1315. ((eq type 'footnote-definition) (looking-at (rx space)))
  1316. ;; At the start of a list item is fine, as long as the bullet is
  1317. ;; unaffected.
  1318. ((eq type 'item)
  1319. (> (point) (+ (org-element-property :begin context)
  1320. (current-indentation)
  1321. (if (org-element-property :checkbox context)
  1322. 5 1))))
  1323. ;; Other elements are invalid.
  1324. ((eq (org-element-class context) 'element) nil)
  1325. ;; Just before object is fine.
  1326. ((= (point) (org-element-property :begin context)))
  1327. ;; Within recursive object too, but not in a link.
  1328. ((eq type 'link) nil)
  1329. ((eq type 'table-cell)
  1330. ;; :contents-begin is not reliable on empty cells, so special
  1331. ;; case it.
  1332. (<= (save-excursion (skip-chars-backward " \t") (point))
  1333. (org-element-property :contents-end context)))
  1334. ((let ((cbeg (org-element-property :contents-begin context))
  1335. (cend (org-element-property :contents-end context)))
  1336. (and cbeg (>= (point) cbeg) (<= (point) cend)))))))
  1337. (defun org-cite--insert-string-before (string reference)
  1338. "Insert STRING before citation REFERENCE object."
  1339. (org-with-point-at (org-element-property :begin reference)
  1340. (insert string ";")))
  1341. (defun org-cite--insert-string-after (string reference)
  1342. "Insert STRING after citation REFERENCE object."
  1343. (org-with-point-at (org-element-property :end reference)
  1344. ;; Make sure to move forward when we're inserting at point, so the
  1345. ;; insertion can happen multiple times.
  1346. (if (char-equal ?\; (char-before))
  1347. (insert-before-markers string ";")
  1348. (insert-before-markers ";" string))))
  1349. (defun org-cite--keys-to-citation (keys)
  1350. "Build a citation object from a list of citation KEYS.
  1351. Citation keys are strings without the leading \"@\"."
  1352. (apply #'org-element-create
  1353. 'citation
  1354. nil
  1355. (mapcar (lambda (k)
  1356. (org-element-create 'citation-reference (list :key k)))
  1357. keys)))
  1358. (defun org-cite-make-insert-processor (select-key select-style)
  1359. "Build a function appropriate as an insert processor.
  1360. SELECT-KEY is a function called with one argument. When it is nil, the function
  1361. should return a citation key as a string, or nil. Otherwise, the function
  1362. should return a list of such keys, or nil. The keys should not have any leading
  1363. \"@\" character.
  1364. SELECT-STYLE is a function called with one argument, the citation object being
  1365. edited or constructed so far. It should return a style string, or nil.
  1366. The return value is a function of two arguments: CONTEXT and ARG. CONTEXT is
  1367. either a citation reference, a citation object, or nil. ARG is a prefix
  1368. argument.
  1369. The generated function inserts or edit a citation at point. More specifically,
  1370. On a citation reference:
  1371. - on the prefix or right before the \"@\" character, insert a new reference
  1372. before the current one,
  1373. - on the suffix, insert it after the reference,
  1374. - otherwise, update the cite key, preserving both affixes.
  1375. When ARG is non-nil, remove the reference, possibly removing the whole
  1376. citation if it contains a single reference.
  1377. On a citation object:
  1378. - on the style part, offer to update it,
  1379. - on the global prefix, add a new reference before the first one,
  1380. - on the global suffix, add a new reference after the last one,
  1381. Elsewhere, insert a citation at point. When ARG is non-nil, offer to complete
  1382. style in addition to references."
  1383. (unless (and (functionp select-key) (functionp select-style))
  1384. (error "Wrong argument type(s)"))
  1385. (lambda (context arg)
  1386. (pcase (org-element-type context)
  1387. ;; When on a citation, check point is not on the blanks after it.
  1388. ;; Otherwise, consider we're after it.
  1389. ((and 'citation
  1390. (guard
  1391. (let ((boundaries (org-cite-boundaries context)))
  1392. (and (< (point) (cdr boundaries))
  1393. (> (point) (car boundaries))))))
  1394. ;; When ARG is non-nil, delete the whole citation. Otherwise,
  1395. ;; action depends on the point.
  1396. (if arg
  1397. (org-cite-delete-citation context)
  1398. (let* ((begin (org-element-property :begin context))
  1399. (style-end (1- (org-with-point-at begin (search-forward ":")))))
  1400. (if (>= style-end (point))
  1401. ;; On style part, edit the style.
  1402. (let ((style-start (+ 5 begin))
  1403. (style (funcall select-style)))
  1404. (unless style (user-error "Aborted"))
  1405. (org-with-point-at style-start
  1406. (delete-region style-start style-end)
  1407. (when (org-string-nw-p style) (insert "/" style))))
  1408. ;; On an affix, insert a new reference before or after
  1409. ;; point.
  1410. (let* ((references (org-cite-get-references context))
  1411. (key (concat "@" (funcall select-key nil))))
  1412. (if (< (point) (org-element-property :contents-begin context))
  1413. (org-cite--insert-string-before key (car references))
  1414. (org-cite--insert-string-after key (org-last references))))))))
  1415. ;; On a citation reference. If ARG is not nil, remove the
  1416. ;; reference. Otherwise, action depends on the point.
  1417. ((and 'citation-reference (guard arg)) (org-cite-delete-citation context))
  1418. ('citation-reference
  1419. (pcase-let* ((`(,start . ,end) (org-cite-key-boundaries context))
  1420. (key (concat "@"
  1421. (or (funcall select-key nil)
  1422. (user-error "Aborted")))))
  1423. ;; Right before the "@" character, do not replace the reference
  1424. ;; at point, but insert a new one before it. It makes adding
  1425. ;; a new reference at the beginning easier in the following
  1426. ;; case: [cite:@key].
  1427. (cond
  1428. ((>= start (point)) (org-cite--insert-string-before key context))
  1429. ((<= end (point)) (org-cite--insert-string-after key context))
  1430. (t
  1431. (org-with-point-at start
  1432. (delete-region start end)
  1433. (insert key))))))
  1434. (_
  1435. (let ((keys (funcall select-key t)))
  1436. (unless keys (user-error "Aborted"))
  1437. (insert
  1438. (format "[cite%s:%s]"
  1439. (if arg
  1440. (let ((style (funcall select-style
  1441. (org-cite--keys-to-citation keys))))
  1442. (if (org-string-nw-p style)
  1443. (concat "/" style)
  1444. ""))
  1445. "")
  1446. (mapconcat (lambda (k) (concat "@" k)) keys "; "))))))))
  1447. ;;;###autoload
  1448. (defun org-cite-insert (arg)
  1449. "Insert a citation at point.
  1450. Insertion is done according to the processor set in `org-cite-insert-processor'.
  1451. ARG is the prefix argument received when calling interactively the function."
  1452. (interactive "P")
  1453. (let ((name org-cite-insert-processor))
  1454. (cond
  1455. ((null name)
  1456. (user-error "No processor set to insert citations"))
  1457. ((not (org-cite--get-processor name))
  1458. (user-error "Unknown processor %S" name))
  1459. ((not (org-cite-processor-has-capability-p name 'insert))
  1460. (user-error "Processor %S cannot insert citations" name))
  1461. (t
  1462. (let ((context (org-element-context))
  1463. (insert (org-cite-processor-insert (org-cite--get-processor name))))
  1464. (cond
  1465. ((memq (org-element-type context) '(citation citation-reference))
  1466. (funcall insert context arg))
  1467. ((org-cite--allowed-p context)
  1468. (funcall insert nil arg))
  1469. (t
  1470. (user-error "Cannot insert a citation here"))))))))
  1471. (provide 'oc)
  1472. ;;; oc.el ends here