-
Notifications
You must be signed in to change notification settings - Fork 55
/
citar.el
1860 lines (1585 loc) · 74.8 KB
/
citar.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
;;; citar.el --- Citation-related commands for org, latex, markdown -*- lexical-binding: t; -*-
;; Copyright (C) 2021-2023 Bruce D'Arcus
;; Author: Bruce D'Arcus <https://github.com/bdarcus>
;; Maintainer: Bruce D'Arcus <https://github.com/bdarcus>
;; Created: February 27, 2021
;; SPDX-License-Identifier: GPL-3.0-or-later
;; Version: 1.4.0
;; Homepage: https://github.com/emacs-citar/citar
;; Package-Requires: ((emacs "27.1") (parsebib "4.2") (org "9.5") (citeproc "0.9"))
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;; A completing-read front-end to browse, filter and act on BibTeX, BibLaTeX,
;; and CSL JSON bibliographic data, including LaTeX, markdown, and org-cite
;; citation editing support.
;;
;;; Code:
(eval-when-compile
(require 'cl-lib)
(require 'subr-x))
(require 'seq)
(require 'map)
(require 'browse-url)
(require 'citar-cache)
(require 'citar-format)
(require 'citar-file)
;;; Declare variables and functions for byte compiler
(defvar embark-default-action-overrides)
(declare-function citar-org-format-note-default "citar-org")
;;; Variables
(defvar-local citar--entries nil
"Override currently active citar entries.
When non-nil, should be a hash table mapping citation keys to
entries, as returned by `citar-get-entries'. Then all citar
functions will use that hash table as the source of bibliography
data instead of accessing the cache.
This variable should only be let-bound locally for the duration
of individual functions or operations. This is useful when using
multiple Citar functions in quick succession, to guarantee that
all potential cache accesses and updates are performed up-front.
In such cases, use a pattern like this:
(let ((citar--entries (citar-get-entries)))
...)
Note that this variable is buffer-local, since Citar has a
different list of bibliographies (and hence entries) for each
buffer.")
;;;; Faces
(defgroup citar nil
"Citations and bibliography management."
:group 'editing)
(defface citar
'((t :inherit font-lock-doc-face))
"Default Face for `citar' candidates."
:group 'citar)
(defface citar-highlight
'((t))
"Face used to highlight content in `citar' candidates."
:group 'citar)
(defface citar-selection
'((t :inherit highlight :slant italic))
"Face used for the currently selected candidates."
:group 'citar)
;;;; Bibliography, file, and note paths
(defcustom citar-bibliography nil
"A list of bibliography files."
:group 'citar
:type '(repeat file))
(defcustom citar-library-paths nil
"A list of files paths for related PDFs, etc."
:group 'citar
:type '(repeat directory))
(defcustom citar-library-paths-recursive nil
"Whether library paths should be searched recursively."
:group 'citar
:type 'boolean)
(defcustom citar-library-file-extensions nil
"List of file extensions to filter for related files.
These are the extensions the `citar-file-open-function'
will open, via `citar-file-open'.
When nil, the function will not filter the list of files."
:group 'citar
:type '(repeat string))
(defcustom citar-notes-paths nil
"A list of file paths for bibliographic notes."
:group 'citar
:type '(repeat directory))
(defcustom citar-crossref-variable "crossref"
"The bibliography field to look for cross-referenced entries.
When non-nil, find associated files and notes not only in the
original entry, but also in entries specified in the field named
by this variable."
:group 'citar
:type '(choice (const "crossref")
(string :tag "Field name")
(const :tag "Ignore cross-references" nil)))
(defcustom citar-additional-fields nil
"A list of fields to add to parsed data.
By default, citar filters parsed data based on the fields
specified in `citar-templates', `citar-file-variable'
`citar-crossref-variable', and `citar-link-fields'. This
specifies additional fields to include."
:group 'citar
:type '(repeat string))
;;;; Displaying completions and formatting
(defcustom citar-templates
'((main . "${author editor:30%sn} ${date year issued:4} ${title:48}")
(suffix . " ${=key= id:15} ${=type=:12} ${tags keywords keywords:*}")
(preview . "${author editor:%etal} (${year issued date}) ${title}, \
${journal journaltitle publisher container-title collection-title}.\n")
(note . "Notes on ${author editor:%etal}, ${title}"))
"Configures formatting for the bibliographic entry.
The main and suffix templates are for candidate display, and note
for the title field for new notes."
:group 'citar
:type '(alist :key-type symbol
:value-type string
:options (main suffix preview note)))
(defcustom citar-ellipsis nil
"Ellipsis string to mark ending of truncated display fields.
If t, use the value of `truncate-string-ellipsis'. If nil, no
ellipsis will be used. Otherwise, this should be a non-empty
string specifying the ellipsis."
:group 'citar
:type '(choice (const :tag "Use `truncate-string-ellipsis'" t)
(const :tag "No ellipsis" nil)
(const "…")
(const "...")
(string :tag "Ellipsis string")))
(defcustom citar-open-entry-function #'citar-open-entry-in-file
"The function to run for `citar-open-entry'.
This function must accept one argument; the citekey."
:group 'citar
:type '(choice
(function-item
:tag "Open in BibTeX/BibLaTeX/CSL JSON file"
citar-open-entry-in-file)
(function-item
:tag "Open in Zotero/Better BibTeX"
citar-open-entry-in-zotero)
(function :tag "Other")))
(defcustom citar-format-reference-function
#'citar-format-reference
"Function used to render formatted references.
This function is called by `citar-insert-reference' and
`citar-copy-reference'. The default value,
`citar-format-reference', formats references using the `preview'
template set in `citar-template'. To use `citeproc-el' to format
references according to CSL styles, set the value to
`citar-citeproc-format-reference'. Alternatively, set to a custom
function that takes a list of CITEKEYS and returns formatted
references as a string."
:group 'citar
:type '(choice (function-item :tag "Use 'citar-template'" citar-format-reference)
(function-item :tag "Use 'citeproc-el'" citar-citeproc-format-reference)
(function :tag "Other")))
(defcustom citar-display-transform-functions
;; TODO change this name, as it might be confusing?
`((sn . (citar--shorten-names))
(etal . (citar--shorten-names 3 "&")))
"Configure transformation of field display values from raw values.
When the car symbol is associated with a field, run the cdr function
and optional arguments on the string value."
:group 'citar
:type '(alist :key-type symbol
;; REVIEW is this OK for now?
:value-type list))
;; Indicator defstruct
;;;###autoload
(cl-defstruct
(citar-indicator (:constructor citar-indicator-create)
(:copier nil))
"A citar indicator specification."
(tag
nil
:documentation
"The string to include as hidden candidate text, and to then determine whether a
candidate predicate function will return non-nil.")
(symbol
nil
:type string
:documentation
"The symbol string to use in the UI when predicate function returns non-nil.")
(padding
" "
:type string
:documentation
"String to add to the right side of the indicator, for proper padding and such.")
(emptysymbol
;; REVIEW we may not need this, so perhaps remove?
" "
:documentation
"The symbol to use in the UI when predicate function returns nil. Can be useful
in some cases when using icons.")
(function
nil
:type function
:documentation
"A predicate function that takes a single CITEKEY argument.")
(compiledfunction
nil
:type compiled-function
:documentation
"A compiled version of `function' used during processing."))
;; Indicator specs
(defvar citar-indicator-files
(citar-indicator-create
:symbol "F"
:function #'citar-has-files
:tag "has:files"))
(defvar citar-indicator-links
(citar-indicator-create
:symbol "L"
:function #'citar-has-links
:tag "has:links"))
(defvar citar-indicator-notes
(citar-indicator-create
:symbol "N"
:function #'citar-has-notes
:tag "has:notes"))
(defvar citar-indicator-cited
(citar-indicator-create
:symbol "C"
:function #'citar-is-cited
:tag "is:cited"))
;; Indicator config
(defvar citar-indicators
(list citar-indicator-links
citar-indicator-files
citar-indicator-notes
citar-indicator-cited))
(defcustom citar-symbols
`((file . ("F" . " "))
(note . ("N" . " "))
(link . ("L" . " ")))
;; DEPRECATED
"Configuration alist specifying which symbol or icon to pick for a bib entry.
This leaves room for configurations where the absense of an item
may be indicated with the same icon but a different face.
To avoid alignment issues make sure that both the car and cdr of a symbol have
the same width."
:group 'citar
:type '(alist :key-type symbol
:value-type (cons (string :tag "Present")
(string :tag "Absent"))
:options (file note link)))
(defcustom citar-symbol-separator " "
"The padding between prefix symbols."
;; DEPRECATED
:group 'citar
:type 'string)
(make-obsolete 'citar-symbols nil "1.4")
(make-obsolete 'citar-symbol-separator nil "1.4")
;;;; Citar actions and other miscellany
(defcustom citar-default-action #'citar-open
"The default action for the `citar-at-point' command.
Should be a function that takes one argument, a list of
CITEKEYS."
:group 'citar
:type 'function)
(defcustom citar-at-point-fallback 'prompt
"Fallback action for `citar-at-point'.
The action is used when no citation key is found at point.
`prompt' means choosing entries via `citar-select-keys'
and nil means no action."
:group 'citar
:type '(radio (const :tag "Prompt" prompt)
(const :tag "Ignore" nil)))
(defcustom citar-open-prompt (list #'citar-open #'citar-attach-files #'citar-open-note)
"Always prompt to open files, notes, or links.
If nil, when chosen keys have a single resource, it will be
selected without prompting. When t, `citar-open',
`citar-open-files', `citar-attach-files', `citar-open-links',
`citar-open-notes', and `citar-open-note' will always prompt to
select a resource.
Otherwise, the value should be a list of command names that will
always prompt to select."
:group 'citar
:type '(choice (const :tag "Always prompt" t)
(const :tag "Prompt only for multiple resources" nil)
(set :tag "Commands that prompt for multiple resources"
(function-item citar-open)
(function-item citar-open-files)
(function-item citar-attach-files)
(function-item citar-open-links)
(function-item citar-open-notes)
(function-item citar-open-note))))
;;;; File, note, and URL handling
(defcustom citar-open-resources '(:files :links :notes :create-notes)
"Types of resources that `citar-open' offers to open."
:group 'citar
:type '(set (const :tag "Library files" :files)
(const :tag "Links" :links)
(const :tag "Notes" :notes)
(const :tag "Create notes" :create-notes)))
(defcustom citar-open-always-create-notes nil
"Offer to create notes even for keys that already have notes.
If nil, `citar-open' and `citar-open-notes' will only offer to
create new notes for keys that have no existing notes. When t,
offer to create new notes for all chosen keys.
Otherwise, the value should be a list of command names that will
offer to create new notes unconditionally."
:group 'citar
:type '(choice (const :tag "Always offer to create notes" t)
(const :tag "Create notes only if none exist" nil)
(set :tag "Create notes for commands"
(function-item citar-open)
(function-item citar-open-notes))))
(defcustom citar-file-sources
(list (list :items #'citar-file--get-from-file-field
:hasitems #'citar-file--has-file-field)
(list :items #'citar-file--get-library-files
:hasitems #'citar-file--has-library-files))
"List of backends used to get library files for bibliography references.
Should be a list of plists, where each plist has the following properties:
:items Function that takes a list of citation keys and returns
a hash table mapping each of those keys to a list of files.
:hasitems Function that takes a citation key and returns
non-nil if it has associated files."
:group 'citar
:type '(repeat (plist :value-type function :options (:items :hasitems))))
(defcustom citar-add-file-sources
'((?b "buffer" "Current buffer" citar--add-file-from-buffer)
(?f "file" "Existing file" citar--add-file-from-file)
(?u "url" "Download from URL" citar--add-file-from-url))
"List of sources from which library files can be added.
The command `citar-add-file-to-library' prompts for the source of
the file to add, with the options being the elements of this
list. Each source must be a list containing:
- The unique shortcut character the user types to select the
source.
- Short name for the source, displayed in the prompt.
- Optional longer description, displayed if the user requests
help.
- Function that provides the file to add, described next.
The function is called with a bibliography key and should return
a plist containing the following keys:
:extension The extension of the source file if known, or nil.
:write-file A function taking arguments DESTFILE and
OK-IF-ALREADY-EXISTS. When called, it should write the source
file into DESTFILE. If DESTFILE already exists, it should act
according to OK-IF-ALREADY-EXISTS, emulating `copy-file'.
The plist returned by this function is passed to
`citar-add-file-function', which see."
:group 'citar
:type '(repeat :tag "Sources for `citar-add-file-to-library'"
(group (character :tag "Shortcut")
(string :tag "Name")
(string :tag "Description")
(function :tag "Source function"))))
(defcustom citar-add-file-function #'citar-save-file-to-library
"Function run by `citar-add-file-to-library' to add a file.
This function must accept two arguments: the CITEKEY of a
bibliography item; and the SOURCE-PLIST documented in
`citar-add-file-sources'."
:group 'citar
:type '(radio
(function-item
:doc "Save the file to `citar-library-paths'."
citar-save-file-to-library)
(function :tag "Other")))
(defcustom citar-notes-sources
`((citar-file .
,(list :name "Notes"
:category 'file
:items #'citar-file--get-notes
:hasitems #'citar-file--has-notes
:open #'find-file
:create #'citar-file--create-note
:transform #'file-name-nondirectory)))
"The alist of notes backends available for configuration.
The format of the cons should be (NAME . PLIST), where the
plist has the following properties:
:name the group display name
:category the completion category
:hasitems a function that takes a CITEKEY and returns non-nil
if it has associated notes
:open function that, when given a note ID, opens the note
:create function that, when given a note ID, creates new note if not present
:items function to return completion candidate strings for list of CITEKEYS
:annotate annotation function that returns a string for a note ID (optional)
:transform transformation function (optional)"
:group 'citar
:type '(alist :key-type symbol :value-type plist))
(defcustom citar-notes-source 'citar-file
"The notes backend."
:group 'citar
:type 'symbol)
;; TODO should this be a major mode function?
(defcustom citar-note-format-function #'citar-org-format-note-default
"Function used by `citar-file' note source to format new notes."
:group 'citar
:type 'function)
(defcustom citar-link-fields '((doi . "https://doi.org/%s")
(pmid . "https://www.ncbi.nlm.nih.gov/pubmed/%s")
(pmcid . "https://www.ncbi.nlm.nih.gov/pmc/articles/%s")
(url . "%s"))
"Bibliography fields to parse into links.
Association list whose keys are symbols naming bibliography
fields and values are URL strings. In each URL, \"%s\" is
replaced by the contents of the corresponding field."
:group 'citar
:type '(alist :key-type symbol :value-type string))
;;;; Major mode functions
;; TODO Move this to `citar-org', since it's only used there?
;; Otherwise it seems to overlap with `citar-default-action'
(defcustom citar-at-point-function #'citar-dwim
"The function to run for `citar-at-point'."
:group 'citar
:type 'function)
(defcustom citar-major-mode-functions
'(((org-mode) .
((local-bib-files . citar-org-local-bib-files)
(insert-citation . citar-org-insert-citation)
(insert-edit . citar-org-insert-edit)
(key-at-point . citar-org-key-at-point)
(citation-at-point . citar-org-citation-at-point)
(list-keys . citar-org-list-keys)))
((latex-mode) .
((local-bib-files . citar-latex-local-bib-files)
(insert-citation . citar-latex-insert-citation)
(insert-edit . citar-latex-insert-edit)
(key-at-point . citar-latex-key-at-point)
(citation-at-point . citar-latex-citation-at-point)
(list-keys . citar-latex-list-keys)))
((markdown-mode) .
((insert-keys . citar-markdown-insert-keys)
(insert-citation . citar-markdown-insert-citation)
(insert-edit . citar-markdown-insert-edit)
(key-at-point . citar-markdown-key-at-point)
(citation-at-point . citar-markdown-citation-at-point)
(list-keys . citar-markdown-list-keys)))
(t .
((insert-keys . citar--insert-keys-comma-space-separated))))
"The variable determining the major mode specific functionality.
It is alist with keys being a list of major modes.
The value is an alist with values being functions to be used for
these modes while the keys are symbols used to lookup them up.
The keys are:
local-bib-files: the corresponding functions should return the list of
local bibliography files.
insert-keys: the corresponding function should insert the list of keys given
to as the argument at point in the buffer.
insert-citation: the corresponding function should insert a
complete citation from a list of keys at point. If the point is
in a citation, new keys should be added to the citation.
insert-edit: the corresponding function should accept an optional
prefix argument and interactively edit the citation or key at
point.
key-at-point: the corresponding function should return the
citation key at point or nil if there is none. The return value
should be (KEY . BOUNDS), where KEY is a string and BOUNDS is a
pair of buffer positions indicating the start and end of the key.
citation-at-point: the corresponding function should return the
keys of the citation at point, or nil if there is none. The
return value should be (KEYS . BOUNDS), where KEYS is a list of
strings and BOUNDS is pair of buffer positions indicating the
start and end of the citation.
list-keys: the corresponding function should return the keys
of all citations in the current buffer."
:group 'citar
:type 'alist)
;;;; History, including future history list.
(defvar citar-history nil
"Search history for `citar'.")
(defcustom citar-presets nil
"List of predefined searches."
:group 'citar
:type '(repeat string))
(defcustom citar-select-multiple t
"Use `completing-read-multiple' for selecting citation keys.
When nil, all citar commands will use `completing-read'."
:type 'boolean
:group 'citar)
;;;; Keymaps
(defvar citar-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "a") #'citar-add-file-to-library)
(define-key map (kbd "c") #'citar-insert-citation)
(define-key map (kbd "k") #'citar-insert-keys)
(define-key map (kbd "r") #'citar-copy-reference)
(define-key map (kbd "R") #'citar-insert-reference)
(define-key map (kbd "b") #'citar-insert-bibtex)
(define-key map (kbd "o") #'citar-open)
(define-key map (kbd "e") #'citar-open-entry)
(define-key map (kbd "l") #'citar-open-links)
(define-key map (kbd "n") #'citar-open-notes)
(define-key map (kbd "f") #'citar-open-files)
(define-key map (kbd "RET") #'citar-run-default-action)
map)
"Keymap for Embark minibuffer actions.")
(defvar citar-citation-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "i") #'citar-insert-edit)
(define-key map (kbd "o") #'citar-open)
(define-key map (kbd "e") #'citar-open-entry)
(define-key map (kbd "l") #'citar-open-links)
(define-key map (kbd "n") #'citar-open-notes)
(define-key map (kbd "f") #'citar-open-files)
(define-key map (kbd "r") #'citar-copy-reference)
(define-key map (kbd "RET") #'citar-run-default-action)
map)
"Keymap for Embark citation-key actions.")
;;; Bibliography cache
(defun citar--bibliography-files (&rest buffers)
"Bibliography file names for BUFFERS.
The elements of BUFFERS are either buffers or the symbol global.
Returns the absolute file names of the bibliographies in all
these contexts.
When BUFFERS is nil, return local bibliographies for the current
buffer and global bibliographies."
(citar-file--normalize-paths
(mapcan (lambda (buffer)
(if (eq buffer 'global)
(if (listp citar-bibliography) citar-bibliography
(list citar-bibliography))
(with-current-buffer buffer
(citar--major-mode-function 'local-bib-files #'ignore))))
(or buffers (list (current-buffer) 'global)))))
(defun citar--bibliographies (&rest buffers)
"Return bibliographies for BUFFERS."
(delete-dups
(mapcan
(lambda (buffer)
(citar-cache--get-bibliographies (citar--bibliography-files buffer) buffer))
(or buffers (list (current-buffer) 'global)))))
;;; Completion functions
(defun citar--completion-table (candidates &optional filter &rest metadata)
"Return a completion table for CANDIDATES.
CANDIDATES is a hash with references CAND as key and CITEKEY as value,
where CAND is a display string for the bibliography item.
FILTER, if non-nil, should be a predicate function taking
argument CITEKEY. Only candidates for which this function
returns non-nil will be offered for completion.
By default the metadata of the table contains the category and
affixation function. METADATA are extra entries for metadata of
the form (KEY . VAL).
The returned completion table can be used with `completing-read'
and other completion functions."
(let ((metadata `(metadata . ((category . citar-candidate)
. ((affixation-function . ,#'citar--ref-affix)
. ,metadata)))))
(lambda (string predicate action)
(if (eq action 'metadata)
metadata
;; REVIEW this now works, but probably needs refinement
(let ((predicate
(when (or filter predicate)
(lambda (cand key)
(and (or (null filter) (funcall filter key))
(or (null predicate) (funcall predicate cand)))))))
(complete-with-action action candidates string predicate))))))
(cl-defun citar-select-refs (&key (multiple t) filter)
"Select bibliographic references.
A wrapper around `completing-read' that returns a CITEKEY,
Takes the following optional keyword arguments:
MULTIPLE: if t, calls `completing-read-multiple' and returns a
list of CITEKEYS.
FILTER: if non-nil, should be a predicate function taking a
CITEKEY. Only candidates for which this function returns
non-nil will be offered for completion. For example:
(citar-select-ref :filter (citar-has-note))
(citar-select-ref :filter (citar-has-file))"
(let* ((candidates (or (citar--format-candidates)
(user-error "No bibliography set")))
(chosen (if (and multiple citar-select-multiple)
(citar--select-multiple "References: " candidates
filter 'citar-history citar-presets)
(completing-read "Reference: " (citar--completion-table candidates filter)
nil nil nil 'citar-history citar-presets nil))))
;; If CAND is not in CANDIDATES, treat it as a citekey (e.g. inserted into the minibuffer by `embark-act')
(cl-flet ((candkey (cand) (or (gethash cand candidates) cand)))
;; Return a list of keys regardless of 1 or many
(if (listp chosen)
(mapcar #'candkey chosen)
(list (candkey chosen))))))
(cl-defun citar-select-ref (&key filter)
"Select bibliographic references.
Call `citar-select-ref' with optional FILTER; see its
documentation for the return value."
(car (citar-select-refs :multiple nil :filter filter)))
(defun citar--multiple-completion-table (selected-hash candidates filter)
"Return a completion table for multiple selection.
SELECTED-HASH is the hash-table containing selected candidates.
CANDIDATES is the list of completion candidates, FILTER is the function
to filter them."
(citar--completion-table
candidates filter
`(group-function . (lambda (cand transform)
(pcase (list (not (not transform))
(gethash (substring-no-properties cand) ,selected-hash))
('(nil nil) (concat "Select Multiple ["
(propertize (car citar--multiple-setup)
'font-lock-face 'help-key-binding
'face 'help-key-binding) "]"))
('(nil t) "Selected")
('(t nil) cand)
('(t t)
(add-face-text-property 0 (length cand) 'citar-selection nil (copy-sequence cand))
cand))))))
(defvar citar--multiple-setup '("TAB" . "RET")
"Variable whose value should be a cons (SEL . EXIT)
SEL is the key which should be used for selection. EXIT is the key which
is used for exiting the minibuffer during completing read.")
(defun citar--multiple-exit ()
"Exit with the currently selected candidates."
(interactive)
(setq unread-command-events (listify-key-sequence (kbd (car citar--multiple-setup)))))
(defun citar--setup-multiple-keymap ()
"Make a keymap suitable for `citar--select-multiple'."
(let ((keymap (make-composed-keymap nil (current-local-map)))
(kbdselect (kbd (car citar--multiple-setup)))
(kbdexit (kbd (cdr citar--multiple-setup))))
(define-key keymap kbdselect (lookup-key keymap kbdexit))
(define-key keymap kbdexit #'citar--multiple-exit)
(use-local-map keymap)))
(defun citar--select-multiple (prompt candidates &optional filter history def)
"Select multiple CANDIDATES with PROMPT.
HISTORY is the `completing-read' history argument."
;; Because completing-read-multiple just does not work for long candidate
;; strings, and IMO is a poor UI.
(let* ((selected-hash (make-hash-table :test 'equal)))
(while (let ((initial-history (symbol-value history))
(item (minibuffer-with-setup-hook #'citar--setup-multiple-keymap
(completing-read
(format "%s (%s/%s): " prompt
(hash-table-count selected-hash)
(hash-table-count candidates))
(citar--multiple-completion-table selected-hash candidates filter)
nil t nil history `("" . ,def)))))
(unless (string-empty-p item)
(if (not (gethash item selected-hash))
(puthash item t selected-hash)
(remhash item selected-hash)
(set history initial-history)))
(not (or (eq last-command #'citar--multiple-exit)
(string-empty-p item)))))
(hash-table-keys selected-hash)))
(cl-defun citar--get-resource-candidates (citekeys &key files links notes create-notes)
"Return related resource candidates for CITEKEYS.
Return a list (CATEGORY . CANDIDATES), where CATEGORY is a
completion category and CANDIDATES is a list of resources
associated with CITEKEYS. Return nil if there are no associated
resources.
The resources include:
* FILES: a list of files or t to use `citar-get-files'.
* LINKS: a list of links or t to use `citar-get-links'.
* NOTES: a list of notes or t to use `citar-get-notes'.
* CREATE-NOTES: a list of cite keys for which to create notes,
or t to use CITEKEYS. See `citar-open-always-create-notes'.
If any of FILES, LINKS, NOTES, or CREATE-NOTES is nil, that
resource type is omitted from CANDIDATES.
CATEGORY is one of:
* `file' when returning only files
* `url' when returning only links
* the `:category' property of `citar-notes-source' if returning
only notes
* `citar-reference' when returning notes to create.
* `multi-category' when CANDIDATES has resources of multiple
types. The `multi-category' text property is applied to each
element of CANDIDATES."
(cl-flet ((getresources (table) (when table
(delete-dups (apply #'append (hash-table-values table)))))
(keycands (type citekeys)
(let ((format (citar-format--parse (citar--get-template 'completion)))
(width (- (frame-width) 2)))
(mapcar (lambda (key)
(let* ((entry (citar-get-entry key))
(cand (citar-format--entry format entry width
:ellipsis citar-ellipsis))
(keycand (citar--prepend-candidate-citekey key cand))
(target (cons 'citar-reference
(propertize key 'citar--resource type))))
(propertize keycand 'multi-category target)))
citekeys)))
(withtype (type cat cands) (when cands
(cons cat (mapcar (lambda (cand)
(propertize cand 'citar--resource type))
cands)))))
(let* ((citar--entries (citar-get-entries))
(files (if (listp files) files (getresources (citar-get-files citekeys))))
(links (if (listp links) links (getresources (citar-get-links citekeys))))
(keynotes (unless (and (listp notes) (listp create-notes)) (citar-get-notes citekeys)))
(notes (if (listp notes) notes (getresources keynotes)))
(create-notes
(keycands 'create-note
(cond ((listp create-notes) create-notes)
((or (eq t citar-open-always-create-notes)
(memq this-command citar-open-always-create-notes)
(not keynotes))
citekeys)
(t (seq-remove (lambda (citekey) (gethash citekey keynotes)) citekeys)))))
(notecat (citar--get-notes-config :category))
(sources (delq nil (list (withtype 'file 'file files)
(withtype 'url 'url links)
(withtype 'note notecat notes)
(withtype 'create-note 'citar-candidate create-notes)))))
(if (null (cdr sources)) ; if sources is nil or singleton list,
(car sources) ; return either nil or the only source.
(cons 'multi-category ; otherwise, combine all sources
(mapcan
(pcase-lambda (`(,cat . ,cands))
(if (not cat)
cands
(mapcar (lambda (cand)
(if (get-text-property 0 'multi-category cand)
cand
(propertize cand 'multi-category (cons cat cand))))
cands)))
sources))))))
(defun citar--annotate-note (candidate)
"Annotate note CANDIDATE."
(when-let (((eq 'note (get-text-property 0 'citar--resource candidate)))
(annotate (citar--get-notes-config :annotate)))
(funcall annotate (substring-no-properties candidate))))
(cl-defun citar--select-resource (citekeys &key files links notes create-notes)
"Select related FILES, NOTES, or LINKS resource for CITEKEYS.
Return (TYPE . RESOURCE), where TYPE is `file', `link', `note',
or `create-note' and RESOURCE is the selected resource string.
Return nil if there are no resources.
Use `completing-read' to prompt for a resource, unless there is
only one resource and `citar-open-prompt' is t or contains
`this-command'. Return nil if the user declined to choose."
(when-let ((resources (citar--get-resource-candidates citekeys :files files :links links
:notes notes :create-notes create-notes)))
(pcase-let ((`(,category . ,cands) resources))
(when-let ((selected
(if (not (or (cdr cands) (eq t citar-open-prompt) (memq this-command citar-open-prompt)))
(car cands)
(let* ((metadata `(metadata
(group-function . ,#'citar--select-group-related-resources)
(annotation-function . ,#'citar--annotate-note)
,@(when category `((category . ,category)))))
(table (lambda (string predicate action)
(if (eq action 'metadata)
metadata
(complete-with-action action cands string predicate))))
(selected (completing-read "Select resource: " table nil t)))
(car (member selected cands))))))
(pcase (get-text-property 0 'citar--resource selected)
('create-note (cons 'create-note (citar--extract-candidate-citekey selected)))
;; Embark expects the plain string here.
(type (cons type (substring-no-properties selected))))))))
(defun citar--select-group-related-resources (resource transform)
"Group RESOURCE by type or TRANSFORM."
(pcase (get-text-property 0 'citar--resource resource)
('file (if transform (file-name-nondirectory resource) "Library Files"))
('url (if transform resource "Links"))
('note
(if transform
(funcall (or (citar--get-notes-config :transform) #'identity) resource)
(or (citar--get-notes-config :name) "Notes")))
('create-note
(if transform
resource
(format "Create %s" (or (citar--get-notes-config :name) "Notes"))))
(_ (if transform
resource
nil))))
;; Indicator functions
(defun citar--make-indicator-processors (ispecs)
"Set the compiledfunction slots in ISPECS."
(mapc
(lambda (ispec)
(let ((fnsym (citar-indicator-function ispec)))
(setf (citar-indicator-compiledfunction ispec)
(funcall fnsym))))
ispecs))
(defun citar--make-indicator-tags (citekey iprocs)
"Return indicator tags string for CITEKEY, using IPROCS.
This string is incorporated in the candidates as hidden text, so
it can be searched against, and to contruct the indicator symbols
visible in the completion UI."
(mapconcat
(lambda (iproc)
(when-let* ((cfun (citar-indicator-compiledfunction iproc))
(tag (citar-indicator-tag iproc)))
(when (funcall cfun citekey)
(propertize (concat " " tag) 'invisible t))))
iprocs ""))
(defun citar--make-indicator-symbols (candidate)
"Return indicator string for CANDIDATE display."
(seq-reduce
(lambda (constructed ispec)
;; first arg is the accumulated string
(let* ((matchtext (citar-indicator-tag ispec))
(matchtagp (string-match-p matchtext candidate))
(sym (citar-indicator-symbol ispec))
(emptysym (citar-indicator-emptysymbol ispec))
(padding (citar-indicator-padding ispec))
(str (concat
constructed
(if matchtagp sym emptysym)
padding))
(pos (length str)))
;; See https://github.com/emacs-citar/citar/issues/764 for explanation of what this code is doing.
;;
;; We say that the last character of the padding should be replaced by a space which stretches to the
;; position we want to.
;;
;; So for example if the icon has string width 1 but occupies 0.9 the space will stretch to occupy 1.1
;; and if the icon occupies 1.5 it will shrink to occupy 0.5.
;;
;; Emacs 29 has `vtable', which we might use here in the future as well.
(put-text-property (- pos 1) pos 'display
(cons 'space
(list :align-to (string-width str)))
str)
str))
citar-indicators ""))
(defun citar--format-candidates ()
"Format completion candidates for bibliography entries.
Return a hash table with the keys being completion candidate
strings and values being citation keys.
Return nil if `citar-bibliography' returns nil."
;; Populate bibliography cache.
(when-let ((bibs (citar--bibliographies)))
(let* ((citar--entries (citar-cache--entries bibs))
(preformatted (citar-cache--preformatted bibs))
(indicatorprocs (citar--make-indicator-processors citar-indicators))
(symbolswidth (string-width
(citar--make-indicator-symbols "")))
(width (- (frame-width) symbolswidth 2))
(completions (make-hash-table :test 'equal :size (hash-table-count citar--entries))))
(prog1 completions
(maphash
(lambda (citekey _entry)
(let* ((preform (or (gethash citekey preformatted)
(error "No preformatted candidate string: %s" citekey)))
(display (citar-format--star-widths
(- width (car preform)) (cdr preform)
t citar-ellipsis))
(tagged (concat display
(citar--make-indicator-tags citekey indicatorprocs))))
(puthash tagged citekey completions)))
citar--entries)))))
(defun citar--prepend-candidate-citekey (citekey candidate)
"Prepend invisible CITEKEY to CANDIDATE string.
CITEKEY is quoted if necessary and can be extracted using
`citar--extract-candidate-citekey'."
(let* ((keyquoted (if (or (string-empty-p citekey) ; quote citekey if it's empty,
(= ?\" (aref citekey 0)) ; or starts with ",
(seq-contains-p citekey ?\s #'=)) ; or has a space.