oc.el 66 KB

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