summaryrefslogtreecommitdiff
path: root/lisp/textmodes/bibtex.el
blob: 575da9418baf982fc23bfc73f292c554a969297e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
;;; bibtex.el --- BibTeX mode for GNU Emacs

;; Copyright (C) 1992, 1994, 1995 Free Software Foundation, Inc.

;; Author: Stefan Schoef <schoef@informatik.uni-oldenburg.de>
;;      Bengt Martensson <ubrinf!mond!bengt>
;;	Mark Shapiro <shapiro@corto.inria.fr>
;;	Mike Newton <newton@gumby.cs.caltech.edu>
;;	Aaron Larson <alarson@src.honeywell.com>
;; Maintainer: Stefan Schoef <schoef@informatik.uni-oldenburg.de>
;; Keywords: BibTeX, LaTeX, TeX

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:

;;  Major mode for editing and validating BibTeX files.

;;  Usage:
;;  See documentation for function bibtex-mode (or type "\M-x describe-mode"
;;  when you are in bibtex-mode).

;;  Todo:
;;  Distribute texinfo file.

;;  Known Bugs:
;;   1. using regular expressions to match the entire BibTeX entry dies
;;      on long entries (e.g. those containing abstracts) since
;;      the length of regular expression matches is fairly limited.
;;   2. Calling bibtex-find-text in a string entry results in the
;;      error message "Can't find enclosing Bibtex field" instead of
;;      moving to the empty string. [reported by gernot@cs.unsw.oz.au]
;;   3. Quotes inside quote-parenthesized fields (like
;;      `author = "Stefan Sch{\"o}f"') break bibtex-validate-buffer.
;;      Further, you must use braces here, if you want to set
;;      bibtex-maintain-sorted-entries to a non-nil value.

;; (current keeper: schoef@informatik.uni-oldenburg.de
;;  previous: alarson@src.honeywell.com)

;;; Code:

;; User Options:

(defvar bibtex-field-left-delimiter "{"
  "*Set this to { or \" according to your personal preferences.
This variable is buffer local.")
(make-variable-buffer-local 'bibtex-field-left-delimiter)

(defvar bibtex-field-right-delimiter "}"
  "*Set this to } or \" according to your personal preferences.
This variable is buffer local.")
(make-variable-buffer-local 'bibtex-field-right-delimiter)

(defvar bibtex-include-OPTcrossref '("InProceedings" "InCollection")
  "*All entries listed here will have an OPTcrossref field.")

(defvar bibtex-include-OPTkey t
  "*If non-nil, all entries will have an OPTkey field.")

(defvar bibtex-include-OPTannote t
  "*If non-nil, all entries will have an OPTannote field.")

(defvar bibtex-mode-user-optional-fields nil
  "*List of optional fields the user wants to have always present.
Entries should be lists of strings with two elements (first element =
name of the field, second element = comment to appear in the echo area).")

(defvar bibtex-clean-entry-zap-empty-opts t
  "*If non-nil, bibtex-clean-entry will delete all empty optional fields.")

(defvar bibtex-sort-ignore-string-entries t
  "*If non-nil, BibTeX @STRING entries are not sort-significant.
That means they are ignored when determining ordering of the buffer
(e.g. sorting, locating alphabetical position for new entries, etc.).
This variable is buffer local.")
(make-variable-buffer-local 'bibtex-sort-ignore-string-entries)

(defvar bibtex-maintain-sorted-entries nil
  "*If non-nil, bibtex-mode maintains all BibTeX entries in sorted order.
Setting this variable to nil will strip off some comfort (e.g. TAB
completion for reference keys in minibuffer, automatic detection of
duplicates) from bibtex-mode. See also bibtex-sort-ignore-string-entries.
This variable is buffer local.")
(make-variable-buffer-local 'bibtex-maintain-sorted-entries)

(defvar bibtex-entry-field-alist
  '(
    ("Article" . (((("author" "Author1 [and Author2 ...] [and others]")
                    ("title" "Title of the article (BibTeX converts it to lowercase)")
                    ("journal" "Name of the journal (use string, remove braces)")
                    ("year" "Year of publication"))
		   (("volume" "Volume of the journal")
                    ("number" "Number of the journal")
                    ("month" "Month of the publication as a string (remove braces)")
                    ("pages" "Pages in the journal")
                    ("note" "Remarks to be put at the end of the \\bibitem")))
		  ((("author" "Author1 [and Author2 ...] [and others]")
                    ("title" "Title of the article (BibTeX converts it to lowercase)"))
		   (("journal" "Name of the journal (use string, remove braces)") 
                    ("year" "Year of publication")
                    ("volume" "Volume of the journal")
                    ("number" "Number of the journal")
		    ("month" "Month of the publication as a string (remove braces)")
                    ("pages" "Pages in the journal")
                    ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("Book" . (((("author" "Author1 [and Author2 ...] [and others]")
                 ("title" "Title of the book")
                 ("publisher" "Publishing company")
                 ("year" "Year of publication"))
		(("editor" "Editor1 [and Editor2 ...] [and others]")
                 ("volume" "Volume of the book in the series")
                 ("number" "Number of the book in a small series (overwritten by volume)")
                 ("series" "Series in which the book appeared")
                 ("address" "Address of the publisher")
		 ("edition" "Edition of the book as a capitalized English word")
                 ("month" "Month of the publication as a string (remove braces)")
                 ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("Booklet" . (((("title" "Title of the booklet (BibTeX converts it to lowercase)"))
		   (("author" "Author1 [and Author2 ...] [and others]")
                    ("howpublished" "The way in which the booklet was published")
                    ("address" "Address of the publisher")
                    ("year" "Year of publication")
                    ("month" "Month of the publication as a string (remove braces)")
                    ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("InBook" . (((("author" "Author1 [and Author2 ...] [and others]")
                   ("title" "Title of the book")
                   ("chapter" "Chapter in the book")
                   ("publisher" "Publishing company")
                   ("year" "Year of publication"))
		  (("editor" "Editor1 [and Editor2 ...] [and others]")
                   ("volume" "Volume of the book in the series")
                   ("number" "Number of the book in a small series (overwritten by volume)")
                   ("series" "Series in which the book appeared")
                   ("address" "Address of the publisher")
		   ("edition" "Edition of the book as a capitalized English word")
                   ("month" "Month of the publication as a string (remove braces)")
                   ("pages" "Pages in the book")
                   ("type" "Word to use instead of \"chapter\"")
                   ("note" "Remarks to be put at the end of the \\bibitem")))
		 ((("author" "Author1 [and Author2 ...] [and others]")
                   ("title" "Title of the book")
                   ("chapter" "Chapter in the book"))
		  (("publisher" "Publishing company")
                   ("year" "Year of publication")
                   ("editor" "Editor1 [and Editor2 ...] [and others]")
                   ("volume" "Volume of the book in the series")
                   ("number" "Number of the book in a small series (overwritten by volume)")
		   ("series" "Series in which the book appeared")
                   ("address" "Address of the publisher")
                   ("edition" "Edition of the book as a capitalized English word")
                   ("month" "Month of the publication as a string (remove braces)")
                   ("pages" "Pages in the book")
                   ("type" "Word to use instead of \"chapter\"")
                   ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("InCollection" . (((("author" "Author1 [and Author2 ...] [and others]")
                         ("title" "Title of the article in book (BibTeX converts it to lowercase)")
			 ("booktitle" "Name of the book")
                         ("publisher" "Publishing company")
                         ("year" "Year of publication"))
			(("editor" "Editor1 [and Editor2 ...] [and others]")
                         ("volume" "Volume of the book in the series")
                         ("number" "Number of the book in a small series (overwritten by volume)")
                         ("series" "Series in which the book appeared")
                         ("chapter" "Chapter in the book")
                         ("type" "Word to use instead of \"chapter\"")
                         ("address" "Address of the publisher")
                         ("edition" "Edition of the book as a capitalized English word")
                         ("month" "Month of the publication as a string (remove braces)")
			 ("pages" "Pages in the book")
                         ("note" "Remarks to be put at the end of the \\bibitem")))
		       ((("author" "Author1 [and Author2 ...] [and others]")
                         ("title" "Title of the article in book (BibTeX converts it to lowercase)")
                         ("booktitle" "Name of the book"))
			(("publisher" "Publishing company")
                         ("year" "Year of publication")
			 ("editor" "Editor1 [and Editor2 ...] [and others]")
                         ("volume" "Volume of the book in the series")
                         ("number" "Number of the book in a small series (overwritten by volume)")
                         ("series" "Series in which the book appeared")
                         ("chapter" "Chapter in the book")
                         ("type" "Word to use instead of \"chapter\"")
                         ("address" "Address of the publisher")
                         ("edition" "Edition of the book as a capitalized English word")
                         ("month" "Month of the publication as a string (remove braces)")
			 ("pages" "Pages in the book")
                         ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("InProceedings" . (((("author" "Author1 [and Author2 ...] [and others]")
                          ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)")
                          ("booktitle" "Name of the conference proceedings")
                          ("year" "Year of publication"))
			 (("editor" "Editor1 [and Editor2 ...] [and others]")
                          ("volume" "Volume of the conference proceedings in the series")
                          ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
                          ("series" "Series in which the conference proceedings appeared")
			  ("organization" "Sponsoring organization of the conference")
                          ("publisher" "Publishing company, its location")
                          ("address" "Location of the Proceedings")
                          ("month" "Month of the publication as a string (remove braces)")
                          ("pages" "Pages in the conference proceedings")
                          ("note" "Remarks to be put at the end of the \\bibitem")))
			((("author" "Author1 [and Author2 ...] [and others]")
                          ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)")
			  ("booktitle" "Name of the conference proceedings"))
			 (("editor" "Editor1 [and Editor2 ...] [and others]")
                          ("volume" "Volume of the conference proceedings in the series")
                          ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
                          ("series" "Series in which the conference proceedings appeared")
                          ("year" "Year of publication")
			  ("organization" "Sponsoring organization of the conference")
                          ("publisher" "Publishing company, its location")
                          ("address" "Location of the Proceedings")
                          ("month" "Month of the publication as a string (remove braces)")
                          ("pages" "Pages in the conference proceedings")
                          ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("Manual" . (((("title" "Title of the manual"))
		  (("author" "Author1 [and Author2 ...] [and others]")
                   ("organization" "Publishing organization of the manual")
                   ("address" "Address of the organization")
                   ("edition" "Edition of the manual as a capitalized English word")
                   ("year" "Year of publication")
		   ("month" "Month of the publication as a string (remove braces)")
                   ("note" "Remarks to be put at the end of the \\bibitem")))))

    ("MastersThesis" . (((("author" "Author1 [and Author2 ...] [and others]")
                          ("title" "Title of the master\'s thesis (BibTeX converts it to lowercase)")
                          ("school" "School where the master\'s thesis was written")
                          ("year" "Year of publication"))
			 (("address" "Address of the school (if not part of field \"school\") or country")
                          ("type" "Type of the master\'s thesis")
                          ("month" "Month of the publication as a string (remove braces)")
                          ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("Misc" . ((()
		(("author" "Author1 [and Author2 ...] [and others]")
                 ("title" "Title of the reference (BibTeX converts it to lowercase)")
                 ("howpublished" "The way in which the reference was published")
                 ("year" "Year of publication")
                 ("month" "Month of the publication as a string (remove braces)")
                 ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("PhdThesis" . (((("author" "Author1 [and Author2 ...] [and others]")
                      ("title" "Title of the PhD. thesis")
                      ("school" "School where the PhD. thesis was written")
                      ("year" "Year of publication"))
		     (("address" "Address of the school (if not part of field \"school\") or country")
                      ("type" "Type of the PhD. thesis")
                      ("month" "Month of the publication as a string (remove braces)")
                      ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("Proceedings" . (((("title" "Title of the conference proceedings")
                        ("year" "Year of publication"))
		       (("editor" "Editor1 [and Editor2 ...] [and others]")
                        ("volume" "Volume of the conference proceedings in the series")
                        ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
                        ("series" "Series in which the conference proceedings appeared")
                        ("publisher" "Publishing company, its location")
			("organization" "Sponsoring organization of the conference")
                        ("address" "Location of the Proceedings")
                        ("month" "Month of the publication as a string (remove braces)")
                        ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("TechReport" . (((("author" "Author1 [and Author2 ...] [and others]")
                       ("title" "Title of the technical report (BibTeX converts it to lowercase)")
                       ("institution" "Sponsoring institution of the report")
                       ("year" "Year of publication"))
		      (("type" "Type of the report (if other than \"technical report\")")
                       ("number" "Number of the technical report")
                       ("address" "Address of the institution (if not part of field \"institution\") or country")
                       ("month" "Month of the publication as a string (remove braces)")
                       ("note" "Remarks to be put at the end of the \\bibitem")))))
    ("Unpublished" . (((("author" "Author1 [and Author2 ...] [and others]")
                        ("title" "Title of the unpublished reference (BibTeX converts it to lowercase)")
                        ("note" "Remarks to be put at the end of the \\bibitem"))
		       (("year" "Year of publication")
                        ("month" "Month of the publication as a string (remove braces)")))))
    )

  "Defines reference types and their associated fields.
List of
(entry-name (required optional) (crossref-required crossref-optional))
triples.
If the third element is nil, the first pair is always to be used.
If not, the second pair is to be used in the case of presence of a
crossref field and the third in the case of absence.
Required , optional, crossref-required and crossref-optional are lists. 
Each element of these lists is a list of strings with two elements
(first element  = name of the field, 
 second element = comment to appear in the echo area).")

(defvar bibtex-predefined-strings
  '(
    ("jan") ("feb") ("mar") ("apr") ("may") ("jun") ("jul") ("aug")
    ("sep") ("oct") ("nov") ("dec")
    ("acmcs") ("acta") ("cacm") ("ibmjrd") ("ibmsj") ("ieeese")
    ("ieeetc") ("ieeetcad") ("ipl") ("jacm") ("jcss") ("scp")
    ("sicomp") ("tcs") ("tocs") ("tods") ("tog") ("toms") ("toois")
    ("toplas")
    )
  "Alist of string definitions.
Should contain the strings defined in the BibTeX style files. Each
element is a list with just one element: the string.")

(defvar bibtex-string-files nil
  "*List of BibTeX files containing string definitions.
Those files must be specified using pathnames relative to the
directories specified in $BIBINPUTS. This variable is only evaluated
when bibtex-mode is entered (i. e. when loading the BibTeX file).")

(defvar bibtex-help-message t
  "*If not nil print help messages in the echo area on entering a new field.")

(defvar bibtex-autokey-names 1
  "*Number of names to use for the automatically generated reference key.
If this is set to anything but a number, all names are used.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-name-change-strings
  '(("\\\\\\\"a" "ae") ("\\\\\\\"o" "oe") ("\\\\\\\"u" "ue")
    ("\\\\\\\"s" "ss")
    ("\\\\\\\"A" "Ae") ("\\\\\\\"O" "Oe") ("\\\\\\\"U" "Ue")
    ("{" "") ("}" ""))
  "Alist of (old-regexp new-string) pairs.
Any part of name matching a old-regexp is replaced by new-string.
Case of the old-regexp is significant. All regexps are tried in the
order in which they appear in the list, so be sure to avoid recursion here.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-name-length 'infty
  "*Number of characters from name to incorporate into key.
If this is set to anything but a number, all characters are used.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-name-separator ""
  "*String that comes between any two names in the key.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-year-length 2
  "*Number of rightmost digits from the year field yo incorporate into key.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-titlewords 5
  "*Number of title words to use for the automatically generated reference key.
If this is set to anything but a number, all title words are used.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-title-terminators
  '("\\." "!"  "\\?" ":" ";" "---")
  "*Regexp list defining the termination of the main part of the title.
Case of the regexps is ignored.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-titlewords-stretch 2
  "*Number of words that can additionally be used from the title.
These words are used only, if a sentence from the title can be ended then.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-titleword-first-ignore
  '("a" "an" "on" "the" "eine?" "der" "die" "das")
  "*Determines words that may begin a title but are not to be used in the key.
Each item of the list is a regexp. If the first word of the title matchs a
regexp from that list, it is not included in the title, even if it is
capitalized. Regexps in the list must be entered using lowercase letters.")

(defvar bibtex-autokey-titleword-abbrevs nil
  "*Determines exceptions to the usual abbreviation mechanism.
A list of (old-regexp new-string) pairs. 
Use all lowercase letters for old-regexp.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-titleword-change-strings
  '(("\\\\\\\"a" "ae") ("\\\\\\\"o" "oe") ("\\\\\\\"u" "ue")
    ("\\\\\\\"s" "ss")
    ("\\\\\\\"A" "Ae") ("\\\\\\\"O" "Oe") ("\\\\\\\"U" "Ue")
    ("{" "") ("}" ""))
  "Alist of (old-regexp new-string) pairs.
Any part of title word matching a old-regexp is replaced by new-string.
Case of the old-regexp is significant.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-titleword-length 5
  "*Number of characters from title words to incorporate into key.
If this is set to anything but a number, all characters are used.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-titleword-separator "_"
  "*String to be put between the title words.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-name-year-separator ""
  "*String to be put between name part and year part of key.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-year-title-separator ":_"
  "*String to be put between name part and year part of key.
See the documentation of function bibtex-generate-autokey for further detail.")

(defvar bibtex-autokey-edit-before-use t
  "*If non-nil, user is allowed to edit the generated key before it is used.")

(defvar bibtex-font-lock-keywords
  (list
   '("\\(^@\\sw+\\)[ \t]*[({][ \t]*\\([^ \t\n,]*\\)"
     (1 font-lock-keyword-face) (2 font-lock-reference-face))
   ;; reference type and reference label
   '("^[ \t]*\\(OPT\\sw+\\)[ \t]*="
     1 font-lock-comment-face)
   ;; optional field names (treated as comments)
   '("^[ \t]*\\(\\sw+\\)[ \t]*="
     1 font-lock-variable-name-face)
   ;; field names
   )
  "*Default expressions to highlight in BibTeX mode.")

;; Syntax Table, Keybindings and BibTeX Entry List
(defvar bibtex-mode-syntax-table
  (let ((st (make-syntax-table)))
    ;; [alarson:19920214.1004CST] make double quote a string quote
    (modify-syntax-entry ?\" "\"" st)
    (modify-syntax-entry ?$ "$$  " st)
    (modify-syntax-entry ?% "<   " st)
    (modify-syntax-entry ?'  "w   " st)
    (modify-syntax-entry ?@  "w   " st)
    (modify-syntax-entry ?\\ "\\" st)
    (modify-syntax-entry ?\f ">   " st)
    (modify-syntax-entry ?\n ">   " st)
    (modify-syntax-entry ?~ " " st)
    st))

(defvar bibtex-mode-map
  (let ((km (make-sparse-keymap)))
    
    (define-key km "\t" 'bibtex-find-text)
    (define-key km "\n" 'bibtex-next-field)
    (define-key km "\M-\t" 'bibtex-complete-string)
    (define-key km "\C-c\"" 'bibtex-remove-double-quotes-or-braces)
    (define-key km "\C-c{" 'bibtex-remove-double-quotes-or-braces)
    (define-key km "\C-c}" 'bibtex-remove-double-quotes-or-braces)
    (define-key km "\C-c\C-c" 'bibtex-clean-entry)
    (define-key km "\C-c?" 'bibtex-print-help-message)
    (define-key km "\C-c\C-p" 'bibtex-pop-previous)
    (define-key km "\C-c\C-n" 'bibtex-pop-next)
    (define-key km "\C-c\C-k" 'bibtex-kill-optional-field)
    (define-key km "\C-c\C-d" 'bibtex-empty-field)
    (define-key km "\C-c$"   'bibtex-ispell-entry)
    (define-key km "\M-\C-a"   'bibtex-beginning-of-entry)
    (define-key km "\M-\C-e"   'bibtex-end-of-entry)
    (define-key km "\C-c\C-b"   'bibtex-entry)
    (define-key km "\C-c\C-q" 'bibtex-hide-entry-bodies)
    (define-key km "\C-c\C-rn" 'bibtex-narrow-to-entry)
    (define-key km "\C-c\C-rw" 'widen)
    (define-key km "\C-c\C-o" 'bibtex-remove-OPT)

    (define-key km "\C-c\C-e\C-i" 'bibtex-InProceedings)
    (define-key km "\C-c\C-ei" 'bibtex-InCollection)
    (define-key km "\C-c\C-eI" 'bibtex-InBook)
    (define-key km "\C-c\C-e\C-a" 'bibtex-Article)
    (define-key km "\C-c\C-e\C-b" 'bibtex-InBook)
    (define-key km "\C-c\C-eb" 'bibtex-Book)
    (define-key km "\C-c\C-eB" 'bibtex-Booklet)
    (define-key km "\C-c\C-e\C-c" 'bibtex-InCollection)
    (define-key km "\C-c\C-e\C-m" 'bibtex-Manual)
    (define-key km "\C-c\C-em" 'bibtex-MastersThesis)
    (define-key km "\C-c\C-eM" 'bibtex-Misc)
    (define-key km "\C-c\C-e\C-p" 'bibtex-InProceedings)
    (define-key km "\C-c\C-ep" 'bibtex-Proceedings)
    (define-key km "\C-c\C-eP" 'bibtex-PhdThesis)
    (define-key km "\C-c\C-e\M-p" 'bibtex-preamble)
    (define-key km "\C-c\C-e\C-s" 'bibtex-string)
    (define-key km "\C-c\C-e\C-t" 'bibtex-TechReport)
    (define-key km "\C-c\C-e\C-u" 'bibtex-Unpublished)
    km))

(define-key bibtex-mode-map [menu-bar bibtex-edit]
  (cons "BibTeX-Edit" (make-sparse-keymap "BibTeX-Edit")))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-print-help-message]
  '("Help about Current Field" . bibtex-print-help-message))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-complete-string]
  '("String Complete" . bibtex-complete-string))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-next-field]
  '("Next Field" . bibtex-next-field))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-find-text]
  '("End of Field" . bibtex-find-text))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-pop-previous]
  '("Snatch from Similar Preceding Field" . bibtex-pop-previous))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-pop-next]
  '("Snatch from Similar Following Field" . bibtex-pop-next))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-remove-OPT]
  '("Remove OPT" . bibtex-remove-OPT))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-remove-double-quotes-or-braces]
  '("Remove Quotes or Braces" . bibtex-remove-double-quotes-or-braces))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-clean-entry]
  '("Clean Up Entry" . bibtex-clean-entry))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-sort-entries]
  '("Sort Entries" . bibtex-sort-entries))
(define-key bibtex-mode-map [menu-bar bibtex-edit bibtex-validate-buffer]
  '("Validate Entries" . bibtex-validate-buffer))

(define-key bibtex-mode-map [menu-bar entry-types]
  (cons "Entry-Types" (make-sparse-keymap "Entry-Types")))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-preamble]
  '("Preamble" . bibtex-preamble))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-string]
  '("String" . bibtex-string))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-Misc]
  '("Miscellaneous" . bibtex-Misc))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-Unpublished]
  '("Unpublished" . bibtex-Unpublished))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-Manual]
  '("Technical Manual" . bibtex-Manual))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-TechReport]
  '("Technical Report" . bibtex-TechReport))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-MastersThesis]
  '("Master's Thesis" . bibtex-MastersThesis))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-PhdThesis]
  '("PhD. Thesis" . bibtex-PhdThesis))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-Booklet]
  '("Booklet (Bound, but no Publisher/Institution)" . bibtex-Booklet))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-Book]
  '("Book" . bibtex-Book))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-Proceedings]
  '("Conference Proceedings" . bibtex-Proceedings))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-InBook]
  '("Chapter or Pages in a Book" . bibtex-InBook))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-InCollection]
  '("Article in a Collection" . bibtex-InCollection))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-InProceedings]
  '("Article in Conference Proceedings" . bibtex-InProceedings))
(define-key bibtex-mode-map [menu-bar entry-types bibtex-Article]
  '("Article in Journal" . bibtex-Article))



;; Internal Variables

(defvar bibtex-pop-previous-search-point nil)
;; Next point where bibtex-pop-previous starts looking for a similar
;; entry.

(defvar bibtex-pop-next-search-point nil)
;; Next point where bibtex-pop-next starts looking for a similar entry.

(defvar bibtex-completion-candidates nil)
;; Candidates for bibtex-complete-string. Initialized from
;; bibtex-predefined-strings and bibtex-string-files. This variable is
;; buffer-local.
(make-variable-buffer-local 'bibtex-completion-candidates)

(defvar bibtex-keys nil)
;; Candidates for TAB completion when entering a reference key using
;; the minibuffer. Initialized in bibtex-mode and updated for each
;; new entry. This variable is buffer-local.
(make-variable-buffer-local 'bibtex-keys)

(defvar bibtex-buffer-last-parsed-for-keys-tick nil)
;; Remembers the value returned by buffer-modified-tick when buffer
;; was parsed for keys the last time.
(make-variable-buffer-local 'bibtex-keys)



;; Functions to Parse the BibTeX Entries

(defun bibtex-cfield (name text)
  ;; Create a regexp for a BibTeX field of name NAME and text TEXT.
  (concat ",[ \t\n]*\\("
	  name
	  "\\)[ \t\n]*=[ \t\n]*\\("
	  text
	  "\\)"))
(defconst bibtex-name-in-cfield 1)
;; The regexp subexpression number of the name part in bibtex-cfield.

(defconst bibtex-text-in-cfield 2)
;; The regexp subexpression number of the text part in bibtex-cfield.

(defconst bibtex-field-name "[A-Za-z_-][A-Za-z0-9_-]*")
;; Regexp defining the name part of a BibTeX field.

(defconst bibtex-field-const "[0-9A-Za-z][A-Za-z0-9:_+-]*"
  "Format of a bibtex field constant.")

(defconst bibtex-field-string
  (concat
   "\\("
   "{\\(\\({\\(\\({[^}]*}\\)\\|\\([^{}]\\)\\)*}\\)\\|\\([^{}]\\)\\)*}"
   ;; maximal twice nested {}
   "\\)\\|\\("
   "\"[^\"]*[^\\\\]\"\\|\"\""
   "\\)"))
;; Match either a string or an empty string.

(defconst bibtex-field-string-or-const
  (concat bibtex-field-const "\\|" bibtex-field-string))
;; Match either bibtex-field-string or bibtex-field-const.

(defconst bibtex-field-text
  (concat
    "\\(" bibtex-field-string-or-const "\\)"
        "\\([ \t\n]+#[ \t\n]+\\(" bibtex-field-string-or-const "\\)\\)*"))
;; Regexp defining the text part of a BibTeX field: either a string,
;; or an empty string, or a constant followed by one or more # /
;; constant pairs.

(defconst bibtex-field
  (bibtex-cfield bibtex-field-name bibtex-field-text))
;; Regexp defining the format of a BibTeX field.

(defconst bibtex-name-in-field bibtex-name-in-cfield)
;; The regexp subexpression number of the name part in BibTeX-field.

(defconst bibtex-text-in-field bibtex-text-in-cfield)
;; The regexp subexpression number of the text part in BibTeX-field.

(defconst bibtex-reference-type "@[A-Za-z]+")
;; Regexp defining the type part of a BibTeX reference entry.

(defconst bibtex-reference-key "[A-Za-z][A-Za-z0-9.:;?!`'/*@_+-]*")
;; Regexp defining the label part of a BibTeX reference entry.

(defconst bibtex-reference-head
  (concat "^\\( \\|\t\\)*\\("
	  bibtex-reference-type
	  "\\)[ \t]*[({]\\("
	  bibtex-reference-key
	  "\\)"))
;; Regexp defining format of the header line of a BibTeX reference
;; entry.

(defconst bibtex-reference-maybe-empty-head
  (concat bibtex-reference-head "?"))
;; Regexp defining format of the header line of a maybe empty
;; BibTeX reference entry (without reference key).

(defconst bibtex-type-in-head 2)
;; The regexp subexpression number of the type part in
;; bibtex-reference-head.

(defconst bibtex-key-in-head 3)
;; The regexp subexpression number of the key part in
;; bibtex-reference-head.

(defconst bibtex-reference
  (concat bibtex-reference-head
	  "\\([ \t\n]*" bibtex-field "\\)*"
	  "[ \t\n]*,?[ \t\n]*[})]"))
;; Regexp defining the format of a BibTeX reference entry.

(defconst bibtex-type-in-reference bibtex-type-in-head)
;; The regexp subexpression number of the type part in
;; bibtex-reference.

(defconst bibtex-key-in-reference bibtex-key-in-head)
;; The regexp subexpression number of the key part in
;; bibtex-reference.

(defconst bibtex-string
  (concat "^[ \t]*@[sS][tT][rR][iI][nN][gG][ \t\n]*[({][ \t\n]*\\("
	  bibtex-reference-key
	  "\\)[ \t\n]*=[ \t\n]*\\("
	  bibtex-field-text
	  "\\)[ \t\n]*[})]"))
;; Regexp defining the format of a BibTeX string entry.

(defconst bibtex-key-in-string 1)
;; The regexp subexpression of the name part in bibtex-string.

(defconst bibtex-text-in-string 2)
;; The regexp subexpression of the text part in bibtex-string.

(defconst bibtex-name-alignment 2)
;; Alignment for the name part in BibTeX fields. Chosen on aesthetic
;; grounds only.

(defconst bibtex-text-alignment (length "  organization = "))
;; Alignment for the text part in BibTeX fields. Equal to the space
;; needed for the longest name part.



;; Helper Functions

(defun assoc-ignore-case (string alist)
  ;; Return non-nil if STRING is `equal' to the car of an element of
  ;; LIST. Comparison is done with case ignored. The value is actually
  ;; the element of LIST whose car is `equal' to STRING.
  (or (assoc string alist)
      (while (and alist
		  (not (string-equal
                        (downcase string)
                        (downcase (car (car alist))))))
	(setq alist (cdr alist)))
      (car alist)))

(defun member-of-regexp (string list)
  ;; Return non-nil if STRING is exactly matched by an element of
  ;; LIST. This function is influenced by the actual value of
  ;; `case-fold-search'. The value is actually the tail of LIST whose
  ;; car matches STRING.
  (while
      (and
       list
       (not
        (string-match
         (concat "^" (car list) "$")
         string)))
    (setq list (cdr list)))
  list)

(defun assoc-of-regexp (string alist)
  ;; Return non-nil if STRING is exactly matched by the car of an
  ;; element of LIST. This function is influenced by the actual value
  ;; of `case-fold-search'. The value is actually the element of LIST
  ;; whose car matches STRING.
  (while
      (and
       alist
       (not
        (string-match
         (concat "^" (car (car alist)) "$")
         string)))
    (setq alist (cdr alist)))
  (car alist))

(defun skip-whitespace-and-comments ()
  (let ((md (match-data)))
    (unwind-protect
	(while (cond ((looking-at "\\s>+\\|\\s +")
		      ;; was whitespace
		      ;; NOTE: also checked end-comment.  In latex and
		      ;; lisp modes, newline is an end comment, but it
		      ;; should also be a whitespace char.
		      (goto-char (match-end 0)))
		     ;; If looking at beginning of comment, skip to end.
		     ((looking-at "\\s<")
		      (re-search-forward "\\s>"))))		      
      (store-match-data md))))

(defun map-bibtex-entries (fun)
  ;; Call FUN for each BibTeX entry starting with the current. Do this
  ;; to the end of the file. FUN is called with one argument, the key
  ;; of the entry, and with point inside the entry. If
  ;; bibtex-sort-ignore-string-entries is non-nil, FUN will not be called
  ;; for @string entries.
  (bibtex-beginning-of-entry)
  (while (re-search-forward bibtex-reference-head nil t)
    (if (and bibtex-sort-ignore-string-entries
	     (string-equal "@string"
                           (downcase (buffer-substring-no-properties
                                      (match-beginning bibtex-type-in-head)
                                      (match-end bibtex-type-in-head)))))
	nil
      (funcall fun (buffer-substring-no-properties
                    (match-beginning bibtex-key-in-head)
                    (match-end bibtex-key-in-head))))))

(defun bibtex-flash-head ()
  ;; Flash at BibTeX reference head before point, if exists.
  (let ((flash))
    (cond ((re-search-backward bibtex-reference-head (point-min) t)
	   (goto-char (match-beginning bibtex-type-in-head))
	   (setq flash (match-end bibtex-key-in-reference)))
	  (t
	   (end-of-line)
	   (skip-chars-backward " \t")
	   (setq flash (point))
	   (beginning-of-line)
	   (skip-chars-forward " \t")))
    (if (pos-visible-in-window-p (point))
	(sit-for 1)
      (message "From: %s"
	       (buffer-substring (point) flash)))))

(defun bibtex-move-outside-of-entry ()
  ;; Make sure we are outside of a BibTeX entry.
  (cond ((or
	  (= (point) (point-max))
	  (= (point) (point-min))
	  (looking-at "[ \n]*@")
	  )
	 t)
	(t
	 (backward-paragraph)
	 (forward-paragraph)))
  (re-search-forward "[ \t\n]*" (point-max) t))

(defun beginning-of-first-bibtex-entry ()
  ;; Go to the beginning of the first BibTeX entry in buffer.
  (goto-char (point-min))
   (cond
    ((re-search-forward "^@" nil 'move)
     (beginning-of-line))
    ((and (bobp) (eobp))
     nil)
    (t
     (message "Warning: No BibTeX entries found!"))))

(defun bibtex-inside-field ()
  ;; Try to avoid point being at end of a BibTeX field.
  (end-of-line)
  (skip-chars-backward " \t")
  (cond ((= (preceding-char) ?,)
	 (forward-char -2)))
  (cond ((or
          (= (preceding-char) ?})
          (= (preceding-char) ?\"))
         (forward-char -1))))

(defun bibtex-enclosing-field ()
  ;; Search for BibTeX field enclosing point. Point moves to end of
  ;; field; also, use match-beginning and match-end to parse the field.
  ;; sct@dcs.edinburgh.ac.uk
  (let ((old-point (point)))
    (condition-case errname
 	(bibtex-enclosing-regexp bibtex-field)
      (search-failed
       (goto-char old-point)
       (error "Can't find enclosing BibTeX field.")))))

(defun bibtex-enclosing-reference ()
  ;; Search for BibTeX reference enclosing point. Point moves to
  ;; beginning of reference. Beginning/end of reference is given by
  ;; (match-beginning/match-end 0).
  (let ((old-point (point)))
    (if (not
         (re-search-backward bibtex-reference-head (point-min) t))
        (progn
          (error "Can't find enclosing BibTeX reference.")
          (goto-char old-point)))
    (goto-char (match-beginning bibtex-type-in-head))
    (let ((pnt (point)))
      (if (not
           (re-search-forward bibtex-reference (point-max) t))
          (progn
            (error "Can't find enclosing BibTeX reference.")
            (goto-char old-point))
        (goto-char pnt)))))

(defun bibtex-enclosing-reference-maybe-empty-head ()
  ;; Search for BibTeX reference enclosing point. Point moves to
  ;; beginning of reference. Beginning/end of reference is given by
  ;; (match-beginning/match-end 0).
  (let ((old-point (point)))
    (if (not
         (re-search-backward
          bibtex-reference-maybe-empty-head (point-min) t))
        (progn
          (error "Can't find enclosing BibTeX reference.")
          (goto-char old-point)))
    (goto-char (match-beginning bibtex-type-in-head))
    (let ((pnt (point)))
      (if (not
           (re-search-forward
            (concat
             bibtex-reference-maybe-empty-head
             "\\([ \t\n]*" bibtex-field "\\)*"
             "[ \t\n]*,?[ \t\n]*[})]")
            (point-max) t))
          (progn
            (error "Can't find enclosing BibTeX reference.")
            (goto-char old-point))
        (goto-char pnt)))))

(defun bibtex-enclosing-regexp (regexp)
  ;; Search for REGEXP enclosing point. Point moves to end of
  ;; REGEXP. See also match-beginning and match-end. If an enclosing
  ;; REGEXP is not found, signals search-failed; point is left in an
  ;; undefined location.
  ;; Doesn't something like this exist already?
  ; compute reasonable limits for the loop
  (let* ((initial (point))
	 (right (if (re-search-forward regexp (point-max) t)
		    (match-end 0)
		  (point-max)))
	 (left
	  (progn
	    (goto-char initial)
	    (if (re-search-backward regexp (point-min) t)
		(match-beginning 0)
	      (point-min)))))
    ; within the prescribed limits, loop until a match is found
    (goto-char left)
    (re-search-forward regexp right nil 1)
    (if (> (match-beginning 0) initial)
	(signal 'search-failed (list regexp)))	  
    (while (<= (match-end 0) initial)
      (re-search-forward regexp right nil 1)
      (if (> (match-beginning 0) initial)
	  (signal 'search-failed (list regexp))))
    ))

(defun bibtex-autokey-change (string change-list)
  ;; Returns a string where some regexps are changed according to
  ;; change-list. Every item of change-list is an (old-regexp
  ;; new-string) pair.
  (let ((return-string string)
        case-fold-search
        (index 0)
        (len (length change-list))
        change-item)
    (while (< index len)
      (setq change-item (elt change-list index))
      (while (string-match (car change-item) return-string)
        (setq
         return-string
         (concat (substring return-string 0 (match-beginning 0))
                 (elt change-item 1)
                 (substring return-string (match-end 0)))))
      (setq index (1+ index)))
    return-string))

(defun bibtex-autokey-abbrev (string len)
  ;; Returns an abbreviation of string with at least len
  ;; characters. String is aborted only after a consonant or at the
  ;; word end. If len is not a number, string is returned unchanged.
  (let* ((string-length (length string))
         (len (if (numberp len)
                  (min len string-length)
                len))
         (return-string (if (numberp len)
                            (substring string 0 len)))
         (index len)
         (vowels '(?a ?e ?i ?o ?u ?A ?E ?I ?O ?U)))
    (if (numberp len)
        (progn
          (while (and
                  (< index string-length) 
                  (member (elt return-string
                               (1- (length return-string)))
                          vowels))
            (setq return-string (concat return-string
                                        (substring
                                         string index (1+ index)))
                  index (1+ index)))
          return-string)
      string)))        

(defun bibtex-generate-autokey ()
  "Generates automatically a key from the author/editor and the title field.
The generation algorithm works as follows:
  1. If there is a non-empty author (preferred) or editor field,
     use it for the name part of the key.
  2. Change any substring found in `bibtex-autokey-name-change-strings' 
     to the corresponding new one (see documentation of this variable
     for further detail).
  3. For every of the first `bibtex-autokey-names' names in the
     \"name\" field, determine the last name.
  4. From every last name, take at least `bibtex-autokey-name-length'
     characters (abort only after a consonant or at a word end).
  5. Build the name part of the key by concatenating all abbreviated last
     names with the string `bibtex-autokey-name-separator' between
     any two.
  6. Build the year part of the key by truncating the contents of the
     \"year\" field to the rightmost `bibtex-autokey-year-length'
     digits (useful values are 2 and 4).
  7. For the title part of the key change the contents of the \"title\"
     field of the reference according to
     `bibtex-autokey-titleword-change-strings' to the corresponding
     new one (see documentation of this variable for further detail).
  8. Abbreviate the result to the string up to (but not including) the
     first occurrence of a regexp matched by the items of
     `bibtex-autokey-title-terminators' and delete the first
     word if it appears in `bibtex-autokey-titleword-first-ignore'. 
     Build the title part of the key by using at least the first
     `bibtex-autokey-titlewords' capitalized words from this
     abbreviated title. If the abbreviated title ends after maximal
     `bibtex-autokey-titlewords' + `bibtex-autokey-titlewords-stretch'
     capitalized words, all capitalized words from the abbreviated title
     are used. 
  9. For every used title word that appears in
     `bibtex-autokey-titleword-abbrevs' use the corresponding abbreviation
     (see documentation of this variable for further detail).
 10. From every title word not generated by an abbreviation, take at
     least `bibtex-autokey-titleword-length' characters (abort only after
     a consonant or at a word end).
 11. Build the title part of the key by concatenating all abbreviated
     title words with the string `bibtex-autokey-titleword-separator'
     between any two.
 12. At least, to get the key, concatenate the name part, the year part
     and the title part with `bibtex-autokey-name-year-separator'
     between the name and the year if both are non-empty and
     `bibtex-autokey-year-title-separator' between the year and
     the title if both are non-empty."

  (let* ((pnt (point))
         (min
          (progn
            (bibtex-beginning-of-entry)
            (point)))
         (max
          (progn
            (bibtex-end-of-entry)
            (point)))
         (namefield
          (progn
            (goto-char min)
            (if (or
                 (re-search-forward "^[ \t]*author[ \t]*=" max t)
                 (re-search-forward "^[ \t]*editor[ \t]*=" max t))
                (let* (bibtex-help-message
                       (start (progn
                                (bibtex-find-text t)
                                (point)))
                       (end (progn
                              (bibtex-find-text nil)
                              (point))))
                  (bibtex-autokey-change
                   (buffer-substring-no-properties start end)
                   bibtex-autokey-name-change-strings))
              "")))
         (namelist
          (mapcar
           (function
            (lambda (fullname)
              (bibtex-autokey-abbrev
               (if (string-match "," fullname)
                   (substring fullname 0 (match-beginning 0))
                 (progn
                   (if (string-match " [^ ]*$" fullname)
                       (substring
                        fullname (1+ (match-beginning 0)))
                     fullname)))
               bibtex-autokey-name-length)))
           ;; Gather all names into a list
           (let (names
                 (counter 0))
             (while (and
                     (not (equal namefield ""))
                     (or
                      (not (numberp bibtex-autokey-names))
                      (< counter bibtex-autokey-names)))
               (if (string-match " and " namefield)
                   (progn
                     (setq
                      names
                      (append names
                              (list
                               (downcase
                                (substring
                                 namefield 0 (match-beginning 0)))))
                      namefield
                      (substring namefield (match-end 0))))
                 (setq names
                       (append names (list (downcase namefield)))
                       namefield ""))
               (setq counter (1+ counter)))
             names)))
         (namepart (mapconcat (function (lambda (name) name))
                              namelist
                              bibtex-autokey-name-separator))
         (yearfield
          (progn
            (goto-char min)
            (if (re-search-forward
                 "^[ \t]*year[ \t]*=[ \t]*\\([0-9]*\\)" max t)
                (buffer-substring-no-properties
                 (match-beginning 1) (match-end 1))
              "")))
         (yearpart
          (if (equal yearfield "")
              ""
            (substring yearfield
                       (- (length yearfield)
                          bibtex-autokey-year-length))))
         (titlestring
          (let ((case-fold-search t)
                (titlefield
                 (progn
                   (goto-char min)
                   (if (re-search-forward
                        "^[ \t]*title[ \t]*=" max t)
                       (let* (bibtex-help-message
                              (start (progn
                                       (bibtex-find-text t)
                                       (point)))
                              (end (progn
                                     (bibtex-find-text nil)
                                     (point))))
                         (bibtex-autokey-change
                          (buffer-substring-no-properties start end)
                          bibtex-autokey-titleword-change-strings))
                     "")))
                case-fold-search
                (index 0)
                (numberofitems
                 (length bibtex-autokey-title-terminators)))
            (while (< index numberofitems)
              (if (string-match
                   (elt bibtex-autokey-title-terminators index)
                   titlefield)
                  (setq titlefield
                        (substring titlefield 0 (match-beginning 0))))
              (setq index (1+ index)))
            titlefield))
         (titlelist
          (mapcar
           (function
            (lambda (titleword)
              (let ((abbrev
                     (assoc-of-regexp
                      titleword bibtex-autokey-titleword-abbrevs)))
                (if abbrev
                    (elt abbrev 1)
                  (bibtex-autokey-abbrev
                   titleword
                   bibtex-autokey-titleword-length)))))
           ;; Gather all titlewords into a list
           (let (titlewords
                 titlewords-extra
                 case-fold-search
                 (counter 0)
                 (first t))
             (while (and
                     (not (equal titlestring ""))
                     (or
                      (not (numberp bibtex-autokey-titlewords))
                      (< counter (+
                                  bibtex-autokey-titlewords
                                  bibtex-autokey-titlewords-stretch))))
               (if (string-match "\\b[A-Z][A-Za-z0-9]*" titlestring)
                   (let* ((end-match (match-end 0))
                          (titleword
                           (downcase (substring titlestring
                                                (match-beginning 0)
                                                end-match))))
                     (if (or
                          (not (numberp bibtex-autokey-titlewords))
                          (< counter bibtex-autokey-titlewords))
                         (if (and
                              first
                              (member-of-regexp
                               titleword
                               bibtex-autokey-titleword-first-ignore))
                             (setq counter -1)
                           (setq titlewords
                                 (append titlewords (list titleword))))
                       (setq
                        titlewords-extra
                        (append titlewords-extra (list titleword))))
                     (setq titlestring
                           (substring titlestring end-match)))
                 (setq titlestring ""))
               (setq first nil
                     counter (1+ counter)))
             (if (string-match "\\b[A-Z][^ ]*\\b" titlestring)
                 titlewords
               (append titlewords titlewords-extra)))))
         (titlepart (mapconcat (function (lambda (name) name))
                               titlelist
                               bibtex-autokey-titleword-separator))
         (autokey
          (concat
           namepart
           (if (not
                (or
                 (equal namepart "")
                 (equal yearpart "")))
               bibtex-autokey-name-year-separator)
           yearpart
           (if (not
                (or
                 (and
                  (equal namepart "")
                  (equal yearpart ""))
                 (equal titlepart "")))
               bibtex-autokey-year-title-separator)
           titlepart)))
    (goto-char pnt)
    autokey))

(defun bibtex-parse-keys (add &optional abortable)
  ;; Sets bibtex-keys to the keys used in the whole (possibly
  ;; restricted) buffer (either as entry keys or as crossref entries).
  ;; If ADD is non-nil adds the new keys to bibtex-keys instead of
  ;; simply resetting it. If ABORTABLE is non-nil abort on user input.
  (if bibtex-maintain-sorted-entries
      (let ((labels (if add
                        bibtex-keys))
            label
            (case-fold-search t))
        (save-excursion
          (goto-char (point-min))
          (if (not add)
              (message "Parsing reference keys..."))

          (if (not
               (catch 'userkey
                 (while
                     (re-search-forward
                      (concat
                       "\\("
                       bibtex-reference-head
                       "\\)\\|\\("
                       "^[ \t\n]*crossref[ \t\n]*=[ \t\n]*[{\"]\\([A-Za-z][]A-Za-z0-9.:;?!`'()/*@_+-]*\\)[}\"],?$"
                       "\\)")
                      nil t)
                   (if (and
                        abortable
                        (input-pending-p))
                       (throw 'userkey t))
                   (if (match-beginning (1+ bibtex-key-in-head))
                       (setq
                        label
                        (buffer-substring-no-properties 
                         (match-beginning (1+ bibtex-key-in-head))
                         (match-end (1+ bibtex-key-in-head))))
                     (setq
                      label
                      (buffer-substring-no-properties
                       (match-beginning (+ 3 bibtex-key-in-head))
                       (match-end (+ 3 bibtex-key-in-head)))))
                   (if (not (assoc label labels))
                       (setq labels
                             (cons (list label) labels))))))
              (progn
                (setq
                 bibtex-buffer-last-parsed-for-keys-tick
                 (buffer-modified-tick))
                (if (not add)
                    (message "Parsing reference keys... done"))
                (setq bibtex-keys labels)))))))

(defun bibtex-auto-fill-function ()
  (let ((fill-prefix (make-string (+ bibtex-text-alignment 1) ? )))
    (do-auto-fill)))



;; Interactive Functions:

;;;###autoload
(defun bibtex-mode () 
  "Major mode for editing BibTeX files.

\\{bibtex-mode-map}

A command such as \\[bibtex-Book] will outline the fields for a BibTeX book entry.

The optional fields start with the string OPT, and thus ignored by BibTeX.
The OPT string may be removed from a field with \\[bibtex-remove-OPT].
\\[bibtex-kill-optional-field] kills the current optional field entirely.
\\[bibtex-remove-double-quotes-or-braces] removes the double-quotes or
braces around the text of the current field.  \\[bibtex-empty-field]
replaces the text of the current field with the default \"\" or {}.

The command \\[bibtex-clean-entry] cleans the current entry, i.e. (i) removes
double-quotes or braces from entirely numerical fields, (ii) removes
OPT from all non-empty optional fields, (iii) removes all empty
optional fields, and (iv) checks that no non-optional fields are empty.

Use \\[bibtex-find-text] to position the cursor at the end of the current field.
Use \\[bibtex-next-field] to move to end of the next field.

The following may be of interest as well:

  Functions:
    bibtex-entry
    bibtex-print-help-message
    bibtex-beginning-of-entry
    bibtex-end-of-entry
    bibtex-ispell-abstract
    bibtex-narrow-to-entry
    bibtex-hide-entry-bodies
    bibtex-sort-entries
    bibtex-validate-buffer
    bibtex-pop-previous
    bibtex-pop-next
    bibtex-complete-string

  Variables:
    bibtex-field-left-delimiter
    bibtex-field-right-delimiter
    bibtex-include-OPTcrossref
    bibtex-include-OPTkey
    bibtex-include-OPTannote
    bibtex-mode-user-optional-fields
    bibtex-clean-entry-zap-empty-opts
    bibtex-sort-ignore-string-entries
    bibtex-maintain-sorted-entries
    bibtex-entry-field-alist
    bibtex-predefined-strings
    bibtex-string-files

---------------------------------------------------------
Entry to this mode calls the value of bibtex-mode-hook if that value is
non-nil."
  (interactive)
  (kill-all-local-variables)
  (use-local-map bibtex-mode-map)
  (setq major-mode 'bibtex-mode)
  (setq mode-name "BibTeX")
  (set-syntax-table bibtex-mode-syntax-table)
  (setq bibtex-completion-candidates bibtex-predefined-strings)
  (mapcar
   (function
    (lambda (filename)
      ;; collect pathnames
      (let* ((bib (getenv "BIBINPUTS"))
             (path (if bib
                       bib
                     "."))
             (dirs
              (mapcar
               (function
                (lambda (dirname)  ;; strips off trailing slashes
                  (let ((len (length dirname)))
                    (if (equal (elt dirname (1- len)) "/")
                        (substring dirname 0 (1- (1- len)))
                      dirname))))
               (let (actdirs)
                 (while (string-match ":" path)
                   (setq actdirs
                         (append actdirs
                                 (list (substring
                                        path 0
                                        (1- (match-end 0)))))
                         path (substring path (match-end 0))))
                 (append actdirs (list path)))))
             (filename (if (string-match "\.bib$" filename)
                           filename
                         (concat filename ".bib")))
             fullfilename
             (item 0)
             (size (length dirs)))
        ;; test filenames
        (while (and
                (< item size)
                (not (file-readable-p
                      (setq fullfilename
                            (concat (elt dirs item) "/" filename)))))
          (setq item (1+ item)))
        (if (< item size)
            ;; file was found
            (let ((curbuf (current-buffer))
                  (bufname (make-temp-name ""))
                  (compl bibtex-completion-candidates))
              (create-file-buffer bufname)
              (set-buffer bufname)
              (insert-file-contents fullfilename)
              (goto-char (point-min))
              (while (re-search-forward bibtex-string nil t)
                (setq
                 compl
                 (append
                  compl
                  (list
                   (list (buffer-substring-no-properties
                          (match-beginning bibtex-key-in-string)
                          (match-end bibtex-key-in-string)))))))
              (kill-buffer bufname)
              (set-buffer curbuf)
              (setq bibtex-completion-candidates compl))
          (error "File %s not in $BIBINPUTS paths" filename)))))
   bibtex-string-files)
  (add-hook
   'auto-save-hook
   (function
    (lambda ()
      (if (and
           bibtex-maintain-sorted-entries
           (eq major-mode 'bibtex-mode)
           (not
            (eq (buffer-modified-tick)
                bibtex-buffer-last-parsed-for-keys-tick)))
          (bibtex-parse-keys nil t)))))
  (bibtex-parse-keys nil)
  (make-local-variable 'paragraph-start)
  (setq paragraph-start "[ \f\n\t]*$")
  (make-local-variable 'comment-start)
  (setq comment-start "%")
  (auto-fill-mode 1)
  (setq auto-fill-function 'bibtex-auto-fill-function)
  (set (make-local-variable 'font-lock-defaults)
       '(bibtex-font-lock-keywords
         nil t ((?_ . "w") (?- . "w") (?$ . "\""))))
  (run-hooks 'bibtex-mode-hook))

(defun bibtex-entry (entry-type &optional required optional)
  "Inserts a new BibTeX entry.
Calls the value of bibtex-add-entry-hook if that value is non-nil."
  (interactive (let* ((completion-ignore-case t)
		      (e-t (completing-read
                            "Entry Type: "
                            bibtex-entry-field-alist
                            nil t)))
		 (list e-t)))
  (if (and (null required) (null optional))
      (let* ((e (assoc-ignore-case entry-type bibtex-entry-field-alist))
	     (r-n-o (elt e 1))
	     (c-ref (elt e 2)))
	(if (null e)
            (error "Bibtex entry type %s not defined!" entry-type))
	(if (and
             (member entry-type bibtex-include-OPTcrossref)
             c-ref)
	    (setq required (elt c-ref 0)
		  optional (elt c-ref 1))
	  (setq required (elt r-n-o 0)
		optional (elt r-n-o 1)))))
  (let ((key
         (if bibtex-maintain-sorted-entries
             (completing-read
              (format "%s key: " entry-type)
              bibtex-keys))))
    (if bibtex-maintain-sorted-entries
	(bibtex-find-entry-location key)
      (bibtex-move-outside-of-entry))
    (insert "@" entry-type "{")
    (if key
	(insert key))
    (save-excursion
      (mapcar 'bibtex-make-field required)
      (if (member entry-type bibtex-include-OPTcrossref)
	  (bibtex-make-optional-field '("crossref")))
      (if bibtex-include-OPTkey
	  (bibtex-make-optional-field '("key")))
      (mapcar 'bibtex-make-optional-field optional)
      (mapcar 'bibtex-make-optional-field 
	      bibtex-mode-user-optional-fields)
      (if bibtex-include-OPTannote
	  (bibtex-make-optional-field '("annote")))
      (insert "\n}\n\n"))
    (bibtex-next-field t)
    (run-hooks 'bibtex-add-entry-hook)))

(defun bibtex-print-help-message ()
  "Prints helpful information about current field in current BibTeX entry."
  (interactive)
    (let* ((pnt (point))
         (field-name
          (progn
            (beginning-of-line)
            (condition-case errname
                (bibtex-enclosing-regexp bibtex-field)
              (search-failed
               (goto-char pnt)
               (error "Not on BibTeX field")))
            (let ((mb (match-beginning bibtex-name-in-field))
                  (me (match-end bibtex-name-in-field)))
              (goto-char mb)
              (buffer-substring-no-properties
               (if (looking-at "OPT")
                   (+ 3 mb)
                 mb)
               me))))
         (reference-type
          (progn
            (re-search-backward
             bibtex-reference-maybe-empty-head nil t)
            (buffer-substring-no-properties
             (1+ (match-beginning bibtex-type-in-head))
             (match-end bibtex-type-in-head))))
         (entry-list
          (assoc-ignore-case reference-type
                               bibtex-entry-field-alist))
         (c-r-list (elt entry-list 2))
         (req-opt-list
          (if (and
               (member reference-type bibtex-include-OPTcrossref)
               c-r-list)
              c-r-list
            (elt entry-list 1)))
         (list-of-entries (append
                           (elt req-opt-list 0)
                           (elt req-opt-list 1)
                           bibtex-mode-user-optional-fields
                           (if (member
                                reference-type
                                bibtex-include-OPTcrossref)
                               '(("crossref"
                                  "Label of the crossreferenced entry")))
                           (if bibtex-include-OPTannote
                               '(("annote"
                                  "Personal annotation (ignored)")))
                           (if bibtex-include-OPTkey
                               '(("key"
                                  "Key used for label creation if author and editor fields are missing"))))))
    (goto-char pnt)
    (if (assoc field-name list-of-entries)
        (message (elt (assoc field-name list-of-entries) 1))
      (message "NO COMMENT AVAILABLE"))))

(defun bibtex-make-field (e-t)
  "Makes a field named E-T in current BibTeX entry."
  (interactive "sBibTeX field name: ")
  (let ((name (if (consp e-t)
                  (elt e-t 0)
                e-t)))
    (if (interactive-p)
        (progn
          (bibtex-find-text nil)
          (if (looking-at "[}\"]")
              (forward-char 1))))
    (insert ",\n")
    (indent-to-column bibtex-name-alignment)
    (insert name " = ")
    (indent-to-column bibtex-text-alignment)
    (insert bibtex-field-left-delimiter bibtex-field-right-delimiter)
    (if (interactive-p)
        (forward-char -1))))

(defun bibtex-make-optional-field (e-t)
  "Makes an optional field named E-T in current BibTeX entry."
  (if (consp e-t)
      (setq e-t (cons (concat "OPT" (car e-t)) (cdr e-t)))
    (setq e-t (concat "OPT" e-t)))
  (bibtex-make-field e-t))

(defun bibtex-beginning-of-entry ()
  "Move to beginning of BibTeX entry.
If inside an entry, move to the beginning of it, otherwise move to the
beginning of the previous entry."
  (interactive)
  (if (looking-at "^@")
      (forward-char))
  (re-search-backward "^@" nil 'move))

(defun bibtex-end-of-entry ()
  "Move to end of BibTeX entry.
If inside an entry, move to the end of it, otherwise move to the end
of the previous entry."
  (interactive)
  (bibtex-beginning-of-entry)
  (let ((parse-sexp-ignore-comments t))
    (forward-sexp 2) ;; skip entry type and body
    ))
  
(defun bibtex-ispell-entry ()
  "Spell whole BibTeX entry."
  (interactive)
  (ispell-region (progn (bibtex-beginning-of-entry) (point))
		 (progn (bibtex-end-of-entry) (point))))

(defun bibtex-ispell-abstract ()
  "Spell abstract of BibTeX entry."
  (interactive)
  (let ((pnt (bibtex-end-of-entry)))
    (bibtex-beginning-of-entry)
    (if (null
         (re-search-forward "^[ \t]*[OPT]*abstract[ \t]*=" pnt))
        (error "No abstract in entry.")))
  (ispell-region (point)
		 (save-excursion (forward-sexp) (point))))

(defun bibtex-narrow-to-entry ()
  "Narrow buffer to current BibTeX entry."
  (interactive)
  (save-excursion
    (narrow-to-region (progn (bibtex-beginning-of-entry) (point))
		      (progn (bibtex-end-of-entry) (point)))))


(defun bibtex-hide-entry-bodies (&optional arg)
  "Hide all lines between first and last BibTeX entries not beginning with @.
With argument, show all text."
  (interactive "P")
  (save-excursion
    (beginning-of-first-bibtex-entry)
    ;; subst-char-in-region modifies the buffer, despite what the
    ;; documentation says...
    (let ((modifiedp (buffer-modified-p))
	  (buffer-read-only nil))
      (if arg
	  (subst-char-in-region (point) (point-max) ?\r ?\n t)
	(while (save-excursion (re-search-forward "\n[^@]" (point-max) t))
	  ;; (save-excursion (replace-regexp "\n\\([^@]\\)" "\r\\1"))
	  (save-excursion
	    (while (re-search-forward "\n\\([^@]\\)" nil t)
	      (replace-match "\r\\1" nil nil)))))
      (setq selective-display (not arg))
      (set-buffer-modified-p modifiedp))))

(defun bibtex-sort-entries ()
  "Sort BibTeX entries alphabetically by key.
Text outside of BibTeX entries is not affected. If
bibtex-sort-ignore-string-entries is non-nil, @string entries will be
ignored."
  (interactive)
  (save-restriction
    (beginning-of-first-bibtex-entry)
    (narrow-to-region
     (point)
     (save-excursion
       (goto-char (point-max))
       (bibtex-end-of-entry)
       (point)))
    (if bibtex-sort-ignore-string-entries
        (if (re-search-forward bibtex-reference nil 'move)
            (goto-char (match-beginning 0))))
    (sort-subr
     nil
     ;; NEXTREC function
     (function
      (lambda ()
        (if bibtex-sort-ignore-string-entries
            (if (re-search-forward bibtex-reference nil 'move)
                (goto-char (match-beginning 0)))
          (if (re-search-forward bibtex-reference-head nil 'move)
              (goto-char (match-beginning 0))))))
     ;; ENDREC function
     'bibtex-end-of-entry
     ;; STARTKEY function
     (function
      (lambda ()
        (if bibtex-sort-ignore-string-entries
            (progn
              (re-search-forward bibtex-reference)
              (buffer-substring-no-properties
               (match-beginning bibtex-key-in-reference)
               (match-end bibtex-key-in-reference)))
          (re-search-forward bibtex-reference-head)
          (buffer-substring-no-properties
           (match-beginning bibtex-key-in-head)
           (match-end bibtex-key-in-head)))))
     ;; ENDKEY function
     nil)))
  
(defun bibtex-find-entry-location (entry-name &optional ignore-dups)
  "Looking for place to put the BibTeX entry named ENTRY-NAME.
Performs a binary search (therefore, buffer is assumed to be in sorted
order, without duplicates (see \\[bibtex-validate-buffer]), if it is
not, bibtex-find-entry-location will fail). If entry-name is already
used as a reference key, an error is signaled. However, if optional
variable IGNORE-DUPS is non-nil, no error messages about duplicate
entries are signaled, but the error handling is assumed to be made in
the calling function. Nil is returned, if an duplicate entry error
occurred, and t in all other cases."
  (let* ((left
          (progn
            (beginning-of-first-bibtex-entry)
            (if bibtex-sort-ignore-string-entries
                (re-search-forward bibtex-reference nil `move)
              (bibtex-end-of-entry))
            (point)))
         (right
          (progn
            (goto-char (point-max))
            (if bibtex-sort-ignore-string-entries
                (re-search-backward bibtex-reference nil `move)
              (bibtex-beginning-of-entry))
            (point)))
         actual-point
         actual-key
         (done (>= left right))
         new
         dup)
    (while (not done)
      (setq actual-point (/ (+ left right) 2))
      (goto-char actual-point)
      (bibtex-beginning-of-entry)
      (setq actual-key
            (if bibtex-sort-ignore-string-entries
                (progn
                  (re-search-forward bibtex-reference)
                  (buffer-substring-no-properties
                   (match-beginning bibtex-key-in-reference)
                   (match-end bibtex-key-in-reference)))
              (re-search-forward bibtex-reference-head)
              (buffer-substring-no-properties
               (match-beginning bibtex-key-in-head)
               (match-end bibtex-key-in-head))))
      (cond
       ((string-lessp entry-name actual-key)
        (setq new (match-beginning 0))
        (if (equal right new)
            (setq done t)
          (setq right new)))
       ((string-lessp actual-key entry-name)
        (setq new (match-end 0))
        (if (equal left new)
            (setq done t)
          (setq left new)))
       ((string-equal actual-key entry-name)
        (setq dup t
              done t)
        (if (not ignore-dups)
            (error "Entry with key `%s' already exists!" entry-name)))))
    (if dup
        nil
      (goto-char right)
      (if (re-search-forward bibtex-reference nil t)
          (progn
            (setq actual-key
                  (buffer-substring-no-properties
                   (match-beginning bibtex-key-in-reference)
                   (match-end bibtex-key-in-reference)))
            (if (string-lessp actual-key entry-name)
                ;; even greater than last entry --> we must append
                (progn
                  (goto-char (match-end 0))
                  (newline (forward-line 2))
                  (beginning-of-line))
              (goto-char right))))
      t)))    

(defun bibtex-validate-buffer ()
  "Validate if the current BibTeX buffer is syntactically correct.
Any garbage (e.g. comments) before the first \"@\" is not tested (so
you can put comments here)."
  (interactive)
  (let ((pnt (point))
        (max (point-max)))
    ;; looking if entries fit syntactical structure
    (goto-char (point-min))
    (while (< (re-search-forward "@\\|\\'") max)
      (forward-char -1)
      (let ((p (point)))
        (if (or
             (looking-at "@string")
             (looking-at "@preamble"))
            (forward-char)
          (if (not (and
                    (re-search-forward bibtex-reference nil t)
                    (equal p (match-beginning 0))))
              (progn
                (goto-char p)
                (error "Bad entry begins here"))))))
    ;; looking if entries are balanced (a single non-escaped quote
    ;; inside braces is not detected by the former check, but
    ;; bibtex-sort-entries stumbles about it
    (goto-char (point-min))
    (map-bibtex-entries
     (function
      (lambda (current)
        (bibtex-beginning-of-entry)
        (forward-sexp 2))))
    ;; looking for correct sort order and duplicates
    (if bibtex-maintain-sorted-entries
        (let ((entry-name (make-string 10 255))
              (previous nil)
              point)
          (beginning-of-first-bibtex-entry)
          (map-bibtex-entries
           (function
            (lambda (current)
              (cond ((or (null previous)
                         (string< previous current))
                     (setq previous current
                           point (point)))
                    ((string-equal previous current)
                     (error "Duplicate here with previous!"))
                    (t
                     (error "Entries out of order here!"))))))))
    (goto-char pnt)
    (message "BibTeX buffer is syntactically correct")))

(defun bibtex-next-field (arg)
  "Finds end of text of next BibTeX field; with arg, to its beginning."
  (interactive "P")
  (bibtex-inside-field)
  (let ((start (point)))
    (condition-case ()
	(progn
	  (bibtex-enclosing-field)
	  (goto-char (match-end 0))
	  (forward-char 2))
      (error
       (goto-char start)
       (end-of-line)
       (forward-char 1))))
  (bibtex-find-text arg))

(defun bibtex-find-text (arg)
  "Go to end of text of current field; with arg, go to beginning."
  (interactive "P")
  (bibtex-inside-field)
  (bibtex-enclosing-field)
  (if arg
      (progn
	(goto-char (match-beginning bibtex-text-in-field))
	(if (looking-at "[{\"]")
	    (forward-char 1)))
    (goto-char (match-end bibtex-text-in-field))
    (if (or
         (= (preceding-char) ?})
         (= (preceding-char) ?\"))
	(forward-char -1)))
  (if bibtex-help-message
      (bibtex-print-help-message)))

(defun bibtex-remove-OPT ()
  "Removes the 'OPT' starting optional arguments and goes to end of text."
  (interactive)
  (bibtex-inside-field)
  (bibtex-enclosing-field)
  (save-excursion
    (goto-char (match-beginning bibtex-name-in-field))
    (if (looking-at "OPT")
	;; sct@dcs.edinburgh.ac.uk
 	(progn
 	  (delete-char (length "OPT"))
 	  (search-forward "=")
 	  (delete-horizontal-space)
 	  (indent-to-column bibtex-text-alignment))))
  (bibtex-inside-field))

(defun bibtex-remove-double-quotes-or-braces ()
  "Removes \"\" or {} around string."
  (interactive)
  (save-excursion
    (bibtex-inside-field)
    (bibtex-enclosing-field)
    (let ((start (match-beginning bibtex-text-in-field))
	  (stop (match-end  bibtex-text-in-field)))
      (goto-char stop)
      (forward-char -1)
      (if (looking-at "[}\"]")
	  (delete-char 1))
      (goto-char start)
      (if (looking-at "[{\"]")
	  (delete-char 1)))))

(defun bibtex-kill-optional-field ()
  "Kill the entire enclosing optional BibTeX field."
  (interactive)
  (bibtex-inside-field)
  (bibtex-enclosing-field)
  (goto-char (match-beginning bibtex-name-in-field))
  (let ((the-end (match-end 0))
	(the-beginning (match-beginning 0)))
    (if (looking-at "OPT")
	(progn
	  (goto-char the-end)
	  (skip-chars-forward " \t\n,")
	  (kill-region the-beginning the-end))
      (error "Mandatory fields can't be killed"))))

(defun bibtex-empty-field ()
  "Delete the text part of the current field, replace with empty text."
  (interactive)
  (bibtex-inside-field)
  (bibtex-enclosing-field)
  (goto-char (match-beginning bibtex-text-in-field))
  (kill-region (point) (match-end bibtex-text-in-field))
  (insert (concat bibtex-field-left-delimiter
                  bibtex-field-right-delimiter)) 
  (bibtex-find-text t))

(defun bibtex-pop-previous (arg)
  "Replace text of current field with the text of similar field in previous entry.
With arg, go up ARG entries.  Repeated, goes up so many times.  May be
intermixed with \\[bibtex-pop-next] (bibtex-pop-next)."
  (interactive "p")
  (bibtex-inside-field)
  (save-excursion
    ; parse current field
    (bibtex-enclosing-field)
    (let ((start-old-text (match-beginning bibtex-text-in-field))
	  (stop-old-text  (match-end bibtex-text-in-field))
	  (start-name (match-beginning bibtex-name-in-field))
	  (stop-name (match-end bibtex-name-in-field))
	  (new-text))
      (goto-char start-name)
      ; construct regexp for previous field with same name as this one
      (let ((matching-entry
	     (bibtex-cfield
	      (buffer-substring-no-properties (if (looking-at "OPT")
                                                  (+ (point) (length "OPT"))
                                                (point))
                                              stop-name)
	      bibtex-field-text)))
	; if executed several times in a row, start each search where the
	; last one finished
	(cond ((or (eq last-command 'bibtex-pop-previous)
		   (eq last-command 'bibtex-pop-next))
	       t
	       )
	      (t
	       (bibtex-enclosing-reference-maybe-empty-head)
	       (setq bibtex-pop-previous-search-point (point))
	       (setq bibtex-pop-next-search-point (match-end 0))))
	(goto-char bibtex-pop-previous-search-point)
	; Now search for arg'th previous similar field
	(cond
	 ((re-search-backward matching-entry (point-min) t arg)
	  (setq new-text
		(buffer-substring-no-properties
                 (match-beginning bibtex-text-in-cfield)
                 (match-end bibtex-text-in-cfield)))
          ;; change delimiters, if any changes needed
          (cond
           ((and
             (equal bibtex-field-left-delimiter "{")
             (eq (aref new-text 0) ?\")
             (eq (aref new-text (1- (length new-text))) ?\"))
            (aset new-text 0 ?\{)
            (aset new-text (1- (length new-text)) ?\}))
           ((and
             (equal bibtex-field-left-delimiter "\"")
             (eq (aref new-text 0) ?\{)
             (eq (aref new-text (1- (length new-text))) ?\}))
            (aset new-text 0 ?\")
            (aset new-text (1- (length new-text)) ?\"))
           ((or
             (not (eq (aref new-text 0)
                      (aref bibtex-field-left-delimiter 0)))
             (not (eq (aref new-text (1- (length new-text)))
                      (aref bibtex-field-right-delimiter 0))))
            (setq new-text (concat bibtex-field-left-delimiter
                                   new-text 
                                   bibtex-field-right-delimiter))))
	  ; Found a matching field. Remember boundaries.
	  (setq bibtex-pop-next-search-point (match-end 0))
	  (setq bibtex-pop-previous-search-point (match-beginning 0))
	  (bibtex-flash-head)
	  ; Go back to where we started, delete old text, and pop new.
	  (goto-char stop-old-text)
	  (delete-region start-old-text stop-old-text)
	  (insert new-text))
	 (t				; search failed
	  (error "No previous matching BibTeX field."))))))
  (setq this-command 'bibtex-pop-previous))

(defun bibtex-pop-next (arg)
  "Replace text of current field with the text of similar field in next entry.
With arg, go up ARG entries.  Repeated, goes up so many times.  May be
intermixed with \\[bibtex-pop-previous] (bibtex-pop-previous)."
  (interactive "p")
  (bibtex-inside-field)
  (save-excursion
    ; parse current field
    (bibtex-enclosing-field)
    (let ((start-old-text (match-beginning bibtex-text-in-field))
	  (stop-old-text  (match-end bibtex-text-in-field))
	  (start-name (match-beginning bibtex-name-in-field))
	  (stop-name (match-end bibtex-name-in-field))
	  (new-text))
      (goto-char start-name)
      ; construct regexp for next field with same name as this one,
      ; ignoring possible OPT's
      (let ((matching-entry
	     (bibtex-cfield
	      (buffer-substring-no-properties (if (looking-at "OPT")
                                                  (+ (point) (length "OPT"))
                                                (point))
                                              stop-name)
	      bibtex-field-text)))
	
	; if executed several times in a row, start each search where the
	; last one finished
	(cond ((or (eq last-command 'bibtex-pop-next)
		   (eq last-command 'bibtex-pop-previous))
	       t
	       )
	      (t
	       (bibtex-enclosing-reference-maybe-empty-head)
	       (setq bibtex-pop-previous-search-point (point))
	       (setq bibtex-pop-next-search-point (match-end 0))))
	(goto-char bibtex-pop-next-search-point)
	
	; Now search for arg'th next similar field
	(cond
	 ((re-search-forward matching-entry (point-max) t arg)
	  (setq new-text
		(buffer-substring-no-properties
                 (match-beginning bibtex-text-in-cfield)
                 (match-end bibtex-text-in-cfield)))
          ;; change delimiters, if any changes needed
          (cond
           ((and
             (equal bibtex-field-left-delimiter "{")
             (eq (aref new-text 0) ?\")
             (eq (aref new-text (1- (length new-text))) ?\"))
            (aset new-text 0 ?\{)
            (aset new-text (1- (length new-text)) ?\}))
           ((and
             (equal bibtex-field-left-delimiter "\"")
             (eq (aref new-text 0) ?\{)
             (eq (aref new-text (1- (length new-text))) ?\}))
            (aset new-text 0 ?\")
            (aset new-text (1- (length new-text)) ?\"))
           ((or
             (not (eq (aref new-text 0)
                      (aref bibtex-field-left-delimiter 0)))
             (not (eq (aref new-text (1- (length new-text)))
                      (aref bibtex-field-right-delimiter 0))))
            (setq new-text (concat bibtex-field-left-delimiter
                                   new-text 
                                   bibtex-field-right-delimiter))))
	  ; Found a matching field. Remember boundaries.
	  (setq bibtex-pop-next-search-point (match-end 0))
	  (setq bibtex-pop-previous-search-point (match-beginning 0))
	  (bibtex-flash-head)
	  ; Go back to where we started, delete old text, and pop new.
	  (goto-char stop-old-text)
	  (delete-region start-old-text stop-old-text)
	  (insert new-text))
	 (t				; search failed
	  (error "No next matching BibTeX field."))))))
  (setq this-command 'bibtex-pop-next))

(defun bibtex-clean-entry (&optional arg)
  "Finish editing the current BibTeX entry and clean it up.
For all optional fields of current BibTeX entry: if empty, kill the
whole field; otherwise, remove the \"OPT\" string in the name; if text
numerical, remove double-quotes. For all mandatory fields: if empty,
signal error. If label of entry is empty or a prefix argument was
given, calculate a new entry label."
  (interactive "P")
  (bibtex-beginning-of-entry)
  (let ((start (point))
        crossref-there)
    (save-restriction
      (narrow-to-region start (save-excursion (bibtex-end-of-entry) (point)))
      (while (and
              (re-search-forward bibtex-field (point-max) t 1)
              (not crossref-there))
        ;; determine if reference has crossref entry
	(let ((begin-name (match-beginning bibtex-name-in-field))
	      (begin-text (match-beginning bibtex-text-in-field)))
	  (goto-char begin-name)
          (if (looking-at "\\(OPTcrossref\\)\\|\\(crossref\\)")
              (progn
                (goto-char begin-text)
                (if (not (looking-at
                          (concat
                           bibtex-field-left-delimiter
                           bibtex-field-right-delimiter)))
                    (setq crossref-there t))))))
      (bibtex-enclosing-reference-maybe-empty-head)
      (re-search-forward bibtex-reference-type)
      (let ((begin-type (1+ (match-beginning 0)))
            (end-type (match-end 0)))
        (goto-char start)
        (while (re-search-forward bibtex-field (point-max) t 1)
          (let ((begin-field (match-beginning 0))
                (end-field (match-end 0))
                (begin-name (match-beginning bibtex-name-in-field))
                (end-name (match-end  bibtex-name-in-field))
                (begin-text (match-beginning bibtex-text-in-field))
                (end-text (match-end bibtex-text-in-field))
                )
            (goto-char begin-name)
            (cond ((and
                    (looking-at "OPT")
                    bibtex-clean-entry-zap-empty-opts)
                   (goto-char begin-text)
                   (if (looking-at
                        (concat
                         bibtex-field-left-delimiter
                         bibtex-field-right-delimiter))
                       ;; empty: delete whole field if really optional
                       ;; (missing crossref handled) or complain
                       (if (and
                            (not crossref-there)
                            (assoc
                             (downcase
                              (buffer-substring-no-properties
                               (+ (length "OPT") begin-name) end-name))
                             (car (car (cdr
                                        (assoc-ignore-case
                                         (buffer-substring-no-properties
                                          begin-type end-type)
                                         bibtex-entry-field-alist))))))
                           ;; field is not really optional
                           (progn
                             (goto-char begin-name)
                             (delete-char (length "OPT"))
                             ;; make field non-OPT
                             (search-forward "=")
                             (delete-horizontal-space)
                             (indent-to-column bibtex-text-alignment)
                             (forward-char)
                             ;; and loop to go through next test
                             (error "Mandatory field ``%s'' is empty"
                                    (buffer-substring-no-properties
                                     begin-name
                                     end-name)))
                         ;; field is optional
                         (delete-region begin-field end-field))
                     ;; otherwise: not empty, delete "OPT"
                     (goto-char begin-name)
                     (delete-char (length "OPT"))
                     (progn
                       ;; fixup alignment. [alarson:19920309.2047CST]
                       (search-forward "=")
                       (delete-horizontal-space)
                       (indent-to-column bibtex-text-alignment))
                     (goto-char begin-field) ; and loop to go through next test
                     ))
                  (t
                   (goto-char begin-text)
                   (cond ((looking-at (concat
                                       bibtex-field-left-delimiter
                                       "[0-9]+"
                                       bibtex-field-right-delimiter))
                          ;; if numerical,
                          (goto-char end-text)
                          (delete-char -1) ; delete enclosing double-quotes
                          (goto-char begin-text)
                          (delete-char 1)
                          (goto-char end-field) ; go to end for next search
                          (forward-char -2) ; to compensate for the 2 quotes deleted
                          )
                         ((looking-at (concat
                                       bibtex-field-left-delimiter
                                       bibtex-field-right-delimiter))
                          ;; if empty quotes, complain
                          (forward-char 1)
                          (if (not (or (equal (buffer-substring-no-properties
                                               begin-name
                                               (+ begin-name 3))
                                              "OPT")
                                       (equal (buffer-substring-no-properties
                                               begin-name
                                               (+ begin-name 3))
                                              "opt")))
                              (error "Mandatory field ``%s'' is empty"
                                     (buffer-substring-no-properties
                                      begin-name end-name))))
                         (t
                          (goto-char end-field)))))))))
    (goto-char start)
    (bibtex-end-of-entry))
  (let* ((eob (progn
                (bibtex-end-of-entry)
                (point)))
         (key (progn
                (bibtex-beginning-of-entry)
                (if (re-search-forward
                     bibtex-reference-head eob t)
                    (buffer-substring-no-properties
                     (match-beginning bibtex-key-in-head)
                     (match-end bibtex-key-in-head))))))
    (if (or
         arg
         (not key))
        (progn
          (let ((autokey
                 (if bibtex-autokey-edit-before-use
                     (read-from-minibuffer "Key to use: "
                                           (bibtex-generate-autokey))
                   (bibtex-generate-autokey))))
            (bibtex-beginning-of-entry)
            (re-search-forward bibtex-reference-maybe-empty-head)
            (if (match-beginning bibtex-key-in-head)
                (delete-region (match-beginning bibtex-key-in-head)
                               (match-end bibtex-key-in-head)))
            (insert autokey)
            (let ((start (progn
                           (bibtex-beginning-of-entry)
                           (point)))
                  (end (progn
                         (bibtex-end-of-entry)
                         (re-search-forward "^@" nil 'move)
                         (beginning-of-line)
                         (point)))
                  last-command)
              (kill-region start end)
              (let ((success
                     (or
                      (not bibtex-maintain-sorted-entries)
                      (bibtex-find-entry-location autokey t))))
                (yank)
                (setq kill-ring (cdr kill-ring))
                (forward-char -1)
                (bibtex-beginning-of-entry)
                (re-search-forward bibtex-reference-head)
                (if (not success)
                    (error
                     "New inserted reference may be a duplicate."))))))))
  (save-excursion
    (let ((start (progn (bibtex-beginning-of-entry) (point)))
          (end (progn (bibtex-end-of-entry) (point))))
      (save-restriction
        (narrow-to-region start end)
        (bibtex-parse-keys t)))))

(defun bibtex-complete-string ()
  "Complete word fragment before point to longest prefix of a defined string.
If point is not after the part of a word, all strings are listed."
  (interactive "*")
  (let* ((end (point))
         (beg (save-excursion
                (re-search-backward "[ \t{\"]")
                (forward-char 1)
                (point)))
         (part-of-word (buffer-substring-no-properties beg end))
         (string-list (copy-sequence bibtex-completion-candidates))
         (case-fold-search t)
         (completion (save-excursion
                       (progn
                         (while (re-search-backward
                                 bibtex-string (point-min) t)
                           (setq string-list
                                 (cons
                                  (list
                                   (buffer-substring-no-properties
                                   (match-beginning bibtex-key-in-string)
                                   (match-end bibtex-key-in-string)))
                                  string-list)))
                         (setq string-list
                               (sort string-list
                                     (lambda(x y)
                                       (string-lessp
                                        (car x)
                                        (car y)))))
                         (try-completion part-of-word string-list)))))
    (cond ((eq completion t)
           (bibtex-remove-double-quotes-or-braces))
          ((null completion)
           (error "Can't find completion for \"%s\"" part-of-word))
          ((not (string= part-of-word completion))
           (delete-region beg end)
           (insert completion)
           (if (assoc completion string-list)
               (bibtex-remove-double-quotes-or-braces)))
          (t
           (message "Making completion list...")
           (let ((list (all-completions part-of-word string-list)))
             (with-output-to-temp-buffer "*Completions*"
               (display-completion-list list)))
           (message "Making completion list...done")))))

(defun bibtex-Article ()
  (interactive)
  (bibtex-entry "Article"))

(defun bibtex-Book ()
  (interactive)
  (bibtex-entry "Book"))

(defun bibtex-Booklet ()
  (interactive)
  (bibtex-entry "Booklet"))

(defun bibtex-InBook ()
  (interactive)
  (bibtex-entry "InBook"))

(defun bibtex-InCollection ()
  (interactive)
  (bibtex-entry "InCollection"))

(defun bibtex-InProceedings ()
  (interactive)
  (bibtex-entry "InProceedings"))

(defun bibtex-Manual ()
  (interactive)
  (bibtex-entry "Manual"))

(defun bibtex-MastersThesis ()
  (interactive)
  (bibtex-entry "MastersThesis"))

(defun bibtex-Misc ()
  (interactive)
  (bibtex-entry "Misc"))

(defun bibtex-PhdThesis ()
  (interactive)
  (bibtex-entry "PhdThesis"))

(defun bibtex-Proceedings ()
  (interactive)
  (bibtex-entry "Proceedings"))

(defun bibtex-TechReport ()
  (interactive)
  (bibtex-entry "TechReport"))

(defun bibtex-Unpublished ()
  (interactive)
  (bibtex-entry "Unpublished"))

(defun bibtex-string ()
  (interactive)
  (bibtex-move-outside-of-entry)
  (insert
   (concat
    "@string{ = "
    bibtex-field-left-delimiter
    bibtex-field-right-delimiter
    "}\n"))
  (forward-line -1)
  (forward-char 8))

(defun bibtex-preamble ()
  (interactive)
  (bibtex-move-outside-of-entry)
  (insert "@Preamble{}\n")
  (forward-line -1)
  (forward-char 10))



;; Make BibTeX a Feature

(provide 'bibtex)


;;; bibtex.el ends here