-
Notifications
You must be signed in to change notification settings - Fork 37
/
ebib.el
5506 lines (5084 loc) · 244 KB
/
ebib.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
;;; ebib.el --- a BibTeX database manager -*- lexical-binding: t -*-
;; Copyright (c) 2003-2024 Joost Kremers
;; Copyright (c) 2022-2024 Hugo Heagren
;; All rights reserved.
;; Author: Joost Kremers <[email protected]>
;; Maintainer: Joost Kremers <[email protected]>
;; Created: 2003
;; Version: 2.48
;; Keywords: text bibtex
;; URL: http://joostkremers.github.io/ebib/
;; Package-Requires: ((parsebib "6.0") (emacs "27.1") (compat "29.1.4.3"))
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; 3. The name of the author may not be used to endorse or promote products
;; derived from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE,
;; DATA, OR PROFITS ; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;; Commentary:
;; Ebib is a BibTeX database manager that runs in GNU Emacs. With Ebib, you
;; can create and manage .bib-files, all within Emacs. It supports @String
;; and @Preamble definitions, multi-line field values, searching, and
;; integration with Emacs' (La)TeX mode, Org mode and others.
;; See the Ebib manual for usage and installation instructions.
;; The latest release version of Ebib, contact information and mailing list
;; can be found at <http://joostkremers.github.io/ebib>. Development
;; sources can be found at <https://github.com/joostkremers/ebib>.
;;; Code:
(require 'cl-lib)
(require 'easymenu)
(require 'bibtex)
(require 'seq)
(require 'crm)
(require 'pp)
(require 'hl-line)
(require 'mule-util) ; for `truncate-string-ellipsis' and `truncate-string-to-width'
(require 'button)
(require 'compat) ; for `pos-bol', `pos-eol'.
(require 'register)
(require 'parsebib)
(require 'ebib-utils)
(require 'ebib-db)
(require 'ebib-filters)
(require 'ebib-keywords)
(require 'ebib-notes)
(require 'ebib-reading-list)
;; Make sure `ivy' & `helm' are loaded during compilation.
(require 'ivy nil 'noerror)
(require 'helm nil 'noerror)
;;; Silence the byte-compiler.
(defvar pandoc-mode)
(defvar selectrum-minibuffer-map)
(defvar ivy-minibuffer-map)
(defvar ivy-sort-max-size)
(declare-function org-capture "org-capture" (&optional goto keys))
(declare-function pandoc--get "ext:pandoc-mode-utils.el" (option &optional buffer))
(declare-function ivy-read "ext:ivy.el" (prompt collection &rest args))
(declare-function helm-marked-candidates "ext:helm.el" (&optional with-wildcard all-sources))
(declare-function helm-build-sync-source "ext:helm-source.el" (name &rest args))
(declare-function helm "ext:helm.el" (&rest plist))
;;;; Helper functions
;;; Functions for `display-buffer'
(defun ebib--display-buffer-reuse-window (buffer _)
"Display BUFFER in an existing Ebib window.
If BUFFER is the index buffer, simply switch to the window
displaying it. (This function should not be called if there is a
chance the index buffer is not visible.) For any other buffer,
find a window displaying an Ebib buffer other than the index
buffer, switch to that window and display BUFFER. If no window
can be found, return nil."
(let (window)
(cond
;; The index buffer can only be displayed in its dedicated window.
((eq buffer (ebib--buffer 'index))
(setq window (get-buffer-window buffer)))
;; If `ebib-layout' isn't `full', the multiline buffer should not be
;; displayed in an Ebib buffer.
((and (memq buffer ebib--multiline-buffer-list)
(not (eq ebib-layout 'full)))
(setq window nil))
;; Find a buffer other than the index buffer that's being displayed.
(t (setq window (let ((b (cdr (seq-find (lambda (elt) (and (not (eq (car elt) 'index))
(get-buffer-window (cdr elt))))
ebib--buffer-alist))))
(if b (get-buffer-window b))))))
(when window
(with-ebib-window-nondedicated (selected-window)
(set-window-buffer window buffer))
window)))
(defun ebib--display-buffer-largest-window (buffer _)
"Display BUFFER in the largest non-dedicated window."
(unless ebib-popup-entry-window
(let ((window (get-largest-window)))
(set-window-buffer window buffer)
window)))
(defun ebib--pop-to-buffer (buffer)
"Select or create a window to display BUFFER and display it.
If the index buffer isn't visible, this function does nothing.
Otherwise, if BUFFER is the index buffer, simply switch to its
window. For any other buffer, if there is a visible Ebib buffer
other than the index buffer, switch to its window and display
BUFFER. If there is no Ebib window, use the largest non-dedicated
window or, if `ebib-layout' is set to `index-only', pop up a new
window. If all else fails, pop up a new frame."
;; If the index buffer isn't visible, do nothing.
(unless (not (get-buffer-window (ebib--buffer 'index)))
(pop-to-buffer buffer
'((ebib--display-buffer-reuse-window
ebib--display-buffer-largest-window
display-buffer-pop-up-window
display-buffer-pop-up-frame))
t)))
;;; Display functions for the index buffer
(defun ebib--get-key-at-point ()
"Return the key of the current item in the index buffer.
If point is not on a BibTeX entry, return nil."
(with-current-ebib-buffer 'index
(get-text-property (point) 'ebib-key)))
(defun ebib--display-entry (key &optional mark)
"Display BibTeX item designated by KEY in the index buffer at POINT.
Included in the display are the data in the fields specified in
`ebib-index-columns'. The item is given the text property
`ebib-key' with KEY as value. If MARK is t, `ebib-marked-face'
is applied to the item."
(let ((data (ebib--get-tabulated-data key))
(n 0)
(max (1- (length ebib-index-columns)))
(ellipsis-width (length truncate-string-ellipsis)))
(with-current-ebib-buffer 'index
(while (< n max)
(let* ((width (cadr (nth n ebib-index-columns)))
(item (nth n (cadr data)))
;; Strings that are too long for their column are truncated, but
;; if the column is too narrow, we prefer not to display
;; anything.
(display-item (if (and (< width (+ 5 ellipsis-width))
(< width (length item)))
""
(truncate-string-to-width item width nil nil t))))
(insert (bidi-string-mark-left-to-right
(format (concat "%-" (int-to-string width) "s")
display-item))
ebib-index-column-separator))
(cl-incf n))
;; The last item isn't truncated.
(insert (nth n (cadr data)))
;; Add a text property to identify the entry.
(add-text-properties (pos-bol) (point) `(ebib-key ,key))
(insert "\n")
(when mark
(add-text-properties (pos-bol 0) (point) '(face ebib-marked-face))))))
(defun ebib--goto-entry-in-index (key)
"Move point to the entry designated by KEY.
Point is placed at the beginning of the line. If there is no
entry with KEY in the buffer, point is not moved."
(with-current-ebib-buffer 'index
(let ((p (point)))
(goto-char (point-min))
(while (not (or (string= key (get-text-property (point) 'ebib-key))
(eobp)))
(forward-line 1))
(if (eobp)
(goto-char p)
(set-window-point (get-buffer-window) (point))))))
(defun ebib--get-tabulated-data (key)
"Get data for KEY.
Return value is a list consisting of KEY and a list of the
values of the fields listed in `ebib-index-columns'."
(list key (mapcar (lambda (elt)
(ebib--first-line (ebib--get-field-value-for-display (car elt) key ebib--cur-db)))
ebib-index-columns)))
(defun ebib--insert-entry-in-index-sorted (key &optional move-point mark)
"Insert KEY in the index buffer obeying the sort order.
Unless MOVE-POINT is non-nil, this function does not move point.
If MARK is non-nil, `ebib-mark-face' is applied to the entry."
(with-current-ebib-buffer 'index
(let ((inhibit-read-only t))
(let* ((keys-list (ebib--sort-keys-list (ebib-db-list-keys ebib--cur-db) ebib--cur-db))
(pos (seq-position keys-list key #'string=))
(new-pos (save-excursion
(goto-char (point-min))
(forward-line pos)
(ebib--display-entry key mark)
(point))))
(when move-point
(goto-char new-pos)
(forward-line -1)
(set-window-point (get-buffer-window) (point))
(hl-line-highlight))))))
;;; Display functions for the entry buffer.
(defun ebib--redisplay-field (field)
"Redisplay the contents of FIELD in the current buffer."
(with-current-ebib-buffer 'entry
;; If the `=type=', `crossref' or `xdata' field has changed, we need to redisplay the
;; entire entry.
(if (member-ignore-case field '("=type=" "crossref" "xdata"))
(progn
(ebib--update-entry-buffer)
(re-search-forward (rx-to-string `(seq bol ,(string-trim field "=" "=")) t))) ; Remove =-signs from `=type='.
(let ((inhibit-read-only t))
(goto-char (point-min))
(re-search-forward (format "^%s" field))
(delete-region (pos-bol) (next-single-property-change (point) 'ebib-field-end))
(save-excursion
(insert (format "%-17s %s"
(propertize field 'face 'ebib-field-face)
(ebib--get-field-highlighted field (ebib--get-key-at-point)))))
(beginning-of-line)))))
(defun ebib--redisplay-current-field ()
"Redisplay the contents of the current field in the entry buffer."
(ebib--redisplay-field (ebib--current-field)))
(defun ebib--convert-multiline-to-string (multilines)
"Convert MULTILINES to a single multiline string.
MULTILINES is a list of strings. The resulting string is
suitable for display in the entry buffer: each string in
MULTILINES corresponds to a line in the resulting string, and all
lines except the first one are prepended with 19 spaces."
(let ((first-line (car multilines))
(rest-lines (mapcar (lambda (line)
(concat (make-string 19 ?\s) (string-trim-left line)))
(cdr multilines))))
(concat first-line
(if rest-lines
(concat "\n" (string-join rest-lines "\n"))))))
(defun ebib--display-multiline-field (string matched)
"Return a string for multiline field values to display in the entry buffer.
STRING is the text to display. MATCHED indicates whether a
search string match was found. If the text is longer than
`ebib-multiline-display-max-lines' lines, it is truncated and a
continuation marker \"[...]\" is added. If MATCHED is non-nil,
this continuation marker is highlighted. Empty lines from the
beginning and end of STRING are removed.
This function calls the function in
`ebib-multiline-display-function' to convert the text to a list
of strings."
(let ((multilines (funcall ebib-multiline-display-function string))
(truncated nil))
(when (> (length multilines) ebib-multiline-display-max-lines)
(setq multilines (seq-subseq multilines 0 ebib-multiline-display-max-lines))
(setq truncated t))
(setq multilines (thread-last multilines
(seq-drop-while (lambda (elt) (string= elt "")))
(reverse)
(seq-drop-while (lambda (elt) (string= elt "")))
(reverse)))
(cl-values (ebib--convert-multiline-to-string multilines)
(if truncated
(concat "\n" (make-string 19 ?\s)
(if matched
(propertize "[...]" 'face 'highlight)
"[...]"))))))
(defun ebib--display-file-field (file-field)
"Return a string for FILE-FIELD to display in the entry buffer."
(let ((files (ebib--split-files file-field)))
(ebib--convert-multiline-to-string (mapcar (lambda (file)
(propertize file
'face 'ebib-link-face
'font-lock-face 'ebib-link-face
'mouse-face 'highlight
'help-echo "mouse-1: open this file"
'button t
'follow-link t
'category t
'button-data file
'keymap button-map
'action 'ebib--call-file-viewer))
files))))
(defun ebib--display-xdata-field (xdata-field)
"Return a string for XDATA-FIELD to display in the entry buffer.
Separate values by commas and put each on a separate line. For
each value, test if there is an entry with that key, and that it
is actually an `@XData' entry. If either test fails, propertize
the value with `ebib-warning-face' and an information help-echo
message."
(let ((keys (split-string xdata-field ",[[:space:]]*")))
(ebib--convert-multiline-to-string
(mapcar
(lambda (key)
(if-let* ((type (ebib-db-get-field-value "=type=" key ebib--cur-db 'noerror)))
(if (cl-equalp "xdata" type)
key
(propertize key
'face 'ebib-warning-face
'help-echo (format "%s is not an @XData entry." key)))
(propertize key
'face 'ebib-warning-face
'help-echo (format "No entry with key `%s'" key))))
keys))))
(defun ebib--display-related-field (related-field)
"Return a string for RELATED-FIELD to display in the entry buffer.
Separate values by commas and put each on a separate line. For
each value, test if there is an entry with that key. If not,
propertize the value with `ebib-warning-face' and an information
help-echo message."
(ebib--convert-multiline-to-string
(mapcar
(lambda (key)
(if (ebib-db-has-key key ebib--cur-db)
key
(propertize key
'face 'ebib-warning-face
'help-echo (format "No entry with key `%s'" key))))
(split-string related-field ",[[:space:]]*"))))
(defun ebib--display-doi-field (doi-field)
"Return a string for DOI-FIELD to display in the entry buffer."
(propertize doi-field
'face 'ebib-link-face
'font-lock-face 'ebib-link-face
'mouse-face 'highlight
'help-echo "mouse-1: follow this doi"
'button t
'follow-link t
'category t
'button-data (concat "https://dx.doi.org/" doi-field)
'keymap button-map
'action 'ebib--call-browser))
(defun ebib--display-url-field (url-field)
"Return a string for URL-FIELD to display in the entry buffer."
(let ((urls (ebib--split-urls url-field)))
(ebib--convert-multiline-to-string
(mapcar (lambda (url)
(propertize url
'face 'ebib-link-face
'font-lock-face 'ebib-link-face
'mouse-face 'highlight
'help-echo "mouse-1: follow this url"
'button t
'follow-link t
'category t
'button-data url
'keymap button-map
'action 'ebib--call-browser))
urls))))
(defun ebib--display-crossref-field (crossref)
"Return a string for CROSSREF to display in the entry buffer."
(propertize crossref
'face 'ebib-link-face
'font-lock-face 'ebib-link-face
'mouse-face 'highlight
'help-echo "mouse-1: follow crossref"
'button t
'follow-link t
'category t
'button-data nil
'keymap button-map
'action (lambda (_) (ebib-follow-crossref))))
(defun ebib--extract-note-text (key &optional truncate)
"Extract the text of the note for entry KEY.
This function simply calls `ebib-notes-extract-text-function'.
KEY and TRUNCATE are passed on unchanged. For their meaning, see
the doc string of `ebib-extract-note-text-default'."
(funcall ebib-notes-extract-text-function key truncate))
(defun ebib-extract-note-text-default (key truncate)
"Extract the text of the note for KEY.
The note must be an Org entry under its own headline.
If TRUNCATE is non-nil, the note is truncated at
`ebib-notes-display-max-lines' lines. If the original text is
longer than that, an ellipsis marker \"[...]\" is added.
The return value is a list of strings, each a separate line,
which can be passed to `ebib--display-multiline-field'."
(with-temp-buffer
(cond
((eq ebib-notes-storage 'multiple-notes-per-file)
(let* ((location (ebib--notes-goto-note key))
(buffer (car location))
(position (cdr location))
beg end)
(when location
(with-current-buffer buffer
(save-mark-and-excursion
(goto-char position)
(org-mark-subtree)
(setq beg (region-beginning)
end (region-end))))
(insert-buffer-substring buffer beg end))))
((eq ebib-notes-storage 'one-file-per-note)
(let ((filename (expand-file-name (ebib--create-notes-file-name key))))
(when (file-readable-p filename)
(insert-file-contents filename)))))
(let ((truncated nil)
string)
;; If appropriate, first reduce the size of the text we need to
;; pass to `org-element-parse-buffer', since this function can
;; be slow if the note is long.
(when truncate
(let ((max (progn
(goto-char (point-min))
(pos-bol (* 2 ebib-notes-display-max-lines)))))
(when (< max (point-max))
(setq truncated t)
(delete-region max (point-max)))))
;; Extract any property drawers.
(let ((contents (org-element-parse-buffer)))
(org-element-map contents 'property-drawer
(lambda (drawer)
(org-element-extract-element drawer)))
(erase-buffer)
(insert (org-element-interpret-data contents)))
;; Extract relevant lines
(let* ((beg (progn
(goto-char (point-min))
(forward-line 1) ; Skip the headline.
(point)))
;; If `truncate', then take the first
;; `ebib-notes-display-max-lines' lines.
(end (if truncate
(progn
(goto-char (point-min))
(forward-line (1+ ebib-notes-display-max-lines))
(point))
;; Otherwise take all lines
(point-max))))
(setq string (buffer-substring-no-properties beg end))
(if (or truncated
(< end (point-max)))
(setq string (concat string "[...]\n"))))
(split-string string "\n"))))
(defun ebib--get-field-highlighted (field key &optional db match-str)
"Return the contents of FIELD in entry KEY in DB with MATCH-STR highlighted."
(or db (setq db ebib--cur-db))
(let* ((case-fold-search t)
(value (ebib-get-field-value field key db 'noerror nil 'xref 'expand-strings))
(multiline "")
(raw " ")
(matched nil)
(alias ""))
;; We have to do a couple of things now:
;; - Remove {} or "" around the value, if they're there.
;; - Search for `match-str'.
;; - Properly adjust the value if it's multiline.
;; But all this is not necessary if there was no value, so we test that first.
(when value
(if (get-text-property 0 'ebib--alias value)
(setq alias (propertize (format " [<== %s]" (cdr (assoc-string field ebib--field-aliases 'case-fold))) 'face 'ebib-alias-face)))
(if (get-text-property 0 'ebib--expanded value)
(setq value (propertize value 'face 'ebib-abbrev-face 'fontified t)))
;; Propertize any stretch of the value which has an `ebib--xref'
;; property with `ebib-crossref-face'
(let* ((xref-lst (seq-filter (lambda (plist) (eq (caaddr plist) 'ebib--xref))
;; This is a HACK, based on
;; https://emacs.stackexchange.com/a/54181/34394
;; FIXME Using `object-intervals' would be much quicker and more
;; elegant here, but only once it's supported in a current
;; version of Emacs!
(seq-partition (cdr-safe (read (substring (format "%S" value) 1))) 3)))
(int-lst (mapcar #'butlast xref-lst)))
(mapc
(lambda (ints)
(add-text-properties
(car ints) (cadr ints)
`(face ebib-crossref-face
help-echo ,(format "Inherited from entry `%s'" (get-text-property (car ints) 'ebib--xref value)))
value))
int-lst))
(if (and (member-ignore-case field '("crossref" "xref"))
(not (ebib--find-db-for-key (ebib-unbrace value) ebib--cur-db)))
(setq value (propertize value 'face 'ebib-warning-face)))
(if (cl-equalp field "keywords")
(let* ((keywords (ebib--keywords-to-list (ebib-unbrace value)))
(new-value (mapconcat (lambda (keyword)
(if (not (member-ignore-case keyword ebib--keywords-completion-list))
(propertize keyword 'face 'ebib-warning-face)
keyword))
keywords
ebib-keywords-separator)))
(setq value (if (ebib-unbraced-p value)
new-value
(ebib-brace new-value)))))
(if (ebib-unbraced-p value)
(setq raw "*")
(setq value (ebib-unbrace value))) ; We have to make the value look nice.
(when match-str
(cl-multiple-value-setq (value matched) (ebib--match-all-in-string match-str value)))
(when (ebib--multiline-p value)
(cl-multiple-value-setq (value multiline) (ebib--display-multiline-field value matched)))
(if (cl-equalp field "file")
(setq value (ebib--display-file-field value)))
(if (cl-equalp field "related")
(setq value (ebib--display-related-field value)))
(if (cl-equalp field "xdata")
(setq value (ebib--display-xdata-field value)))
(if (cl-equalp field "url")
(setq value (ebib--display-url-field value)))
(if (cl-equalp field "doi")
(setq value (ebib--display-doi-field value)))
(if (cl-equalp field "crossref")
(setq value (ebib--display-crossref-field value))))
(concat raw value alias multiline)))
(defun ebib--display-fields (key &optional db match-str)
"Display the fields of entry KEY in DB.
The fields are inserted in the current buffer with their values.
If MATCH-STR is provided, then when it is present in the value,
it is highlighted. DB defaults to the current database."
(or db
(setq db ebib--cur-db))
(let* ((dialect (ebib--get-dialect db))
(entry (ebib-get-entry key db 'noerror 'xref))
(entry-type (cdr (assoc "=type=" entry)))
(req-fields (ebib--list-fields entry-type 'required dialect))
(opt-fields (ebib--list-fields entry-type 'optional dialect))
(extra-fields (ebib--list-fields entry-type 'extra dialect))
(undef-fields (seq-remove #'ebib--special-field-p (mapcar #'car (ebib--list-undefined-fields entry dialect)))))
(insert (format "%-18s %s%s"
(propertize "type" 'face 'ebib-field-face)
(if (assoc-string entry-type (ebib--list-entry-types dialect t) 'case-fold)
entry-type
(propertize entry-type 'face 'error))
(if (and (eq dialect 'biblatex)
(assoc-string entry-type ebib--type-aliases 'case-fold))
(propertize (format " [==> %s]" (cdr (assoc-string entry-type ebib--type-aliases 'case-fold))) 'face 'ebib-alias-face)
""))
(propertize "\n" 'ebib-field-end t))
(mapc (lambda (fields)
(when fields ; If one of the sets is empty, we don't want an extra empty line.
(insert "\n")
(mapc (lambda (field)
(unless (and (not (ebib-get-field-value field key db 'noerror nil 'xref 'expand-strings)) ; If a field does not have a value,
(or (eq ebib-hidden-fields t) ; and is hidden, don't display it,
(and (listp ebib-hidden-fields)
(member-ignore-case field ebib-hidden-fields)))
ebib--hide-hidden-fields) ; unless the user wants to see all hidden fields.
(insert (format "%-17s %s"
(propertize field 'face 'ebib-field-face)
(ebib--get-field-highlighted field key db match-str))
;; The final newline gets a special text
;; property, so we can easily detect the end of
;; a field.
(propertize "\n" 'ebib-field-end t))))
fields)))
(list req-fields opt-fields extra-fields undef-fields))
(when (and (eq ebib-notes-show-note-method 'top-lines)
(ebib--notes-has-note key))
(let ((note (ebib--extract-note-text key 'truncate)))
(insert "\n"
(format "%-18s %s"
(propertize "external note" 'face 'ebib-field-face)
(ebib--convert-multiline-to-string note))
(propertize "\n" 'ebib-field-end t))))))
;;; Display functions for the strings buffer.
(defun ebib--generate-string-display (string)
"Get a formatted string for displaying abbrev STRING."
(let* ((def (ebib-get-string string ebib--cur-db 'noerror nil))
(rawp (ebib-unbraced-p def))
(unbraced-str (ebib-unbrace def))
(multilinep (ebib--multiline-p unbraced-str))
(str (if multilinep
(ebib--first-line unbraced-str)
unbraced-str))
(flags (concat (if rawp "*" "")
(if multilinep "+" "")))
(expansion (if rawp (concat "[" (ebib-get-string string ebib--cur-db 'noerror 'unbraced 'expand) "]") "")))
(format "%-18s %2s%s %s"
string ;; Abbreviation
flags ;; Raw/multiline indicators
str ;; Definition (presented without unbraced)
expansion))) ;; Full expansion when unbraced
(defun ebib--redisplay-strings-buffer ()
"Redisplay all strings in strings buffer."
(with-current-ebib-buffer 'strings
(let ((inhibit-read-only t)
(string (ebib--current-string)))
(erase-buffer)
(ebib--fill-strings-buffer)
(re-search-forward
(rx-to-string `(: line-start ,string (syntax -)) t)))))
;;; Updating the buffers
(defun ebib--update-buffers (&optional no-index-refresh)
"Redisplay the index and entry buffers.
The contents of both buffers are recreated, unless
NO-INDEX-REFRESH is non-nil, in which case the index buffer is
not recreated. Instead, the index buffer of `ebib--cur-db' is
simply displayed. If `ebib--cur-db' has no index buffer yet, one
is created.
Note that NO-INDEX-REFRESH does not affect the entry buffer: its
contents is recreated unconditionally."
(ebib--update-index-buffer no-index-refresh)
(ebib--update-entry-buffer))
(defun ebib--update-index-buffer (&optional no-refresh)
"Recreate the contents of the index buffer using the keys of `ebib--cur-db'.
If `ebib--cur-db' is nil, the buffer is just erased and its name
set to \"Ebib (no file)\". If NO-REFRESH is non-nil, display the
index buffer associated with `ebib--cur-db' but do not refresh
its contents, unless the buffer-local value of
`ebib--dirty-index-buffer' is non-nil. If `ebib--cur-db' does
not have an associated index buffer, create one and fill it."
(let ((window (get-buffer-window (ebib--buffer 'index)))
(index-buffer (when ebib--cur-db
(ebib-db-get-buffer ebib--cur-db))))
(when (not index-buffer)
(setq index-buffer (ebib--get-or-create-index-buffer ebib--cur-db))
(setq no-refresh nil)) ; We just created the index buffer, so we need to fill it.
(if (buffer-local-value 'ebib--dirty-index-buffer index-buffer)
(setq no-refresh nil))
(setcdr (assq 'index ebib--buffer-alist) index-buffer)
(when window ; Just to be sure, but `window' shouldn't be nil.
(with-selected-window window
(with-ebib-window-nondedicated (selected-window)
(switch-to-buffer index-buffer))))
(with-current-ebib-buffer 'index
(let ((cur-entry (ebib--db-get-current-entry-key ebib--cur-db)))
(unless no-refresh
(let ((inhibit-read-only t))
(erase-buffer)
(when ebib--cur-db
(let ((cur-keys-list (ebib--list-keys))
(marked-entries (ebib-db-list-marked-entries ebib--cur-db)))
;; We may call this function when there are no entries in the
;; database. If so, we don't need to do this:
(unless (= 0 (ebib-db-count-entries ebib--cur-db))
;; It may be that no entry satisfies the filter.
(if (not cur-keys-list)
(message "No entries matching the filter")
;; Fill the buffer.
(dolist (entry cur-keys-list)
(ebib--display-entry entry (member entry marked-entries)))
;; Make sure the current entry is among the visible entries.
(unless (member cur-entry cur-keys-list)
(setq cur-entry (car cur-keys-list)))))))
(with-current-buffer index-buffer
(setq ebib--dirty-index-buffer nil))))
(if (and window cur-entry)
(ebib--goto-entry-in-index cur-entry)
(goto-char (point-min)))
(hl-line-highlight))
(ebib--rename-index-buffer))))
(defun ebib--rename-index-buffer ()
"Rename the index buffer."
(with-current-ebib-buffer 'index
(rename-buffer (or (and ebib--cur-db
(concat (format " %d:" (1+ (- (length ebib--databases)
(length (member ebib--cur-db ebib--databases)))))
(ebib-db-get-filename ebib--cur-db 'short)))
ebib--empty-index-buffer-name)
'unique)))
(defvar ebib--note-window nil "Window showing the current entry's note.")
(defun ebib--update-entry-buffer (&optional match-str keep-note)
"Fill the entry buffer with the fields of the current entry.
MATCH-STR is a regexp that will be highlighted when it occurs in
the field contents.
If KEEP-NOTE is non-nil, the window showing the current entry's
note is not recreated."
(when (ebib--buffer 'entry)
(when (and ebib--note-window (not keep-note))
(when (window-live-p ebib--note-window)
(delete-window ebib--note-window)
(setq ebib--needs-update nil)) ; See below.
(setq ebib--note-window nil))
(with-current-ebib-buffer 'entry
(let ((inhibit-read-only t)
(key (ebib--get-key-at-point)))
(erase-buffer)
(when key ; Are there entries being displayed?
(ebib--display-fields key ebib--cur-db match-str)
(goto-char (point-min))
(if (and (not keep-note)
(get-buffer-window (ebib--buffer 'entry))
(eq ebib-notes-show-note-method 'all)
(eq ebib-layout 'full)
(ebib--notes-has-note key))
(setq ebib--note-window (display-buffer (ebib-open-note (ebib--get-key-at-point)))
;; If Ebib is lowered and then reopened, we need to redisplay
;; the entry buffer, because otherwise the notes buffer isn't
;; redisplayed. So we set the variable `ebib--needs-update' to
;; t, which then causes the command `ebib' to redisplay the
;; buffers. This is a hack, but the simplest way to do it.
ebib--needs-update t)))))))
(defun ebib--update-entry-buffer-keep-note ()
"Update the entry buffer but keep the note window."
;; This function is used in `after-save-hook' in note buffers. See
;; `ebib--notes-open-single-note-file'.
(ebib--update-entry-buffer nil t))
(defun ebib--set-modified (mod db &optional main dependents)
"Set the modified flag MOD on database DB.
MOD must be either t or nil. If DB is the current database, the
mode line is redisplayed, in order to correctly reflect the
database's modified status.
If MAIN is non-nil and DB is a dependent database, also set the
modified status of DB's main database to MOD. If DEPENDENTS is
non-nil, it should be a list of dependent databases, whose
modified status is also set to MOD. Note: it is ok to have MAIN
set to t if DB is not a dependent database: in such a case, MAIN
has no effect. The DEPENDENTS are set to MOD unconditionally,
however, without checking to see if they are really dependents of
DB, or even dependents at all.
The return value is MOD."
(unless db
(setq db ebib--cur-db))
(ebib-db-set-modified mod db)
(when (and main (ebib-db-dependent-p db))
(ebib-db-set-modified mod (ebib-db-get-main db)))
(when dependents
(mapc (lambda (dependent)
(ebib-db-set-modified mod dependent))
dependents))
(when (eq db ebib--cur-db)
(with-current-ebib-buffer 'index
(force-mode-line-update)))
mod)
(defun ebib--modified-p ()
"Check if any of the databases in Ebib were modified.
Return the first modified database, or nil if none was modified."
(seq-find (lambda (db)
(ebib-db-modified-p db))
ebib--databases))
(defun ebib--create-new-database (&optional main)
"Create a new database instance and return it.
If MAIN is non-nil, create a dependent database for MAIN."
(let ((new-db (ebib-db-new-database main)))
(setq ebib--databases (append ebib--databases (list new-db)))
new-db))
(defun ebib--list-keys (&optional db)
"Return a list of entry keys in DB.
If a filter is active, only the keys of entries that match the
filter are returned. The returned list is sorted. DB defaults
to the current database."
(or db (setq db ebib--cur-db))
(let ((keys (if (ebib-db-get-filter db)
(ebib--filters-run-filter db)
(ebib-db-list-keys db))))
(ebib--sort-keys-list keys db)))
(defun ebib-read-database (prompt &optional databases)
"Read the filename of a database, with completion.
The filenames of the databases in DATABASES are offered for
completion, the database associated with the selected filename is
returned. DATABASES defaults to the databases
in`ebib--databases'. PROMPT is the string used to prompt the
user."
(or databases (setq databases ebib--databases))
(ebib--get-db-from-filename (completing-read prompt (mapcar (lambda (s)
(ebib-db-get-filename s 'shortened))
databases)
nil t)))
(defun ebib--completion-finish-key (command)
"Return the key binding that finishes a completion command.
COMMAND is the command to finish, one of the symbols
`completing-read' or `read-file-name'."
(cond
((and (boundp 'selectrum-mode) selectrum-mode) (key-description (where-is-internal 'selectrum-submit-exact-input (list selectrum-minibuffer-map) 'non-ascii)))
((and (boundp 'ivy-mode) ivy-mode) (key-description (where-is-internal 'ivy-immediate-done (list ivy-minibuffer-map) 'non-ascii)))
((and (boundp 'helm-mode) helm-mode) (let ((map (symbol-value (alist-get command '((completing-read . helm-comp-read-map)
(read-file-name . helm-read-file-map))))))
(key-description (where-is-internal 'helm-cr-empty-string (list map) 'non-ascii))))
(t (key-description [return]))))
;;; Main
;;;###autoload
(defun ebib (&optional file key)
"Ebib, a BibTeX database manager.
Optional argument FILE is a file to load. If FILE is already
loaded, switch to it. If KEY is given, jump to it."
(interactive)
;; Save the buffer from which Ebib is called.
(setq ebib--buffer-before (current-buffer))
;; And set it as the buffer to push entries to.
(setq ebib--push-buffer (current-buffer))
;; See if there are local databases.
(ebib--get-local-bibfiles)
;; See if there's a key at point.
(or key (setq key (ebib--read-string-at-point "][^\"@\\&$#%',={} \t\n\f")))
;; Initialize Ebib if required.
(unless ebib--initialized
(ebib-init)
(setq ebib--needs-update t)
(ebib-check-notes-config))
;; Set up the windows.
(ebib--setup-windows)
;; See if we have a file.
(when file
(setq ebib--cur-db (ebib--load-bibtex-file-internal (ebib--locate-bibfile file (append ebib-bib-search-dirs (list default-directory)))))
(setq ebib--needs-update t))
;; See if we have a key.
(when (and key (ebib--find-and-set-key key (buffer-local-value 'ebib-local-bibfiles ebib--buffer-before)))
(setq ebib--needs-update t))
(when ebib--needs-update
(setq ebib--needs-update nil)
(ebib--update-buffers 'no-refresh))
(ebib--history-mutate (ebib--get-key-at-point)))
(defun ebib--find-and-set-key (key files)
"Make KEY the current entry.
FILES is a list of BibTeX files in which KEY is searched,
provided they are open in Ebib. If FILES is nil, only the
current database is searched."
(when ebib--databases
(if (null files)
(unless (member key (ebib-db-list-keys ebib--cur-db))
(setq key nil))
(let ((database (catch 'found
(mapc (lambda (file)
(let ((db (ebib--get-db-from-filename file)))
(if (and db (member key (ebib-db-list-keys db)))
(throw 'found db))))
files)
nil))) ; We must return nil if the key wasn't found anywhere.
(if (null database)
(setq key nil)
(setq ebib--cur-db database))))
(if key
(ebib-db-set-current-entry-key key ebib--cur-db))))
(defun ebib--read-string-at-point (chars)
"Read a string at POINT delimited by CHARS and return it.
CHARS is a string of characters that should not occur in the string."
(save-excursion
(skip-chars-backward (concat "^" chars))
(let ((beg (point)))
(ebib--looking-at-goto-end (concat "[^" chars "]*"))
(buffer-substring-no-properties beg (point)))))
;;;###autoload
(defun ebib-init ()
"Initialise Ebib.
This function sets all variables to their initial values, creates
the buffers and loads the files in `ebib-preload-bib-files'.
This function can be used to open Ebib in the background, e.g.,
in the user's init file."
(setq ebib--saved-window-config nil)
(ebib--create-buffers)
(if ebib-keywords
(ebib--keywords-load-canonical-list))
(ebib--filters-load-file ebib-filters-default-file)
(add-hook 'kill-emacs-query-functions 'ebib--kill-emacs-query-function)
(add-hook 'kill-buffer-query-functions 'ebib--kill-multiline-query-function)
(when ebib-preload-bib-files
(mapc (lambda (file)
(ebib--load-bibtex-file-internal (or (locate-file file ebib-bib-search-dirs)
(expand-file-name file))))
ebib-preload-bib-files)
(setq ebib--cur-db (car ebib--databases))) ; Display the first database in the list.
(setq ebib--initialized t
ebib--needs-update t))
(defun ebib--setup-windows ()
"Create Ebib's window configuration.
If the index buffer is already visible in some frame, select its
window and make the frame active,"
(let ((index-window (get-buffer-window (ebib--buffer 'index) t))
(old-frame (selected-frame)))
(if index-window
(progn (select-window index-window t)
(unless (eq (window-frame) old-frame)
(select-frame-set-input-focus (window-frame))
(setq ebib--frame-before old-frame)))
(setq ebib--saved-window-config (current-window-configuration))
(setq ebib--frame-before nil)
(cond
((eq ebib-layout 'full)
(delete-other-windows))
((eq ebib-layout 'custom)
(setq ebib--window-before (selected-window))
(delete-other-windows)
(let ((width (cond
((integerp ebib-width)
(- (window-total-width) ebib-width))
((floatp ebib-width)
(- (window-total-width) (truncate (* (window-total-width) ebib-width)))))))
(select-window (split-window (selected-window) width t)))))
(let* ((index-window (selected-window))
(entry-window (split-window index-window ebib-index-window-size
ebib-window-vertical-split)))
(switch-to-buffer (ebib--buffer 'index))
(unless (eq ebib-layout 'index-only)
(set-window-buffer entry-window (ebib--buffer 'entry)))
(set-window-dedicated-p index-window t)
(if (eq ebib-layout 'custom)
(set-window-dedicated-p entry-window t)))))
(if (buffer-local-value 'ebib--dirty-index-buffer (ebib--buffer 'index))
(setq ebib--needs-update t)))
(defun ebib--create-buffers ()
"Create the buffers for Ebib."
;; First we create a buffer to hold the fields of the current entry.
(push (cons 'entry (get-buffer-create "*Ebib-entry*")) ebib--buffer-alist)
(with-current-ebib-buffer 'entry
(ebib-entry-mode)
(buffer-disable-undo))
;; Then we create a buffer to hold the @String definitions.
(push (cons 'strings (get-buffer-create "*Ebib-strings*")) ebib--buffer-alist)
(with-current-ebib-buffer 'strings
(ebib-strings-mode)
(buffer-disable-undo))
;; The log buffer.
(push (cons 'log (get-buffer-create "*Ebib-log*")) ebib--buffer-alist)
(with-current-ebib-buffer 'log
(erase-buffer)
(insert "Ebib log messages\n\n(Press C-v or SPACE to scroll down, M-v or `b' to scroll up, `q' to quit.)\n\n")
(ebib-log-mode)
(buffer-disable-undo))
;; And lastly we create a buffer for the entry keys.
(push (cons 'index (ebib--get-or-create-index-buffer)) ebib--buffer-alist))
(defun ebib--get-or-create-index-buffer (&optional db)
"Create an index buffer for DB.
If DB already has an index buffer, return it instead. If DB is
nil, get or create a buffer named \" Ebib (no file)\". Return
the new buffer."
(let ((buffer (if db
(or (ebib-db-get-buffer db)
(generate-new-buffer (ebib-db-get-filename db 'short)))
(get-buffer-create ebib--empty-index-buffer-name))))
(with-current-buffer buffer
(ebib-index-mode))
(when db
(ebib-db-set-buffer buffer db))
buffer))
(defun ebib-check-notes-config ()
"Check the user's notes configuration and adjust if necessary.
If `ebib-notes-file' is set, `ebib-notes-locations' is set to
`multiple-notes-per-file' and a warning is issued."
(when (and (bound-and-true-p ebib-notes-file))
(setq ebib-notes-storage 'multiple-notes-per-file)
(ebib--log 'warning "Ebib's handling of external notes has changed. Please visit the manual and update your configuration.")))
(defun ebib-force-quit ()
"Force quit Ebib by call `ebib-quit'."
(interactive)
(ebib-quit t))
(defun ebib-quit (&optional force-quit)
"Quit Ebib.