oc.el 70 KB

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