oc.el 66 KB

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