oc.el 68 KB

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