oc.el 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  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. (match-beginning 4)
  1330. (>= (point) (match-beginning 4))
  1331. (or (not (match-beginning 5))
  1332. (< (point) (match-beginning 5))))))
  1333. ;; White spaces after an object or blank lines after an element
  1334. ;; are OK.
  1335. ((>= (point)
  1336. (save-excursion (goto-char (org-element-property :end context))
  1337. (skip-chars-backward " \r\t\n")
  1338. (if (eq (org-element-class context) 'object) (point)
  1339. (line-beginning-position 2)))))
  1340. ;; At the beginning of a footnote definition, right after the
  1341. ;; label, is OK.
  1342. ((eq type 'footnote-definition) (looking-at (rx space)))
  1343. ;; At the start of a list item is fine, as long as the bullet is
  1344. ;; unaffected.
  1345. ((eq type 'item)
  1346. (> (point) (+ (org-element-property :begin context)
  1347. (org-current-text-indentation)
  1348. (if (org-element-property :checkbox context)
  1349. 5 1))))
  1350. ;; Other elements are invalid.
  1351. ((eq (org-element-class context) 'element) nil)
  1352. ;; Just before object is fine.
  1353. ((= (point) (org-element-property :begin context)))
  1354. ;; Within recursive object too, but not in a link.
  1355. ((eq type 'link) nil)
  1356. ((eq type 'table-cell)
  1357. ;; :contents-begin is not reliable on empty cells, so special
  1358. ;; case it.
  1359. (<= (save-excursion (skip-chars-backward " \t") (point))
  1360. (org-element-property :contents-end context)))
  1361. ((let ((cbeg (org-element-property :contents-begin context))
  1362. (cend (org-element-property :contents-end context)))
  1363. (and cbeg (>= (point) cbeg) (<= (point) cend)))))))
  1364. (defun org-cite--insert-string-before (string reference)
  1365. "Insert STRING before citation REFERENCE object."
  1366. (org-with-point-at (org-element-property :begin reference)
  1367. (insert string ";")))
  1368. (defun org-cite--insert-string-after (string reference)
  1369. "Insert STRING after citation REFERENCE object."
  1370. (org-with-point-at (org-element-property :end reference)
  1371. ;; Make sure to move forward when we're inserting at point, so the
  1372. ;; insertion can happen multiple times.
  1373. (if (char-equal ?\; (char-before))
  1374. (insert-before-markers string ";")
  1375. (insert-before-markers ";" string))))
  1376. (defun org-cite--keys-to-citation (keys)
  1377. "Build a citation object from a list of citation KEYS.
  1378. Citation keys are strings without the leading \"@\"."
  1379. (apply #'org-element-create
  1380. 'citation
  1381. nil
  1382. (mapcar (lambda (k)
  1383. (org-element-create 'citation-reference (list :key k)))
  1384. keys)))
  1385. (defun org-cite-make-insert-processor (select-key select-style)
  1386. "Build a function appropriate as an insert processor.
  1387. SELECT-KEY is a function called with one argument. When it is
  1388. nil, the function should return a citation key as a string, or
  1389. nil. Otherwise, the function should return a list of such keys,
  1390. or nil. The keys should not have any leading \"@\" character.
  1391. SELECT-STYLE is a function called with one argument, the citation
  1392. object being edited or constructed so far. It should return
  1393. a style string, or nil.
  1394. The return value is a function of two arguments: CONTEXT and ARG.
  1395. CONTEXT is either a citation reference, a citation object, or
  1396. nil. ARG is a prefix argument.
  1397. The generated function inserts or edits a citation at point.
  1398. More specifically,
  1399. On a citation reference:
  1400. - on the prefix or right before the \"@\" character, insert
  1401. a new reference before the current one,
  1402. - on the suffix, insert it after the reference,
  1403. - otherwise, update the cite key, preserving both affixes.
  1404. When ARG is non-nil, remove the reference, possibly removing
  1405. the whole citation if it contains a single reference.
  1406. On a citation object:
  1407. - on the style part, offer to update it,
  1408. - on the global prefix, add a new reference before the first
  1409. one,
  1410. - on the global suffix, add a new reference after the last
  1411. one.
  1412. Elsewhere, insert a citation at point. When ARG is non-nil,
  1413. offer to complete style in addition to references."
  1414. (unless (and (functionp select-key) (functionp select-style))
  1415. (error "Wrong argument type(s)"))
  1416. (lambda (context arg)
  1417. (pcase (org-element-type context)
  1418. ;; When on a citation, check point is not on the blanks after it.
  1419. ;; Otherwise, consider we're after it.
  1420. ((and 'citation
  1421. (guard
  1422. (let ((boundaries (org-cite-boundaries context)))
  1423. (and (< (point) (cdr boundaries))
  1424. (> (point) (car boundaries))))))
  1425. ;; When ARG is non-nil, delete the whole citation. Otherwise,
  1426. ;; action depends on the point.
  1427. (if arg
  1428. (org-cite-delete-citation context)
  1429. (let* ((begin (org-element-property :begin context))
  1430. (style-end (1- (org-with-point-at begin (search-forward ":")))))
  1431. (if (>= style-end (point))
  1432. ;; On style part, edit the style.
  1433. (let ((style-start (+ 5 begin))
  1434. (style (funcall select-style)))
  1435. (unless style (user-error "Aborted"))
  1436. (org-with-point-at style-start
  1437. (delete-region style-start style-end)
  1438. (when (org-string-nw-p style) (insert "/" style))))
  1439. ;; On an affix, insert a new reference before or after
  1440. ;; point.
  1441. (let* ((references (org-cite-get-references context))
  1442. (key (concat "@" (funcall select-key nil))))
  1443. (if (< (point) (org-element-property :contents-begin context))
  1444. (org-cite--insert-string-before key (car references))
  1445. (org-cite--insert-string-after key (org-last references))))))))
  1446. ;; On a citation reference. If ARG is not nil, remove the
  1447. ;; reference. Otherwise, action depends on the point.
  1448. ((and 'citation-reference (guard arg)) (org-cite-delete-citation context))
  1449. ('citation-reference
  1450. (pcase-let* ((`(,start . ,end) (org-cite-key-boundaries context))
  1451. (key (concat "@"
  1452. (or (funcall select-key nil)
  1453. (user-error "Aborted")))))
  1454. ;; Right before the "@" character, do not replace the reference
  1455. ;; at point, but insert a new one before it. It makes adding
  1456. ;; a new reference at the beginning easier in the following
  1457. ;; case: [cite:@key].
  1458. (cond
  1459. ((>= start (point)) (org-cite--insert-string-before key context))
  1460. ((<= end (point)) (org-cite--insert-string-after key context))
  1461. (t
  1462. (org-with-point-at start
  1463. (delete-region start end)
  1464. (insert key))))))
  1465. (_
  1466. (let ((keys (funcall select-key t)))
  1467. (unless keys (user-error "Aborted"))
  1468. (insert
  1469. (format "[cite%s:%s]"
  1470. (if arg
  1471. (let ((style (funcall select-style
  1472. (org-cite--keys-to-citation keys))))
  1473. (if (org-string-nw-p style)
  1474. (concat "/" style)
  1475. ""))
  1476. "")
  1477. (mapconcat (lambda (k) (concat "@" k)) keys "; "))))))))
  1478. ;;;###autoload
  1479. (defun org-cite-insert (arg)
  1480. "Insert a citation at point.
  1481. Insertion is done according to the processor set in `org-cite-insert-processor'.
  1482. ARG is the prefix argument received when calling interactively the function."
  1483. (interactive "P")
  1484. (unless org-cite-insert-processor
  1485. (user-error "No processor set to insert citations"))
  1486. (org-cite-try-load-processor org-cite-insert-processor)
  1487. (let ((name org-cite-insert-processor))
  1488. (cond
  1489. ((not (org-cite-get-processor name))
  1490. (user-error "Unknown processor %S" name))
  1491. ((not (org-cite-processor-has-capability-p name 'insert))
  1492. (user-error "Processor %S cannot insert citations" name))
  1493. (t
  1494. (let ((context (org-element-context))
  1495. (insert (org-cite-processor-insert (org-cite-get-processor name))))
  1496. (cond
  1497. ((memq (org-element-type context) '(citation citation-reference))
  1498. (funcall insert context arg))
  1499. ((org-cite--allowed-p context)
  1500. (funcall insert nil arg))
  1501. (t
  1502. (user-error "Cannot insert a citation here"))))))))
  1503. (provide 'oc)
  1504. ;;; oc.el ends here