-
Notifications
You must be signed in to change notification settings - Fork 2
/
bibtex-runtime.lisp
1592 lines (1448 loc) · 57.2 KB
/
bibtex-runtime.lisp
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
;; A BibTeX re-implementation in Common Lisp - runtime package
;; Copyright 2001, 2002 Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of version 2.1 of the GNU Lesser
;; General Public License as published by the Free Software
;; Foundation or any later version, as clarified by the preamble
;; found in COPYING-preamble.txt. This preamble is in the style
;; of the Franz Inc. preamble at http://opensource.franz.com/preamble.html
;; with names and copyright holders altered accordingly.
(in-package bibtex-runtime)
;;; Error history
(defconstant +spotless-history+ 0)
(defconstant +warning-message+ 1)
(defconstant +error-message+ 2)
(defconstant +fatal-message+ 3)
(defvar *history* +spotless-history+)
(defvar *err-count* 0)
(defun mark-history (level)
(cond ((> level *history*)
(setq *history* level
*err-count* 1))
((= level *history*)
(incf *err-count*))))
(defun mark-warning ()
(mark-history +warning-message+))
(defun mark-error ()
(mark-history +error-message+))
(defun mark-fatal ()
(mark-history +fatal-message+))
(defun bib-warn (format-control &rest args)
"Emit a warning."
(format *error-output* "Warning--")
(apply #'format *error-output* format-control args)
(terpri *error-output*)
(mark-warning))
(defun bib-warn* (&rest strings)
"Emit a warning consisting of the concatenation of STRINGS."
(bib-warn "~{~A~}" strings))
(defun bib-error (format-control &rest args)
"When there's a serious error parsing a BIB file, we flush
everything up to the beginning of the next entry."
(apply #'format *error-output* format-control args)
(format *error-output* "~&I'm skipping whatever remains of this command or entry~%")
(mark-error)
(throw 'bib-error nil))
(defun bib-fatal (format-control &rest args)
(apply #'format *error-output* format-control args)
(terpri *error-output*)
(mark-fatal)
(error "Fatal BibTeX error"))
;;; Interface to BibTeX entries
;;; Reading the database files
(defvar *bib-stream* nil)
(defvar *bib-macros* nil "A hashtable associating macro names with their definitions")
(defvar *bib-database* nil "A hashtable associating BibTeX keys with entries")
(defvar *bib-entries* nil "A list containing all requested BibTeX entries")
(defvar *bib-preamble* "" "A string accumulating all BibTeX @PREAMBLEs")
(defvar *bib-entry* nil)
(defvar *bib-entry-type-functions* nil
"An alist mapping BibTeX entry types to formatter functions")
(defparameter *identifier-growth* 32)
(defun read-bib-identifier ()
"Read an identifier from *BIB-STREAM*, returning it as a string, or
nil if no identifier could be read."
(if (digit-char-p (peek-char t *bib-stream*))
nil
(let ((s (make-array 0 :element-type 'character :fill-pointer 0 :adjustable t)))
(loop as char = (peek-char nil *bib-stream*)
until (or (whitespace-p char)
(member char '(#\" #\# #\% #\' #\( #\) #\, #\= #\{ #\} )))
do (vector-push-extend (read-char *bib-stream*) s *identifier-growth*))
(if (zerop (length s))
nil
s))))
(defun read-bib-database (stream)
"Read a BibTeX database from STREAM, storing the entries in the
hash-table *BIB-DATABASE* and using/updating the macro hash-table
*BIB-MACROS*."
(let ((*bib-stream* stream))
(loop
;; skip everything up to at-sign
(loop (let ((char (read-char stream nil nil)))
(cond ((not char) (return-from read-bib-database))
((char= char #\@) (return)))))
(catch 'bib-error
(let ((ident (read-bib-identifier)))
(cond
((string-equal ident "COMMENT")
nil) ; do nothing
((string-equal ident "PREAMBLE")
(process-bib-preamble-command))
((string-equal ident "STRING")
(process-bib-string-command))
(t (process-bib-entry-command ident))))))))
(defun scan-balanced-braces (stream right-delimiter)
"Scan STREAM for the RIGHT-DELIMITER character, skipping balanced
pairs of braces. Return a string of everything read, except for the
right delimiter."
(let ((brace-level 0)
(result (make-array 32 :element-type 'character :fill-pointer 0 :adjustable t)))
(loop (let ((char (read-char stream nil nil)))
(cond
((and (char= char right-delimiter)
(zerop brace-level))
(return result))
((char= char #\{)
(incf brace-level))
((char= char #\})
(if (zerop brace-level)
(bib-warn "Unbalanced braces")
(decf brace-level))))
(vector-push-extend char result 32)))))
(defun read-bib-field-token ()
(case (peek-char t *bib-stream*)
((#\{)
(read-char *bib-stream*)
(scan-balanced-braces *bib-stream* #\}))
((#\") ; "
(read-char *bib-stream*)
(scan-balanced-braces *bib-stream* #\")) ; "
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
(loop as char = (peek-char nil *bib-stream*)
while (digit-char-p char)
collecting (read-char *bib-stream*) into list
finally (return (coerce list 'string))))
(otherwise
(let ((macro (read-bib-identifier)))
(unless macro
(bib-error "Expected a string, a number, or a macro name"))
(let ((definition (gethash macro *bib-macros*)))
(cond
((null definition)
(bib-warn "string name \"~A\" is undefined" macro)
"")
(t
definition)))))))
(defvar +bib-whitespace-character-list+
'(#\Newline #\Space #\Linefeed #\Return #\Page #\Tab))
(defvar +bib-sep-character-list+
'(#\~ #\-))
(defun whitespace-p (char)
(member char +bib-whitespace-character-list+))
(defun sepchar-p (char)
(member char +bib-sep-character-list+))
(defun compress-whitespace (s)
"Compress non-null whitespace to a single space."
(let ((whitespace-seen-p nil)
(result (make-array (length s)
:element-type 'character
:fill-pointer 0)))
(loop for char across (the string s)
do (cond ((not (whitespace-p char))
(vector-push char result)
(setq whitespace-seen-p nil))
((not whitespace-seen-p)
(vector-push #\Space result)
(setq whitespace-seen-p t))))
result))
(defun read-bib-field-value (field-p)
"Read a list of field tokens from *BIB-STREAM* that define the field
value string and return the concatenation of all field tokens,
compressing non-null whitespace to a single space. If FIELD-P is
non-nil, remove any leading or trailing whitespace."
(let ((result (read-bib-field-token)))
(loop (if (char= (peek-char t *bib-stream*)
#\#)
(progn
(read-char *bib-stream*)
(setq result (concatenate 'string result (read-bib-field-token))))
(return)))
(if field-p
(string-trim +bib-whitespace-character-list+ (compress-whitespace result))
(compress-whitespace result))))
(defun read-bib-field (field-p)
"Return two values, the name and the value."
(let ((name (read-bib-identifier)))
(unless name
(bib-error "Expected a field name"))
(unless (char= (peek-char t *bib-stream*)
#\=)
(bib-error "Expected `=' sign"))
(read-char *bib-stream*)
(values name (read-bib-field-value field-p))))
(defun process-bib-string-command ()
(let* ((open-char (peek-char t *bib-stream*))
(close-char
(case open-char
(#\{ #\})
(#\( #\))
(otherwise "Expected a `(' or `{' sign"))))
(read-char *bib-stream*)
(multiple-value-bind (name value)
(read-bib-field nil)
(setf (gethash name *bib-macros*)
value))
(unless (char= (peek-char t *bib-stream*)
close-char)
(bib-error "Expected `~A' sign" close-char))))
(defun process-bib-preamble-command ()
(let* ((open-char (peek-char t *bib-stream*))
(close-char
(case open-char
(#\{ #\})
(#\( #\))
(otherwise "Expected a `(' or `{' sign"))))
(read-char *bib-stream*)
(setf *bib-preamble*
(concatenate 'string *bib-preamble*
(read-bib-field-value nil)))
(unless (char= (peek-char t *bib-stream*)
close-char)
(bib-error "Expected `~A' sign" close-char))))
(defstruct bib-entry
(type nil)
(cite-key "")
(sort-key% nil)
(dict (make-hash-table :size 16 :test 'equalp) :read-only t))
(defun bib-entry-ref (key entry &optional default)
(gethash key (bib-entry-dict entry) default))
(defun (setf bib-entry-ref) (value key entry &optional default)
(declare (ignore default))
(when (string= key "SORT.KEY$") (setf (bib-entry-sort-key% entry) nil))
(setf (gethash key (bib-entry-dict entry)) value))
(defvar *generate-sort-key* #'identity)
(defun bib-entry-sort-key (entry)
(or (bib-entry-sort-key% entry)
(setf (bib-entry-sort-key% entry)
(funcall *generate-sort-key* (bib-entry-ref "SORT.KEY$" entry "")))))
(defmethod cmp ((a bib-entry) (b bib-entry))
(cmp (bib-entry-sort-key a) (bib-entry-sort-key b)))
(defmethod hash ((entry bib-entry))
(hash (bib-entry-sort-key entry)))
(defun process-bib-entry-command (entry-type)
(let* ((open-char (peek-char t *bib-stream*))
(close-char
(case open-char
(#\{ #\})
(#\( #\))
(otherwise "Expected a `(' or `{' sign")))
key)
(read-char *bib-stream*)
(peek-char t *bib-stream*)
(loop as char = (read-char *bib-stream* nil #\Newline)
until (or (char= char #\,)
(whitespace-p char))
collecting char into list
finally (if (char= char #\,) (unread-char char *bib-stream*))
(setq key (coerce list 'string)))
(when (gethash key *bib-database*)
(bib-error "Repeated entry---~A" key))
(unless (char= (peek-char t *bib-stream*) #\,)
(bib-error "Expected `,' character"))
(read-char *bib-stream*)
(let ((entry (make-bib-entry)))
(setf (bib-entry-type entry) (string-downcase entry-type))
(setf (bib-entry-cite-key entry) key)
(loop (multiple-value-bind (name value)
(read-bib-field t)
(setf (bib-entry-ref name entry)
value))
(let ((char (peek-char t *bib-stream*)))
(cond
((char= char #\,)
(read-char *bib-stream*)
(when (char= (peek-char t *bib-stream*) close-char)
(read-char *bib-stream*)
(return)))
((char= char close-char)
(read-char *bib-stream*)
(return))
(t (bib-error "Expected `,' or `~A'" close-char)))))
(setf (gethash key *bib-database*) entry))))
;;; Writing BibTeX databases
(defun write-bib-entry (entry &optional (stream *standard-output*))
(format stream "~&@~A{~A"
(bib-entry-type entry)
(bib-entry-cite-key entry))
(loop for field being each hash-key in (bib-entry-dict entry)
and value being each hash-value in (bib-entry-dict entry)
do (format stream ",~% ~A = {~A}" field value))
(format stream "~%}~%"))
#||
(write-bib-entry (gethash "Corput" *bib-database*))
(loop for entry being each hash-value in *bib-database* do
(write-bib-entry entry)) ||#
;;; Computing the cited entries
(defun merge-bib-entries (a b)
"Return a fresh bib entry that merges A and B."
(let ((entry (make-bib-entry)))
(setf (bib-entry-type entry) (bib-entry-type a)
(bib-entry-cite-key entry) (bib-entry-cite-key a))
(loop for key being each hash-key in (bib-entry-dict a)
and value being each hash-value in (bib-entry-dict a)
do (setf (bib-entry-ref key entry) value))
(loop for key being each hash-key in (bib-entry-dict b)
and value being each hash-value in (bib-entry-dict b)
do (unless (bib-entry-ref key entry)
(setf (bib-entry-ref key entry) value)))
entry))
(defun get-merged-bib-entry (key)
"Compute a bib entry where all crossrefs have been merged in."
(labels ((get-entry (key parent-keys)
(let ((entry (gethash key *bib-database*)))
(cond
((not entry)
(bib-warn "I didn't find a database entry for ~A"
key)
nil)
(t
(let ((crossref (bib-entry-ref "CROSSREF" entry)))
(cond
((not crossref)
entry)
((member crossref parent-keys :test 'string-equal)
;; circular cross reference
(bib-warn "I detected a circular cross-reference to ~A"
crossref)
nil)
(t
(let ((crossref-entry
(get-entry crossref (cons key parent-keys))))
(if crossref-entry
(merge-bib-entries entry crossref-entry)
entry))))))))))
(get-entry key '())))
(defun cited-bib-entries (cite-keys &key
(min-crossrefs 2))
"Return a vector of the entries in *BIB-DATABASE* whose keys are
given in the list CITE-KEYS (if CITE-KEYS is the symbol T, return a
vector of all database entries. When a crossref'd entry is referenced
at least :MIN-CROSSREFS times, it is included as a separate entry as
well."
(let ((bib-entries (make-array 0 :adjustable t :fill-pointer 0)))
(cond
((eql cite-keys t)
(loop for key being each hash-key in *bib-database*
do (vector-push-extend (get-merged-bib-entry key) bib-entries 256)))
(t
(let ((crossref-hash (make-hash-table :test 'equalp))
(processed-keys '()))
;; count how many times entries are cross-referenced
(labels ((count-crossrefs (key)
(unless (member key processed-keys :test 'string-equal)
(push key processed-keys)
(let ((entry (gethash key *bib-database*)))
(when entry ; we will issue a warning
; for non-existing keys later
(let ((crossref (bib-entry-ref "CROSSREF" entry)))
(when (and crossref
(not (member crossref cite-keys
:test 'string-equal)))
(setf (gethash crossref crossref-hash)
(+ 1 (gethash crossref crossref-hash 0)))
(count-crossrefs crossref))))))))
(dolist (key cite-keys)
(count-crossrefs key)))
(dolist (key cite-keys)
(let ((entry (get-merged-bib-entry key)))
(when entry
(vector-push-extend entry bib-entries 256))))
(loop for key being each hash-key in crossref-hash
and count being each hash-value in crossref-hash
when (>= count min-crossrefs)
do (let ((entry (get-merged-bib-entry key)))
(when entry
(vector-push-extend entry bib-entries 256)))))))
(coerce bib-entries 'list)))
;;; BibTeX names
(defstruct bibtex-name
"BibTeX name, broken down into its components. Each component is a
list of name tokens (SEP-CHAR TOKEN-STRING)."
first von last jr)
(defvar *bibtex-split-initials* t
"If non-nil, BibTeX understands that there are two abbreviated first
names in names like `Padberg, M.W.'. The original BibTeX 0.99c,
written by Oren Patashnik in the WEB language, thinks that `M.W.' is a
single first name; hence, in abbreviated format, the name becomes
`M. Padberg' instead of `M. W. Padberg'.")
(defvar *bibtex-split-initials-already-warned-hashtable* nil)
(defun tokenize-bibtex-name (name-string &key (start 0) (end nil))
"Break a BibTeX name into name tokens."
(unless end
(setq end (length name-string)))
;; Remove leading whitespace and sepchars
(do ()
((>= start end))
(let ((char (elt name-string start)))
(if (or (whitespace-p char)
(sepchar-p char))
(incf start)
(return))))
;; Remove trailing whitespace, sepchars and commas
(do ()
((>= start end))
(let ((char (elt name-string (- end 1))))
(cond
((or (whitespace-p char)
(sepchar-p char))
(decf end))
((char= char #\,)
(bib-warn "Name has a comma at the end")
(decf end))
(t (return)))))
;; Tokenize
(do ((brace-level 0)
(sep-char nil)
(token-start nil)
(tokens '())
(index start (+ index 1)))
((>= index end)
(if token-start
(setq tokens (cons (cons (or sep-char #\Space)
(subseq name-string token-start index))
tokens)))
(nreverse tokens))
(flet ((current-token () (cons (or sep-char #\Space)
(subseq name-string token-start index))))
(let ((char (elt name-string index)))
(cond
((and (zerop brace-level)
(char= char #\,))
(if token-start
(setq tokens (cons (current-token) tokens)
token-start nil))
(setq sep-char #\,))
((and (zerop brace-level)
(or (whitespace-p char)
(sepchar-p char)))
(if token-start
(setq tokens (cons (current-token) tokens)
token-start nil
sep-char nil))
(if (not sep-char)
(setq sep-char (if (whitespace-p char) #\Space char))))
((and (char= char #\.)
*bibtex-split-initials*
(zerop brace-level)
token-start
(< (1+ index) end)
(let ((next-char (char name-string (1+ index))))
(and (not (whitespace-p next-char))
(not (sepchar-p next-char))
(not (char= next-char #\,)))))
(let ((name (subseq name-string start (or end (length name-string)))))
(unless (gethash name *bibtex-split-initials-already-warned-hashtable*)
(bib-warn "Splitting the initials in the name `~A';~% I suggest you add spaces between initials in the database entry" name)
(setf (gethash name *bibtex-split-initials-already-warned-hashtable*) t)))
(setq tokens (cons (cons (or sep-char #\Space)
(subseq name-string token-start (+ index 1)))
tokens)
token-start nil
sep-char nil)) ; nil sep-char is a weak #\Space
((char= char #\{)
(incf brace-level)
(if (not token-start)
(setq token-start index)))
((char= char #\})
(if (zerop brace-level)
(bib-error "Unbalanced braces")
(decf brace-level))
(if (not token-start)
(setq token-start index)))
(t
(if (not token-start)
(setq token-start index))))))))
(defun von-token-p (token)
;; From the BibTeX source code: "the von name
;; starts with the first nonlast token whose first brace-level-0 letter
;; is in lower case (for the purposes of this determination, an accented
;; or foreign character at brace-level-1 that's in lower case will do, as
;; well)."
(let ((string (cdr token)))
(and (> (length string) 0)
(with-input-from-string (s string)
(let ((brace-level 0))
(loop
for char = (read-char s nil nil)
while char
do (cond ((char= char #\{)
(incf brace-level)
(when (and (= brace-level 1)
(char= (peek-char nil s nil #\Space) #\\))
;; @<Check the special character (and |return|)@>=
(read-char s) ;consume backslash
;; Check whether it is a special character; otherwise,
;; just ignore the control sequence.
(let* ((control-sequence (read-tex-control-sequence s))
(foreign-character (find-foreign-character control-sequence)))
(when foreign-character
(return (lower-case-p (char control-sequence 0)))))
;; It is not a special character, so
;; treat it as an accented character. We
;; now only scan till the end of the
;; brace group; the first alphabetic
;; character decides. If nothing is
;; found within the brace group, decide
;; that is not a "von" token.
(loop
for char = (read-char s nil nil)
while char
while (plusp brace-level)
do (cond ((upper-case-p char)
(return-from von-token-p nil))
((lower-case-p char)
(return-from von-token-p t))
((char= char #\{)
(incf brace-level))
((char= char #\})
(decf brace-level)))
finally (return-from von-token-p nil))))
((plusp brace-level)
(when (char= char #\})
(decf brace-level)))
;; The first alphabetic char at brace-level 0 decides:
((upper-case-p char)
(return nil))
((lower-case-p char)
(return t)))))))))
(defun parse-bibtex-name (name-string &key (start 0) (end nil))
"Break a BibTeX name into its components, returning a BIBTEX-NAME
structure."
(unless end
(setq end (length name-string)))
(let* ((tokens (coerce (tokenize-bibtex-name name-string :start start :end end)
'vector))
(comma-1 (position #\, tokens :key #'car))
(comma-2 (and comma-1
(position #\, tokens :key #'car :start (+ comma-1 1))))
(too-many (and comma-2 (find #\, tokens :key #'car :start (+ comma-2 1)))))
(flet ((token-list (start &optional end)
(unless end (setq end (length tokens)))
(coerce (subseq tokens start end) 'list)))
(when too-many (bib-warn "Too many commas in name"))
(when comma-1 (setf (car (elt tokens comma-1)) #\Space))
(when comma-2 (setf (car (elt tokens comma-2)) #\Space))
(cond
(comma-1
;; format is `von Last, [Jr.,] First', so find out where
;; `von' and `Last' meet
(let* ((von-index
(and (> comma-1 1)
(position-if #'von-token-p tokens :from-end t
:end (- comma-1 1))))
(von-end (if von-index (+ 1 von-index) 0)))
(make-bibtex-name :first (token-list (or comma-2 comma-1))
:von (token-list 0 von-end)
:last (token-list von-end comma-1)
:jr (token-list comma-1 (or comma-2 comma-1)))))
(t
;; format is `First von Last', so find out where these
;; components meet
(let ((von-index (position-if #'von-token-p tokens)))
(if von-index
;; we have a `von' component, so `First' is everything
;; before the first `von', and `Last' is everything
;; after the last `von'.
(let ((right-von-index (position-if #'von-token-p tokens :from-end t)))
(make-bibtex-name :first (token-list 0 von-index)
:von (token-list von-index (+ right-von-index 1))
:last (token-list (+ right-von-index 1))))
;; we have no `von' component, so `Last' consists of
;; all connected tokens at the end.
(let ((last-start (position-if #'(lambda (token)
(or (char= (car token) #\~)
(not (sepchar-p (car token)))))
tokens :from-end t)))
(make-bibtex-name :first (token-list 0 (or last-start 0))
:last (token-list (or last-start 0)))))))))))
(defun find-and-at-brace-level-0 (string &key (start 0) (end nil))
"Return the index of the first `and' surrounded by non-null
whitespace at brace level 0 in STRING, bounded by :START and :END. If
none found, return nil."
(unless end
(setq end (length string)))
(do ((brace-level 0)
(preceding-white nil (whitespace-p (elt string index)))
(index start (+ 1 index)))
((>= index end) nil)
(case (elt string index)
(#\a (if (and (< (+ index 3) end)
(zerop brace-level)
preceding-white
(string-equal "and" string :start2 index :end2 (+ index 3))
(whitespace-p (elt string (+ index 3))))
(return-from find-and-at-brace-level-0 index)))
(#\{ (incf brace-level))
(#\} (if (zerop brace-level)
(bib-warn "Unbalanced braces")
(decf brace-level))))))
(defun parse-bibtex-name-list (names-string)
"Parse a string containing BibTeX names, separated by the word `and'
surrounded by non-null whitespace, and return a list of BIBTEX-NAME
structures."
(if (every #'whitespace-p names-string)
'()
(do ((start 0)
(name-list '()))
(nil)
(let ((index (find-and-at-brace-level-0 names-string :start start)))
(setq name-list (cons (parse-bibtex-name names-string :start start :end index) name-list))
(if index
(setq start (+ index 4))
(return (nreverse name-list)))))))
(defvar *bibtex-long-token-length* 3
"A BibTeX name token is considered `long' when it has at least this
many text characters.")
(defvar *bibtex-long-name-length* 3
"A BibTeX name component is considered `long' when it has at least this
many text characters.")
(defun enough-text-chars (string min-length)
;; FIXME: Handle special characters (418)
(>= (length string) min-length))
(defun format-bibtex-name-component (stream stream-string
tokens full inter-token-string)
;; From the BibTeX documentation:
;; A tie is the default space character between the last two tokens of
;; the name part, and between the first two tokens if the first token is
;; short enough; otherwise, a space is the default.
;;
;; CL-BibTeX remark: We note that BibTeX treats initial literal
;; characters in a level-1 brace group as belonging to the first
;; name token. That is:
;;
;; "C. A. J. Foooo" #1 "{ff}" format.name$ write$ newline$
;; ==> C.~A.~J.
;; "C. A. J. Foooo" #1 "{ll}, {ff}" format.name$ write$ newline$
;; ==> Foooo, C.~A.~J.
;; "C. A. J. Foooo" #1 "{ll}{, ff}" format.name$ write$ newline$
;; ==> Foooo, C. A.~J.
;;
;; In the last example, ", C." is the first token, so that it is long enough, so it is not connected with a tie!
;;
;; This might be a bug in BibTeX, but we mimic this behaviour in
;; CL-BibTeX as well.
;;
(do ((tokens tokens (cdr tokens))
(token-index 0 (+ token-index 1)))
((null tokens))
(let ((token (car tokens))
(*print-pretty* nil))
(unless (zerop token-index)
(cond
(inter-token-string
(princ inter-token-string stream))
(t
(unless full (princ #\. stream))
(cond
((sepchar-p (car token))
(princ (car token) stream))
((null (cdr tokens)) ; last token
(princ #\~ stream))
((not (enough-text-chars stream-string
*bibtex-long-token-length*))
(princ #\~ stream))
(t
(princ #\Space stream))))))
(cond
(full
(princ (cdr token) stream))
(t ;; Abbreviate
(write-tex-group (list (first (parse-tex-string (cdr token))))
stream))))))
(defun format-bibtex-name (stream format-string bibtex-name)
(let ((*print-pretty* nil)
(string-output nil)
(end (length format-string)))
(cond
((null stream) (setq stream (make-string-output-stream)
string-output t))
((eq stream t) (setq stream *standard-output*)))
(do ((index 0))
((>= index end))
(let ((c (char format-string index)))
(cond
((char= c #\{)
(incf index)
(let ((string (make-array 0
:element-type 'character
:adjustable t
:fill-pointer 0))
(any-output t))
(with-output-to-string (s string)
(do ((brace-level 1))
((or (>= index end)
(= brace-level 0)))
(setq c (char format-string index))
(incf index)
(cond ((and (alpha-char-p c)
(= brace-level 1))
(let* ((tokens
(case (char-upcase c)
(#\F (bibtex-name-first bibtex-name))
(#\V (bibtex-name-von bibtex-name))
(#\L (bibtex-name-last bibtex-name))
(#\J (bibtex-name-jr bibtex-name))
(otherwise
(error "The format string ~S has an illegal brace-level-1 letter"
format-string))))
(double-letter
(and (< index end)
(char-equal c (char format-string index))))
(inter-token-string nil))
(when double-letter (incf index))
(when (null tokens)
(setq any-output nil))
(when (and (< index end)
(char= #\{ (char format-string index)))
;; Get inter-token string
(incf brace-level)
(do ((i (+ index 1) (+ i 1)))
((or (= brace-level 1) (>= i end))
(setq inter-token-string (subseq format-string
(+ index 1) (- i 1))
index i))
(case (char format-string i)
(#\{ (incf brace-level))
(#\} (if (zerop brace-level)
(error "Unbalanced braces in BibTeX format string ~S" format-string)
(decf brace-level))))))
(format-bibtex-name-component s string tokens
double-letter inter-token-string)))
((char= c #\{)
(incf brace-level)
(princ c s))
((char= c #\})
(if (zerop brace-level)
(error "Unbalanced braces in BibTeX format string ~S" format-string)
(decf brace-level))
(unless (zerop brace-level)
(princ c s)))
(t (princ c s)))))
(when any-output
(when (and (>= (length string) 1)
(char= (char string (- (length string) 1)) #\~))
;; Handle a discretionary tie
(cond
((and (>= (length string) 2)
(char= (char string (- (length string) 2)) #\~))
;; double tie, so remove one
(decf (fill-pointer string)))
((not (enough-text-chars string (+ *bibtex-long-name-length* 1)))
;; too short, keep the tie
nil)
(t
(setf (char string (- (length string) 1)) #\Space))))
(princ string stream))))
((char= c #\})
(error "Unbalanced braces in BibTeX format string ~A" format-string))
(t
(princ c stream)
(incf index)))))
(when string-output
(get-output-stream-string stream))))
(defun format-nth-bibtex-name (stream format-string names-string index)
"Parse NAMES-STRING as an `and'-separated list of BibTeX names, pick
the name of given 1-based INDEX and format it to STREAM according to
the BibTeX-style FORMAT-STRING."
(unless (> index 0)
(bib-warn "Bad index: ~A" index)
(return-from format-nth-bibtex-name ""))
(let ((bibtex-names (parse-bibtex-name-list names-string)))
(when (> index (length bibtex-names))
(if (zerop (length bibtex-names))
(bib-warn "There is no name in ~S" names-string)
(bib-warn "There aren't ~A names in ~S" index names-string))
(return-from format-nth-bibtex-name ""))
(format-bibtex-name stream format-string (elt bibtex-names (- index 1)))))
(defun num-bibtex-names (names-string)
(length (parse-bibtex-name-list names-string)))
;;; Reading the AUX files
(defvar *aux-file-commands*
'(("citation" . aux-citation-command)
("bibdata" . aux-bibdata-command)
("bibstyle" . aux-bibstyle-command)
("@input" . aux-input-command)))
;; Variables used during READ-AUX-FILE
(defvar *citation-seen-p* nil "Non-nil if a \citation command has been seen in an AUX file.")
(defvar *bibdata-seen-p* nil "Non-nil if a \bibdata command has been seen in an AUX file.")
(defvar *aux-stream* nil "The stream corresponding to the current AUX file.")
;; The results of READ-AUX-FILE
(defvar *bib-style* nil "The requested BibTeX style.")
(defvar *bib-files* '()
"List of BibTeX database files to be read.")
(defvar *cite-all-entries* nil
"Non-nil if all BibTeX entries are cited.")
(defvar *cite-keys* '()
"List of cited BibTeX keys.")
(defun aux-error (format-control &rest args)
(apply #'format *error-output* format-control args)
(mark-error)
(throw 'aux-error nil))
(defun tex-alpha-char-p (char &key (at-is-letter nil))
(or (alpha-char-p char)
(and at-is-letter (char= char #\@))))
(defun read-tex-control-sequence (stream &key (skip-whitespace t)
(at-is-letter nil))
"Read a TeX control sequence from STREAM, assuming that the escape
character (\\) has already been read. In the case of a control word,
trailing whitespace is flushed if :SKIP-WHITESPACE is non-nil."
(let ((char (read-char stream nil #\Space)))
(if (tex-alpha-char-p char :at-is-letter at-is-letter)
(let ((result (make-array 1 :element-type 'character
:fill-pointer t :adjustable t
:initial-element char)))
(loop for char = (peek-char nil stream nil #\Space)
while (tex-alpha-char-p char :at-is-letter at-is-letter)
do (vector-push-extend (read-char stream) result 32))
(when skip-whitespace
(peek-char t stream nil nil))
result)
(string char))))
(defun get-aux-command-and-process ()
"Read a TeX control sequence from *AUX-STREAM*. If the sequence is
found in *AUX-FILE-COMMANDS*, call the associated function."
(let* ((ctl (read-tex-control-sequence *aux-stream*
:skip-whitespace nil
:at-is-letter t))
(command (assoc ctl *aux-file-commands* :test 'string=)))
(when command
(if (catch 'aux-error
(funcall (cdr command))
t)
(let ((line-end (read-line *aux-stream* nil "")))
(unless (every #'whitespace-p line-end)
(format *error-output* "~&Trailing garbage after AUX-file command: `~A'~%"
line-end)))
(progn
(format *error-output* "~&I'm skipping whatever remains of this command~%")
(read-line *aux-stream* nil ""))))))
(defvar *aux-file-level* 0)
(defun read-aux-file-recursively (name)
(let ((full-name (kpathsea:find-file name)))
(unless full-name
(bib-fatal "I couldn't find auxiliary file: ~S" name))
(with-open-file (*aux-stream* full-name :if-does-not-exist nil)
(unless *aux-stream*
(bib-fatal "I couldn't open auxiliary file: ~S" name))
(if (zerop *aux-file-level*)
(format *error-output* "~&The top-level auxiliary file: ~A~%" full-name)
(format *error-output* "~&A level-~D auxiliary file: ~A~%" *aux-file-level* full-name))
(loop as char = (peek-char nil *aux-stream* nil nil)
while char
do (cond
((char= char #\\)
(read-char *aux-stream*)
(get-aux-command-and-process))
(t (read-line *aux-stream*)))))))
(defun read-aux-file (name)
"Read an AUX file, modifying *CITE-KEYS*, *CITE-ALL-ENTRIES*,
*BIB-FILES*, and *BIB-STYLE*."
(let ((*citation-seen-p* nil)
(*bibdata-seen-p* nil)
(*aux-file-level* 0))
(read-aux-file-recursively name)
;; check everything ok
(flet ((aux-end-error (what)
(format *error-output* "~&I found no ~A while reading the AUX file~%" what)
(mark-error)))
(unless *citation-seen-p*
(aux-end-error "\\citation commands"))
(unless *bibdata-seen-p*
(aux-end-error "\\bibdata command"))
(unless *bib-style*
(aux-end-error "\\bibstyle command")))
(setq *bib-files* (nreverse *bib-files*)
*cite-keys* (nreverse *cite-keys*))))
(defun aux-input-command ()
"Process an AUX-file \\@input command."
(unless (char= (read-char *aux-stream* nil #\Space) #\{)
(aux-error "Expected `{'"))
(let ((file-name (scan-balanced-braces *aux-stream* #\}))
(*aux-file-level* (1+ *aux-file-level*)))
(read-aux-file-recursively file-name)))
(defun aux-bibstyle-command ()
"Process an AUX-file \\bibstyle command."
(when *bib-style*
(aux-error "Illegal, another \\bibstyle command"))
(unless (char= (read-char *aux-stream* nil #\Space) #\{)
(aux-error "Expected `{'"))
(setq *bib-style* (scan-balanced-braces *aux-stream* #\})))
(defun scan-to-delimiter (stream delimiters)
"Read characters from STREAM until a character in the list
DELIMITERS is found. Return a string of these characters, excluding
the delimiter, which is left in the stream."
(let ((s (make-array 0 :element-type 'character
:adjustable t :fill-pointer t)))
(loop as char = (peek-char nil stream nil nil)
until (or (null char)
(member char delimiters))
do (vector-push-extend (read-char stream) s 64))
s))
(defun aux-bibdata-command ()
(when *bibdata-seen-p*
(aux-error "Illegal, another \\bibdata command"))
(setq *bibdata-seen-p* t)
(unless (char= (read-char *aux-stream* nil #\Space) #\{)
(aux-error "Expected `{'"))
(loop (let ((data (scan-to-delimiter *aux-stream* '(#\, #\}))))
(push data *bib-files*)
(unless (char= (read-char *aux-stream* nil #\Space) #\,)
(return)))))
(defun aux-citation-command ()
(setq *citation-seen-p* t)
(unless (char= (read-char *aux-stream* nil #\Space) #\{)
(aux-error "Expected `{'"))
(loop (let ((key (scan-to-delimiter *aux-stream* '(#\, #\}))))
(cond
((string= key "*")
(when *cite-all-entries*
(aux-error "Multiple inclusions of entire database"))
(setq *cite-all-entries* t))
(t
;; fixme: detect duplicates
(unless (member key *cite-keys* :test 'string=)
(push key *cite-keys*))))
(unless (char= (read-char *aux-stream* nil #\Space) #\,)
(return)))))
;;; Writing the BBL file