oc.el 72 KB

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