forked from emacs-citar/citar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
citar.el
1587 lines (1350 loc) · 65.2 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 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: 0.9.7
;; Homepage: https://github.com/emacs-citar/citar
;; Package-Requires: ((emacs "27.1") (parsebib "3.0") (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)
;;; pre-1.0 API cleanup
;; make public
;; (make-obsolete 'citar--get-candidates 'citar-get-candidates "1.0")
;; Renamed in 1.0
(make-obsolete 'citar-has-file #'citar-has-files "1.0")
(make-obsolete 'citar-has-note #'citar-has-notes "1.0")
(make-obsolete 'citar-open-library-file #'citar-open-files "1.0")
(make-obsolete 'citar-attach-library-file #'citar-attach-files "1.0")
(make-obsolete 'citar-open-link #'citar-open-links "1.0")
(make-obsolete 'citar-get-link #'citar-get-links "1.0") ; now returns list
(make-obsolete 'citar-display-value 'citar-get-display-value "1.0")
;; make all these private
(make-obsolete 'citar-clean-string 'citar--clean-string "1.0")
(make-obsolete 'citar-shorten-names 'citar--shorten-names "1.0")
(make-obsolete 'citar-get-template 'citar--get-template "1.0")
(make-obsolete 'citar-open-multi 'citar--open-multi "1.0")
(make-obsolete 'citar-select-group-related-resources
'citar--select-group-related-resources "1.0")
(make-obsolete 'citar-select-resource 'citar--select-resource "1.0")
;; also rename
(make-obsolete 'citar-has-a-value 'citar-get-field-with-value "0.9.5") ; now returns cons pair
(make-obsolete 'citar-field-with-value 'citar-get-field-with-value "1.0") ; now returns cons pair
(make-obsolete 'citar--open-note 'citar-file--open-note "1.0")
;;(make-obsolete-variable 'citar-format-note-function "1.0")
;;; 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 :weight bold))
"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-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} ${date year issued:4} ${title:48}")
(suffix . " ${=key= id:15} ${=type=:12} ${tags keywords keywords:*}")
(preview . "${author editor} (${year issued date}) ${title}, \
${journal journaltitle publisher container-title collection-title}.\n")
(note . "Notes on ${author editor}, ${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-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 (KEY . ENTRY) 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?
'((t . citar--clean-string)
(("author" "editor") . citar--shorten-names))
"Configure transformation of field display values from raw values.
All functions that match a particular field are run in order."
:group 'citar
:type '(alist :key-type (choice (const t) (repeat string))
:value-type function))
(defcustom citar-symbols
`((file . ("F" . " "))
(note . ("N" . " "))
(link . ("L" . " ")))
"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."
:group 'citar
:type 'string)
;;;; 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 with each
entry being either a citation KEY or a (KEY . ENTRY) pair."
: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-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 function to test for keys with notes
:open function to open a given note candidate
:items function to return candidate strings for keys
:annotate annotation function (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 . reftex-all-used-citation-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-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 "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 KEY. 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 (_ key)
(and (or (null filter) (funcall filter key))
(or (null predicate) (funcall predicate string)))))))
(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 (KEY . ENTRY),
where ENTRY is a field-value alist. Therefore `car' of the
return value is the cite key, and `cdr' is an alist of structured
data.
Takes the following optional keyword arguments:
MULTIPLE: if t, calls `completing-read-multiple' and returns an
alist of (KEY . ENTRY) pairs.
FILTER: if non-nil, should be a predicate function taking
arguments KEY and ENTRY. 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 argument ':multiple, and 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) "Select Multiple")
('(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 ((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)
(pop (symbol-value history))))
(not (or (eq last-command #'citar--multiple-exit)
(string-empty-p item)))))
(hash-table-keys selected-hash)))
(cl-defun citar--get-resource-candidates (keys &key files links notes create-notes)
"Return related resource candidates for KEYS.
Return a list (CATEGORY . CANDIDATES), where CATEGORY is a
completion category and CANDIDATES is a list of resources
associated with KEYS. 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 KEYS. 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 keys) (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)))
keys)))
(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 keys))))
(links (if (listp links) links (getresources (citar-get-links keys))))
(keynotes (unless (and (listp notes) (listp create-notes)) (citar-get-notes keys)))
(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))
keys)
(t (seq-remove (lambda (key) (gethash key keynotes)) keys)))))
(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 (keys &key files links notes create-notes)
"Select related FILES, NOTES, or LINKS resource for KEYS.
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 keys :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)))
(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))))
(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-bibliographies' returns nil."
;; Populate bibliography cache.
(when-let ((bibs (citar--bibliographies)))
(let* ((citar--entries (citar-cache--entries bibs))
(preformatted (citar-cache--preformatted bibs))
(hasfilesp (citar-has-files))
(hasnotesp (citar-has-notes))
(haslinksp (citar-has-links))
(hasfilestag (propertize " has:files" 'invisible t))
(hasnotestag (propertize " has:notes" 'invisible t))
(haslinkstag (propertize " has:links" 'invisible t))
(symbolswidth (string-width (citar--symbols-string t t t)))
(width (- (frame-width) symbolswidth 2))
(completions (make-hash-table :test 'equal :size (hash-table-count citar--entries))))
(prog1 completions
(maphash
(lambda (citekey _entry)
(let* ((hasfiles (and hasfilesp (funcall hasfilesp citekey)))
(hasnotes (and hasnotesp (funcall hasnotesp citekey)))
(haslinks (and haslinksp (funcall haslinksp citekey)))
(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 (if (not (or hasfiles hasnotes haslinks))
display
(concat display
(when hasfiles hasfilestag)
(when hasnotes hasnotestag)
(when haslinks haslinkstag)))))
(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.
(prin1-to-string citekey)
citekey))
(prefix (propertize (concat keyquoted
(when (and candidate (not (string-empty-p candidate))) " "))
'invisible t)))
(concat prefix candidate)))
(defun citar--extract-candidate-citekey (candidate)
"Extract the citation key from string CANDIDATE."
(unless (string-empty-p candidate)
(if (= ?\" (aref candidate 0))
(read candidate)
(substring-no-properties candidate 0 (seq-position candidate ?\s #'=)))))
(defun citar--key-at-point ()
"Return bibliography key at point in current buffer, along with its bounds.
Return (KEY . BOUNDS), where KEY is a string and BOUNDS is either
nil or a (BEG . END) pair indicating the location of KEY in the
buffer. Return nil if there is no key at point or the current
major mode is not supported."
(citar--major-mode-function 'key-at-point #'ignore))
(defun citar--citation-at-point ()
"Return citation at point in current buffer, along with its bounds.
Return (KEYS . BOUNDS), where KEYS is a list of citation keys and
BOUNDS is either nil or a (BEG . END) pair indicating the
location of the citation in the buffer. Return nil if there is no
citation at point or the current major mode is not supported."
(citar--major-mode-function 'citation-at-point #'ignore))
(defun citar-key-at-point ()
"Return the citation key at point in the current buffer.
Return nil if there is no key at point or the major mode is not
supported."
(car (citar--key-at-point)))
(defun citar-citation-at-point ()
"Return a list of keys comprising the citation at point in the current buffer.
Return nil if there is no citation at point or the major mode is
not supported."
(car (citar--citation-at-point)))
;;; Major-mode functions
(defun citar--get-major-mode-function (key &optional default)
"Return function associated with KEY in `major-mode-functions'.
If no function is found matching KEY for the current major mode,
return DEFAULT."
(alist-get
key
(cdr (seq-find
(pcase-lambda (`(,modes . ,_functions))
(or (eq t modes)
(apply #'derived-mode-p (if (listp modes) modes (list modes)))))
citar-major-mode-functions))
default))
(defun citar--major-mode-function (key default &rest args)
"Function for the major mode corresponding to KEY applied to ARGS.
If no function is found, the DEFAULT function is called."
(apply (citar--get-major-mode-function key default) args))
;;; Data access functions
(defun citar-get-entry (key)
"Return entry for reference KEY, as an association list.
Note: this function accesses the bibliography cache and should
not be used for retreiving a large number of entries. Instead,
prefer `citar--get-entries'."
(if citar--entries
(gethash key citar--entries)
(citar-cache--entry key (citar--bibliographies))))
(defun citar-get-entries ()
"Return all entries for currently active bibliographies.
Return a hash table whose keys are citation keys and values are
the corresponding entries."
(or citar--entries (citar-cache--entries (citar--bibliographies))))
(defun citar-get-value (field key-or-entry)
"Return value of FIELD in reference KEY-OR-ENTRY.
KEY-OR-ENTRY should be either a string key, or an entry alist as
returned by `citar-get-entry'. Return nil if the FIELD is not
present in KEY-OR-ENTRY."
(let ((entry (if (stringp key-or-entry)
(citar-get-entry key-or-entry)
key-or-entry)))
(cdr (assoc-string field entry))))
(defun citar-get-field-with-value (fields key-or-entry)
"Find the first field among FIELDS that has a value in KEY-OR-ENTRY.
Return (FIELD . VALUE), where FIELD is the element of FIELDS that
was found to have a value, and VALUE is its value."
(let ((entry (if (stringp key-or-entry)
(citar-get-entry key-or-entry)
key-or-entry)))
(seq-some (lambda (field)
(when-let ((value (citar-get-value field entry)))
(cons field value)))
fields)))
(defun citar-get-display-value (fields key-or-entry)
"Return the first non nil value for KEY-OR-ENTRY among FIELDS .
The value is transformed using `citar-display-transform-functions'"
(let ((fieldvalue (citar-get-field-with-value fields key-or-entry)))
(seq-reduce (lambda (string fun)
(if (or (eq t (car fun))
(seq-contains-p (car fun) (car fieldvalue) #'string=))
(funcall (cdr fun) string)
string))
citar-display-transform-functions
;; Make sure we always return a string, even if empty.
(or (cdr fieldvalue) ""))))
;;;; File, notes, and links
(defun citar--get-notes-config (property)
"Return PROPERTY value for configured notes backend."
(plist-get
(alist-get citar-notes-source citar-notes-sources) property))
(defun citar-register-notes-source (name config)
"Register note backend.
NAME is a symbol, and CONFIG is a plist."
(citar--check-notes-source name config)
(setf (alist-get name citar-notes-sources) config))
(defun citar-remove-notes-source (name)
"Remove note backend NAME."
(cl-callf2 assq-delete-all name citar-notes-sources))
(cl-defun citar-get-notes (&optional (key-or-keys nil filter-p))
"Return notes associated with KEY-OR-KEYS.
KEY-OR-KEYS should be either a list KEYS or a single key. Return
a hash table mapping elements of KEYS to lists of associated
notes found using `citar-notes-source'. Include notes associated
with cross-referenced keys.
If KEY-OR-KEYS is omitted, return notes for all entries. If it is
nil, return nil."
(when (or key-or-keys (not filter-p))
(citar--get-resources key-or-keys
(citar--get-notes-config :items))))
(defun citar-create-note (key &optional entry)
"Create a note for KEY and ENTRY.
If ENTRY is nil, use `citar-get-entry' with KEY."
(interactive (list (citar-select-ref)))
(funcall (citar--get-notes-config :create) key (or entry (citar-get-entry key))))
(cl-defun citar-get-files (&optional (key-or-keys nil filter-p))
"Return files associated with KEY-OR-KEYS.
KEY-OR-KEYS should be either a list KEYS or a single key. Return
a hash table mapping elements of KEYS to lists of associated
files found using `citar-file-sources'. Include files associated
with cross-referenced keys.
If KEY-OR-KEYS is omitted, return files for all entries. If it is
nil, return nil."
(when (or key-or-keys (not filter-p))
(citar--get-resources key-or-keys
(mapcar (lambda (source)
(plist-get source :items))
citar-file-sources))))
(cl-defun citar-get-links (&optional (key-or-keys nil filter-p))
"Return links associated with KEY-OR-KEYS.
KEY-OR-KEYS should be either a list KEYS or a single key. Return
a hash table mapping elements of KEYS to lists of associated