-
Notifications
You must be signed in to change notification settings - Fork 0
/
oc.el
1744 lines (1545 loc) · 73 KB
/
oc.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; oc.el --- Org Cite library -*- lexical-binding: t; -*-
;; Copyright (C) 2021-2025 Free Software Foundation, Inc.
;; Author: Nicolas Goaziou <[email protected]>
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This library provides tooling to handle citations in Org, e.g,
;; activate, follow, insert, and export them, respectively called
;; "activate", "follow", "insert" and "export" capabilities.
;; Libraries responsible for providing some, or all, of these
;; capabilities are called "citation processors".
;; Such processors are defined using `org-cite-register-processor'.
;; Using this function, it is possible, in addition to giving it a
;; name, to attach functions associated to capabilities. As such, a
;; processor handling citation export must set the `:export-citation'
;; property to an appropriate function. Likewise, "activate"
;; capability requires an appropriate `:activate' property, "insert"
;; requires `:insert' property and, unsurprisingly, "follow"
;; capability implies `:follow' property.
;; As a user, the first thing to do is setting a bibliography, either
;; globally with `org-cite-global-bibliography', or locally using one
;; or more "bibliography" keywords. Then one can select any
;; registered processor for each capability by providing a processor
;; name to the variables `org-cite-activate-processor' and
;; `org-cite-follow-processor'.
;; The "export" capability is slightly more involved as one need to
;; select the processor providing it, but may also provide a default
;; style for citations and bibliography. Also, the choice of an
;; export processor may depend of the current export backend. The
;; association between export backends and triplets of parameters can
;; be set in `org-cite-export-processors' variable, or in a document,
;; through the "cite_export" keyword.
;; Eventually, this library provides some tools, mainly targeted at
;; processor implementers. Most are export-specific and are located
;; in the "Tools only available during export" and "Tools generating
;; or operating on parsed data" sections.
;; The few others can be used directly from an Org buffer, or operate
;; on processors. See "Generic tools" section.
;;; Code:
(require 'org-macs)
(org-assert-version)
(require 'org-compat)
(require 'org-macs)
(require 'seq)
(declare-function org-at-heading-p "org" (&optional _))
(declare-function org-collect-keywords "org" (keywords &optional unique directory))
(declare-function org-element-adopt "org-element-ast" (parent &rest children))
(declare-function org-element-citation-parser "org-element" ())
(declare-function org-element-citation-reference-parser "org-element" ())
(declare-function org-element-class "org-element" (datum &optional parent))
(declare-function org-element-contents "org-element-ast" (node))
(declare-function org-element-create "org-element-ast" (type &optional props &rest children))
(declare-function org-element-extract "org-element-ast" (node))
(declare-function org-element-insert-before "org-element-ast" (node location))
(declare-function org-element-lineage "org-element-ast" (datum &optional types with-self))
(declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
(declare-function org-element-normalize-string "org-element" (s))
(declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only keep-deferred))
(declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
(declare-function org-element-context "org-element" (&optional element))
(declare-function org-element-property "org-element-ast" (property node))
(declare-function org-element-begin "org-element" (node))
(declare-function org-element-end "org-element" (node))
(declare-function org-element-post-affiliated "org-element" (node))
(declare-function org-element-post-blank "org-element" (node))
(declare-function org-element-contents-begin "org-element" (node))
(declare-function org-element-contents-end "org-element" (node))
(declare-function org-element-parent "org-element-ast" (node))
(declare-function org-element-put-property "org-element-ast" (node property value))
(declare-function org-element-restriction "org-element" (element))
(declare-function org-element-set "org-element-ast" (old new))
(declare-function org-element-type "org-element-ast" (node &optional anonymous))
(declare-function org-element-type-p "org-element-ast" (node types))
(declare-function org-export-derived-backend-p "org-export" (backend &rest backends))
(declare-function org-export-get-next-element "org-export" (blob info &optional n))
(declare-function org-export-get-previous-element "org-export" (blob info &optional n))
(declare-function org-export-raw-string "org-export" (s))
(defvar org-complex-heading-regexp)
(defvar org-element-all-objects)
(defvar org-element-citation-key-re)
(defvar org-element-citation-prefix-re)
(defvar org-element-parsed-keywords)
;;; Constants
;; Borrowed from "citeproc.el" library.
(defconst org-cite--default-region-alist
'(("af" . "za") ("ca" . "ad") ("cs" . "cz") ("cy" . "gb")
("da" . "dk") ("el" . "gr") ("et" . "ee") ("fa" . "ir")
("he" . "ir") ("ja" . "jp") ("km" . "kh") ("ko" . "kr")
("nb" . "no") ("nn" . "no") ("sl" . "si") ("sr" . "rs")
("sv" . "se") ("uk" . "ua") ("vi" . "vn") ("zh" . "cn"))
"Alist mapping those languages to their default region.
Only those languages are given for which the default region is not simply the
result of duplicating the language part.")
;;; Configuration variables
(defgroup org-cite nil
"Options concerning citations in Org mode."
:group 'org
:tag "Org Cite")
(defcustom org-cite-global-bibliography nil
"List of bibliography files available in all documents.
File names must be absolute."
:group 'org-cite
:package-version '(Org . "9.5")
:type '(choice (const :tag "No global bibliography" nil)
(repeat :tag "List of bibliography files"
(file :tag "Bibliography"))))
(defcustom org-cite-activate-processor 'basic
"Processor used for activating citations, as a symbol."
:group 'org-cite
:package-version '(Org . "9.5")
:type '(choice (const :tag "Default fontification" nil)
(symbol :tag "Citation processor")))
(defcustom org-cite-export-processors '((t basic))
"Processor used for exporting citations, as a triplet, or nil.
When nil, citations and bibliography are not exported.
When non-nil, the value is an association list between export backends and
citation export processors:
(BACKEND . PROCESSOR)
where BACKEND is the name of an export backend or t, and PROCESSOR is a
triplet following the pattern
(NAME BIBLIOGRAPHY-STYLE CITATION-STYLE)
There, NAME is the name of a registered citation processor providing export
functionality, as a symbol. BIBLIOGRAPHY-STYLE (respectively CITATION-STYLE)
is the desired default style to use when printing a bibliography (respectively
exporting a citation), as a string or nil. Both BIBLIOGRAPHY-STYLE and
CITATION-STYLE are optional. NAME is mandatory.
The export process selects the citation processor associated to the current
export backend, or the most specific backend the current one is derived from,
or, if all are inadequate, to the processor associated to t. For example, with
the following value
((beamer natbib)
(latex biblatex)
(t csl))
exporting with `beamer' or any backend derived from it will use `natbib',
whereas exporting with `latex' or any backend derived from it but different
from `beamer' will use `biblatex' processor. Any other backend, such as
`html', will use `csl' processor.
CITATION-STYLE is overridden by adding a style to any citation object. A nil
style lets the export processor choose the default output. Any style not
recognized by the export processor is equivalent to nil.
The citation triplet can also be set with the CITE_EXPORT keyword.
E.g.,
#+CITE_EXPORT: basic note numeric
or
#+CITE_EXPORT: basic
In that case, `basic' processor is used on every export, independently on the
backend."
:group 'org-cite
:package-version '(Org . "9.5")
:type '(choice (const :tag "No export" nil)
(alist :key-type symbol
:value-type
(list :tag "Citation processor"
(symbol :tag "Processor name")
(choice
(const :tag "Default bibliography style" nil)
(string :tag "Use specific bibliography style"))
(choice
(const :tag "Default citation style" nil)
(string :tag "Use specific citation style"))))))
(defcustom org-cite-follow-processor 'basic
"Processor used for following citations, as a symbol."
:group 'org-cite
:package-version '(Org . "9.5")
:type '(choice (const :tag "No following" nil)
(symbol :tag "Citation processor")))
(defcustom org-cite-insert-processor 'basic
"Processor used for inserting citations, as a symbol."
:group 'org-cite
:package-version '(Org . "9.5")
:type '(choice (const :tag "No insertion" nil)
(symbol :tag "Citation processor")))
(defcustom org-cite-adjust-note-numbers t
"When non-nil, allow process to modify location of note numbers.
When this variable is non-nil, it is possible to swap between author-date and
note style without modifying the document. To that effect, citations should
always be located as in an author-date style. Prior to turning the citation
into a footnote, the citation processor moves the citation (i.e., the future
note number), and the surrounding punctuation, according to rules defined in
`org-cite-note-rules'.
When nil, the note number is not moved."
:group 'org-cite
:package-version '(Org . "9.5")
:type '(choice (const :tag "Automatic note number location" t)
(const :tag "Place note numbers manually" nil))
:safe #'booleanp)
(defcustom org-cite-note-rules
'(("en-us" inside outside after)
("fr" adaptive same before))
"Alist between languages and typographic rules for citations in note style.
When `org-cite-adjust-note-numbers' is non-nil, and note style is requested,
citation processor is allowed to move the note marker according to some specific
rules, detailed here. More accurately, a rule is a list following the pattern
(LANGUAGE-TAG . RULE)
LANGUAGE-TAG is a down-cased string representing a language tag as defined in
RFC 4646. It may constituted of a language and a region separated with an
hyphen (e.g., \"en-us\"), or the language alone (e.g., \"fr\"). A language
without a region applies to all regions.
RULE is a triplet
(PUNCTUATION NUMBER ORDER)
PUNCTUATION is the desired location of the punctuation with regards to the
quotation, if any. It may be `inside', `outside', or `adaptive'. The latter
permits subtler control over the punctuation: when there is no space between
the quotation mark and the punctuation, it is equivalent to `inside'.
Otherwise, it means `outside', as illustrated in the following examples:
\"A quotation ending without punctuation\" [cite:@org21].
\"A quotation ending with a period\"[cite:@org21].
Notwithstanding the above, a space always appear before the citation when it
is to become anything else than a note.
NUMBER is the desired location of the note number with regards to the
quotation mark, if any. It may be `inside', `outside', or `same'. When set
to `same', the number appears on the same side as the punctuation, unless
there is punctuation on both sides or on none.
ORDER is the relative position of the citation with regards to the closest
punctuation. It may be `after' or `before'.
For example (adaptive same before) corresponds to French typography.
When the locale is unknown to this variable, the default rule is:
(adaptive outside after)
This roughly follows the Oxford Guide to Style recommendations."
:group 'org-cite
:package-version '(Org . "9.5")
:type
'(repeat
(list :tag "Typographic rule"
(string :tag "Language code")
(choice :tag "Location of punctuation"
(const :tag "Punctuation inside quotation" inside)
(const :tag "Punctuation outside quotation" outside)
(const :tag "Location depends on spacing" adaptive))
(choice :tag "Location of citation"
(const :tag "Citation inside quotation" inside)
(const :tag "Citation outside quotation" outside)
(const :tag "Citation next to punctuation" same))
(choice :tag "Order of citation and punctuation"
(const :tag "Citation first" before)
(const :tag "Citation last" after)))))
(defcustom org-cite-punctuation-marks '("." "," ";" ":" "!" "?")
"List of strings that can be moved around when placing note numbers.
When `org-cite-adjust-note-numbers' is non-nil, the citation processor is
allowed to shuffle punctuation marks specified in this list in order to
place note numbers according to rules defined in `org-cite-note-rules'."
:group 'org-cite
:package-version '(Org . "9.5")
:type '(repeat string))
;;; Citation processors
(cl-defstruct (org-cite-processor (:constructor org-cite--make-processor)
(:copier nil))
(name nil :read-only t)
(activate nil :read-only t)
(cite-styles nil :read-only t)
(export-bibliography nil :read-only t)
(export-citation nil :read-only t)
(export-finalizer nil :read-only t)
(follow nil :read-only t)
(insert nil :read-only t))
(defvar org-cite--processors nil
"List of registered citation processors.
See `org-cite-register-processor' for more information about
processors.")
(defun org-cite-register-processor (name &rest body)
"Mark citation processor NAME as available.
NAME is a symbol. BODY is a property list, where the following
optional keys can be set:
`:activate'
Function activating a citation. It is called with a single
argument: a citation object extracted from the current
buffer. It may add text properties to the buffer. If it is
not provided, `org-cite-fontify-default' is used.
`:export-bibliography'
Function rendering a bibliography. It is called with six
arguments: the list of citation keys used in the document, as
strings, a list of bibliography files, the style, as a string
or nil, the local properties, as a property list, the export
backend, as a symbol, and the communication channel, as a
property list.
It is called at each \"print_bibliography\" keyword in the
parse tree. It may return a string, a parsed element, a list
of parsed elements, or nil. When it returns nil, the keyword
is ignored. Otherwise, the value it returns replaces the
keyword in the export output.
`:export-citation' (mandatory for \"export\" capability)
Function rendering citations. It is called with four
arguments: a citation object, the style, as a pair, the
export backend, as a symbol, and the communication channel,
as a property list.
It is called on each citation object in the parse tree. It
may return a string, a parsed object, a secondary string, or
nil. When it returns nil, the citation is ignored.
Otherwise, the value it returns replaces the citation object
in the export output.
`:export-finalizer'
Function called at the end of export process. It must accept
six arguments: the output, as a string, a list of citation
keys used in the document, a list of bibliography files, the
expected bibliography style, as a string or nil, the export
backend, as a symbol, and the communication channel, as a
property list.
It must return a string, which will become the final output
from the export process, barring subsequent modifications
from export filters.
`:follow'
Function called to follow a citation. It accepts two
arguments, the citation or citation reference object at
point, and any prefix argument received during interactive
call of `org-open-at-point'.
`:insert'
Function called to insert a citation. It accepts two
arguments, the citation or citation reference object at point
or nil, and any prefix argument received.
`:cite-styles'
When the processor has export capability, the value can
specify what cite styles, variants, and their associated
shortcuts are supported. It can be useful information for
completion or linting.
The expected format is
((STYLE . SHORTCUTS) . VARIANTS))
where STYLE is a string, SHORTCUTS a list of strings or nil,
and VARIANTS is a list of pairs (VARIANT . SHORTCUTS),
VARIANT being a string and SHORTCUTS a list of strings or
nil.
The \"nil\" style denotes the processor fall-back style. It
should have a corresponding entry in the value.
The value can also be a function. It will be called without
any argument and should return a list structured as the above.
Return a non-nil value on a successful operation."
(declare (indent 1))
(unless (and name (symbolp name))
(error "Invalid processor name: %S" name))
(setq org-cite--processors
(cons (apply #'org-cite--make-processor :name name body)
(seq-remove (lambda (p) (eq name (org-cite-processor-name p)))
org-cite--processors))))
(defun org-cite-try-load-processor (name)
"Try loading citation processor NAME if unavailable.
NAME is a symbol. When the NAME processor is unregistered, try
loading \"oc-NAME\" library beforehand, then cross fingers."
(unless (org-cite-get-processor name)
(require (intern (format "oc-%s" name)) nil t)))
(defun org-cite-get-processor (name)
"Return citation processor named after symbol NAME.
Return nil if no such processor is found."
(seq-find (lambda (p) (eq name (org-cite-processor-name p)))
org-cite--processors))
(defun org-cite-unregister-processor (name)
"Unregister citation processor NAME.
NAME is a symbol. Raise an error if processor is not registered.
Return a non-nil value on a successful operation."
(unless (and name (symbolp name))
(error "Invalid processor name: %S" name))
(pcase (org-cite-get-processor name)
('nil (error "Processor %S not registered" name))
(processor
(setq org-cite--processors (delete processor org-cite--processors))))
t)
(defun org-cite-processor-has-capability-p (processor capability)
"Return non-nil if PROCESSOR is able to handle CAPABILITY.
PROCESSOR is the name of a cite processor, as a symbol. CAPABILITY is
`activate', `export', `follow', or `insert'."
(let ((p (org-cite-get-processor processor)))
(pcase capability
((guard (not p)) nil) ;undefined processor
('activate (functionp (org-cite-processor-activate p)))
('export (functionp (org-cite-processor-export-citation p)))
('follow (functionp (org-cite-processor-follow p)))
('insert (functionp (org-cite-processor-insert p)))
(other (error "Invalid capability: %S" other)))))
;;; Internal functions
(defun org-cite--set-post-blank (datum blanks)
"Set `:post-blank' property from element or object before DATUM to BLANKS.
DATUM is an element or object. BLANKS is an integer. DATUM is modified
by side-effect."
(if (not (org-element-type-p datum 'plain-text))
(org-element-put-property datum :post-blank blanks)
;; Remove any blank from string before DATUM so it is exported
;; with exactly BLANKS white spaces.
(org-element-set
datum
(replace-regexp-in-string
"[ \t\n]*\\'" (make-string blanks ?\s) datum))))
(defun org-cite--set-previous-post-blank (datum blanks info)
"Set `:post-blank' property from element or object before DATUM to BLANKS.
DATUM is an element or object. BLANKS is an integer. INFO is the export
state, as a property list. Previous element or object, if any, is modified by
side-effect."
(let ((previous (org-export-get-previous-element datum info)))
(when previous
(org-cite--set-post-blank previous blanks))))
(defun org-cite--insert-at-split (s citation n regexp)
"Split string S and insert CITATION object between the two parts.
S is split at beginning of match group N upon matching REGEXP against it.
This function assumes S precedes CITATION."
;; When extracting the citation, remove white spaces before it, but
;; preserve those after it.
(let ((post-blank (org-element-post-blank citation)))
(when (and post-blank (> post-blank 0))
(org-element-insert-before (make-string post-blank ?\s) citation)))
(org-element-insert-before
(org-element-put-property (org-element-extract citation)
:post-blank 0)
s)
(string-match regexp s)
(let* ((split (match-beginning n))
(first-part (substring s nil split))
;; Remove trailing white spaces as they are before the
;; citation.
(last-part
(replace-regexp-in-string (rx (1+ (any blank ?\n)) string-end)
""
(substring s split))))
(when (org-string-nw-p first-part)
(org-element-insert-before first-part citation))
(org-element-set s last-part)))
(defun org-cite--move-punct-before (punct citation s info)
"Move punctuation PUNCT before CITATION object.
String S contains PUNCT. INFO is the export state, as a property list.
The function assumes S follows CITATION. Parse tree is modified by side-effect."
(if (equal s punct)
(org-element-extract s) ;it would be empty anyway
(org-element-set s (substring s (length punct))))
;; Remove blanks before citation.
(org-cite--set-previous-post-blank citation 0 info)
(org-element-insert-before
;; Blanks between citation and punct are now before punct and
;; citation.
(concat (make-string (or (org-element-post-blank citation) 0) ?\s)
punct)
citation))
(defun org-cite--parse-as-plist (s)
"Parse string S as a property list.
Values are always strings. Return nil if S is nil."
(cond
((null s) nil)
((stringp s)
(with-temp-buffer
(save-excursion (insert s))
(skip-chars-forward " \t")
(let ((results nil)
(value-flag nil))
(while (not (eobp))
(pcase (char-after)
(?:
(push (read (current-buffer)) results)
(setq value-flag t))
((guard (not value-flag))
(skip-chars-forward "^ \t"))
(?\"
(let ((origin (point)))
(condition-case _
(progn
(read (current-buffer))
(push (buffer-substring (1+ origin) (1- (point))) results))
(end-of-file
(goto-char origin)
(skip-chars-forward "^ \t")
(push (buffer-substring origin (point)) results)))
(setq value-flag nil)))
(_
(let ((origin (point)))
(skip-chars-forward "^ \t")
(push (buffer-substring origin (point)) results)
(setq value-flag nil))))
(skip-chars-forward " \t"))
(nreverse results))))
(t (error "Invalid argument type: %S" s))))
(defun org-cite--get-note-rule (info)
"Return punctuation rule according to language used for export.
INFO is the export state, as a property list.
Rule is found according to the language used for export and
`org-cite-note-rules', which see.
If there is no rule matching current language, the rule defaults
to (adaptive outside after)."
(let* ((language-tags
;; Normalize language as a language-region tag, as described
;; in RFC 4646.
(pcase (split-string (plist-get info :language) "[-_]")
(`(,language)
(list language
(or (cdr (assoc language org-cite--default-region-alist))
language)))
(`(,language ,region)
(list language region))
(other
(error "Invalid language identifier: %S" other))))
(language-region (mapconcat #'downcase language-tags "-"))
(language (car language-tags)))
(or (cdr (assoc language-region org-cite-note-rules))
(cdr (assoc language org-cite-note-rules))
'(adaptive outside after))))
;;; Generic tools
(defun org-cite-list-bibliography-files ()
"List all bibliography files defined in the buffer."
(delete-dups
(append (mapcar (lambda (value)
(pcase value
(`(,f . ,d)
(setq f (org-strip-quotes f))
(if (or (file-name-absolute-p f)
(file-remote-p f)
(equal d default-directory))
;; Keep absolute paths, remote paths, and
;; local relative paths.
f
;; Adjust relative bibliography path for
;; #+SETUP files located in other directory.
;; Also, see `org-export--update-included-link'.
(file-relative-name
(expand-file-name f d) default-directory)))))
(pcase (org-collect-keywords
'("BIBLIOGRAPHY") nil '("BIBLIOGRAPHY"))
(`(("BIBLIOGRAPHY" . ,pairs)) pairs)))
org-cite-global-bibliography)))
(defun org-cite-get-references (citation &optional keys-only)
"Return citations references contained in CITATION object.
When optional argument KEYS-ONLY is non-nil, return the references' keys, as a
list of strings.
Assume CITATION object comes from either a full parse tree, e.g., during export,
or from the current buffer."
(let ((contents (org-element-contents citation)))
(cond
((null contents)
(org-with-point-at (org-element-contents-begin citation)
(narrow-to-region (point) (org-element-contents-end citation))
(let ((references nil))
(while (not (eobp))
(let ((reference (org-element-citation-reference-parser)))
(goto-char (org-element-end reference))
(push (if keys-only
(org-element-property :key reference)
reference)
references)))
(nreverse references))))
(keys-only (mapcar (lambda (r) (org-element-property :key r)) contents))
(t contents))))
(defun org-cite-boundaries (citation)
"Return the beginning and end strict position of CITATION.
Returns a (BEG . END) pair."
(let ((beg (org-element-begin citation))
(end (org-with-point-at (org-element-end citation)
(skip-chars-backward " \t")
(point))))
(cons beg end)))
(defun org-cite-key-boundaries (reference)
"Return citation REFERENCE's key boundaries as buffer positions.
The function returns a pair (START . END) where START and END denote positions
in the current buffer. Positions include leading \"@\" character."
(org-with-point-at (org-element-begin reference)
(let ((end (org-element-end reference)))
(re-search-forward org-element-citation-key-re end t)
(cons (match-beginning 0) (match-end 0)))))
(defun org-cite-main-affixes (citation)
"Return main affixes for CITATION object.
Some export backends only support a single pair of affixes per
citation, even if it contains multiple keys. This function
decides what affixes are the most appropriate.
Return a pair (PREFIX . SUFFIX) where PREFIX and SUFFIX are
parsed data."
(let ((source
;; When there are multiple references, use global affixes.
;; Otherwise, local affixes have priority.
(pcase (org-cite-get-references citation)
(`(,reference) reference)
(_ citation))))
(cons (org-element-property :prefix source)
(org-element-property :suffix source))))
(defun org-cite-supported-styles (&optional processors)
"List of supported citation styles and variants.
Supported styles are those handled by export processors from
`org-cite-export-processors', or in PROCESSORS, as a list of symbols,
when non-nil.
Return value is a list with the following items:
((STYLE . SHORTCUTS) . VARIANTS))
where STYLE is a string, SHORTCUTS a list of strings, and VARIANTS is a list of
pairs (VARIANT . SHORTCUTS), VARIANT being a string and SHORTCUTS a list of
strings."
(let ((collection
(seq-mapcat
(lambda (name)
(pcase (org-cite-processor-cite-styles
(org-cite-get-processor name))
((and (pred functionp) f) (funcall f))
(static-data static-data)))
(or processors
(mapcar (pcase-lambda (`(,_ . (,name . ,_))) name)
org-cite-export-processors))))
(result nil))
;; Merge duplicate styles. Each style full name is guaranteed to
;; be unique, and associated to all shortcuts and all variants in
;; the initial collection.
(pcase-dolist (`((,style . ,shortcuts) . ,variants) collection)
(let ((entry (assoc style result)))
(if (not entry)
(push (list style shortcuts variants) result)
(setf (nth 1 entry)
(seq-uniq (append shortcuts (nth 1 entry))))
(setf (nth 2 entry)
(append variants (nth 2 entry))))))
;; Return value with the desired format.
(nreverse
(mapcar (pcase-lambda (`(,style ,shortcuts ,variants))
(cons (cons style (nreverse shortcuts))
;; Merge variant shortcuts.
(let ((result nil))
(pcase-dolist (`(,variant . ,shortcuts) variants)
(let ((entry (assoc variant result)))
(if (not entry)
(push (cons variant shortcuts) result)
(setf (cdr entry)
(seq-uniq (append shortcuts (cdr entry)))))))
result)))
result))))
(defun org-cite-delete-citation (datum)
"Delete citation or citation reference DATUM.
When removing the last reference, also remove the whole citation."
(pcase (org-element-type datum)
('citation
(pcase-let* ((`(,begin . ,end) (org-cite-boundaries datum))
(pos-before-blank
(org-with-point-at begin
(skip-chars-backward " \t")
(point)))
(pos-after-blank (org-element-end datum))
(first-on-line?
(= pos-before-blank (line-beginning-position)))
(last-on-line?
(= pos-after-blank (line-end-position))))
(cond
;; The citation is alone on its line. Remove the whole line.
;; Do not leave it blank as it might break a surrounding
;; paragraph.
((and first-on-line? last-on-line?)
(delete-region (line-beginning-position) (line-beginning-position 2)))
;; When the citation starts the line, preserve indentation.
(first-on-line? (delete-region begin pos-after-blank))
;; When the citation ends the line, remove any trailing space.
(last-on-line? (delete-region pos-before-blank (line-end-position)))
;; Otherwise, delete blanks before the citation.
;; Nevertheless, make sure there is at least one blank left,
;; so as to not splice unrelated surroundings.
(t
(delete-region pos-before-blank end)
(when (= pos-after-blank end)
(org-with-point-at pos-before-blank (insert " ")))))))
('citation-reference
(let* ((citation (org-element-parent datum))
(references (org-cite-get-references citation))
(begin (org-element-begin datum))
(end (org-element-end datum)))
(cond
;; Single reference.
((= 1 (length references))
(org-cite-delete-citation citation))
;; First reference, no prefix.
((and (= begin (org-element-contents-begin citation))
(not (org-element-property :prefix citation)))
(org-with-point-at (org-element-begin datum)
(skip-chars-backward " \t")
(delete-region (point) end)))
;; Last reference, no suffix.
((and (= end (org-element-contents-end citation))
(not (org-element-property :suffix citation)))
(delete-region (1- begin) (1- (cdr (org-cite-boundaries citation)))))
;; Somewhere in-between.
(t
(delete-region begin end)))))
(other
(error "Invalid object type: %S" other))))
;;; Tools only available during export
(defun org-cite-citation-style (citation info)
"Return citation style used for CITATION object.
Style is a pair (NAME . VARIANT) where NAME and VARIANT are strings or nil.
A nil NAME means the default style for the current processor should be used.
INFO is a plist used as a communication channel."
(let* ((separate
(lambda (s)
(cond
((null s) (cons nil nil))
((not (string-match "/" s)) (cons s nil))
(t (cons (substring s nil (match-beginning 0))
(org-string-nw-p (substring s (match-end 0))))))))
(local (funcall separate (org-element-property :style citation)))
(global
(funcall separate (pcase (plist-get info :cite-export)
(`(,_ ,_ ,style) style)
(_ nil)))))
(cond
((org-string-nw-p (car local))
(cons (org-not-nil (car local)) (cdr local)))
(t
(cons (org-not-nil (car global))
(or (cdr local) (cdr global)))))))
(defun org-cite-read-processor-declaration (s)
"Read processor declaration from string S.
Return (NAME BIBLIOGRAPHY-STYLE CITATION-STYLE) triplet, when
NAME is the processor name, as a symbol, and both
BIBLIOGRAPHY-STYLE and CITATION-STYLE are strings or nil. Those
strings may contain spaces if they are enclosed within double
quotes.
String S is expected to contain between 1 and 3 tokens. The
function raises an error when it contains too few or too many
tokens. Spurious spaces are ignored."
(with-temp-buffer
(save-excursion (insert s))
(let ((result (list (read (current-buffer)))))
(dotimes (_ 2)
(skip-chars-forward " \t")
(cond
((eobp) (push nil result))
((char-equal ?\" (char-after))
(push (org-not-nil (read (current-buffer)))
result))
(t
(let ((origin (point)))
(skip-chars-forward "^ \t")
(push (org-not-nil (buffer-substring origin (point)))
result)))))
(skip-chars-forward " \t")
(unless (eobp)
(error "Trailing garbage following cite export processor declaration %S"
s))
(nreverse result))))
(defun org-cite-processor (info)
"Return expected citation/bibliography processor.
INFO is a plist used as a communication channel."
(car (plist-get info :cite-export)))
(defun org-cite-bibliography-style (info)
"Return expected bibliography style.
INFO is a plist used as a communication channel."
(pcase (plist-get info :cite-export)
(`(,_ ,style ,_) style)
(_ nil)))
(defun org-cite-bibliography-properties (keyword)
"Return properties associated to \"print_bibliography\" KEYWORD object.
Return value is a property list."
(org-cite--parse-as-plist (org-element-property :value keyword)))
(defun org-cite-list-citations (info)
"List citations in the exported document.
Citations are ordered by appearance in the document, when following footnotes.
INFO is the export communication channel, as a property list."
(or (plist-get info :citations)
(letrec ((cites nil)
(tree (plist-get info :parse-tree))
(definition-cache (make-hash-table :test #'equal))
(definition-list nil)
(find-definition
;; Find definition for standard reference LABEL. At
;; this point, it is impossible to rely on
;; `org-export-get-footnote-definition' because the
;; function caches results that could contain
;; un-processed citation objects. So we use
;; a simplified version of the function above.
(lambda (label)
(or (gethash label definition-cache)
(org-element-map
(or definition-list
(setq definition-list
(org-element-map
tree
'footnote-definition
#'identity info)))
'footnote-definition
(lambda (d)
(and (equal label (org-element-property :label d))
(puthash label
(or (org-element-contents d) "")
definition-cache)))
info t))))
(search-cites
(lambda (data)
(org-element-map data '(citation footnote-reference)
(lambda (datum)
(pcase (org-element-type datum)
('citation (push datum cites))
;; Do not force entering inline definitions, since
;; `org-element-map' is going to enter it anyway.
((guard (eq 'inline (org-element-property :type datum))))
;; Walk footnote definition.
(_
(let ((label (org-element-property :label datum)))
(funcall search-cites
(funcall find-definition label)))))
nil)
info nil 'footnote-definition t))))
(funcall search-cites tree)
(let ((result (nreverse cites)))
(plist-put info :citations result)
result))))
(defun org-cite-list-keys (info)
"List citation keys in the exported document.
Keys are ordered by first appearance in the document, when following footnotes.
Duplicate keys are removed. INFO is the export communication channel, as a
property list."
(delete-dups
(org-element-map (org-cite-list-citations info) 'citation-reference
(lambda (r) (org-element-property :key r))
info)))
(defun org-cite-key-number (key info &optional predicate)
"Return number associated to string KEY.
INFO is the export communication channel, as a property list.
Optional argument PREDICATE is called with two keys, and returns non-nil
if the first reference should sort before the second. When nil, references
are sorted in order cited."
(let* ((keys (org-cite-list-keys info))
(sorted-keys (if (functionp predicate)
(sort keys predicate)
keys))
(position (seq-position sorted-keys key #'string-equal)))
(and (integerp position)
(1+ position))))
(defun org-cite-inside-footnote-p (citation &optional strict)
"Non-nil when CITATION object is contained within a footnote.
When optional argument STRICT is non-nil, return t only if CITATION represents
the sole contents of the footnote, e.g., after calling `org-cite-wrap-citation'.
When non-nil, the return value if the footnote container."
(let ((footnote
(org-element-lineage
citation
'(footnote-definition footnote-reference))))
(and footnote
(or (not strict)
(equal (org-element-contents (org-element-parent citation))
(list citation)))
;; Return value.
footnote)))
(defun org-cite-wrap-citation (citation info)
"Wrap an anonymous inline footnote around CITATION object in the parse tree.
INFO is the export state, as a property list.
White space before the citation, if any, are removed. The parse tree is
modified by side-effect.
Return newly created footnote object."
(let ((footnote
(list 'footnote-reference
(list :label nil
:type 'inline
:contents-begin (org-element-begin citation)
:contents-end (org-element-end citation)
:post-blank (org-element-post-blank citation)))))
;; Remove any white space before citation.
(org-cite--set-previous-post-blank citation 0 info)
;; Footnote swallows citation.
(org-element-insert-before footnote citation)
(org-element-adopt footnote
(org-element-extract citation))))
(defun org-cite-adjust-note (citation info &optional rule punct)
"Adjust note number location for CITATION object, and punctuation around it.
INFO is the export state, as a property list.