]> git.lyx.org Git - features.git/blob - src/insets/InsetBibtex.cpp
Simplify some of the bibliography update code. There is really no reason
[features.git] / src / insets / InsetBibtex.cpp
1 /**
2  * \file InsetBibtex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Richard Heck (BibTeX parser improvements)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetBibtex.h"
15
16 #include "BiblioInfo.h"
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "Cursor.h"
20 #include "DispatchResult.h"
21 #include "Encoding.h"
22 #include "Format.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "Language.h"
26 #include "LaTeXFeatures.h"
27 #include "output_xhtml.h"
28 #include "OutputParams.h"
29 #include "PDFOptions.h"
30 #include "TextClass.h"
31
32 #include "frontends/alert.h"
33
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/ExceptionMessage.h"
38 #include "support/FileNameList.h"
39 #include "support/filetools.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/os.h"
43 #include "support/Path.h"
44 #include "support/textutils.h"
45
46 #include <limits>
47
48 using namespace std;
49 using namespace lyx::support;
50
51 namespace lyx {
52
53 namespace Alert = frontend::Alert;
54 namespace os = support::os;
55
56
57 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
58         : InsetCommand(buf, p)
59 {
60         buffer().invalidateBibinfoCache();
61 }
62
63
64 InsetBibtex::~InsetBibtex()
65 {
66         if (isBufferLoaded())
67                 buffer().invalidateBibfileCache();
68 }
69
70
71 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
72 {
73         static ParamInfo param_info_;
74         if (param_info_.empty()) {
75                 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
76                 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
77                 param_info_.add("options", ParamInfo::LYX_INTERNAL);
78         }
79         return param_info_;
80 }
81
82
83 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
84 {
85         switch (cmd.action()) {
86
87         case LFUN_INSET_EDIT:
88                 editDatabases();
89                 break;
90
91         case LFUN_INSET_MODIFY: {
92                 InsetCommandParams p(BIBTEX_CODE);
93                 try {
94                         if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
95                                 cur.noScreenUpdate();
96                                 break;
97                         }
98                 } catch (ExceptionMessage const & message) {
99                         if (message.type_ == WarningException) {
100                                 Alert::warning(message.title_, message.details_);
101                                 cur.noScreenUpdate();
102                         } else 
103                                 throw message;
104                         break;
105                 }
106                 //
107                 setParams(p);
108                 buffer().invalidateBibfileCache();
109                 cur.forceBufferUpdate();
110                 break;
111         }
112
113         default:
114                 InsetCommand::doDispatch(cur, cmd);
115                 break;
116         }
117 }
118
119
120 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
121                 FuncStatus & flag) const
122 {
123         switch (cmd.action()) {
124         case LFUN_INSET_EDIT:
125                 flag.setEnabled(true);
126                 return true;
127
128         default:
129                 return InsetCommand::getStatus(cur, cmd, flag);
130         }
131 }
132
133
134 void InsetBibtex::editDatabases() const
135 {
136         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
137
138         if (bibfilelist.empty())
139                 return;
140
141         int nr_databases = bibfilelist.size();
142         if (nr_databases > 1) {
143                         docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
144                                                        "If you proceed, all of them will be opened."),
145                                                         convert<docstring>(nr_databases));
146                         int const ret = Alert::prompt(_("Open Databases?"),
147                                 message, 0, 1, _("&Cancel"), _("&Proceed"));
148
149                         if (ret == 0)
150                                 return;
151         }
152
153         vector<docstring>::const_iterator it = bibfilelist.begin();
154         vector<docstring>::const_iterator en = bibfilelist.end();
155         for (; it != en; ++it) {
156                 FileName const bibfile = getBibTeXPath(*it, buffer());
157                 formats.edit(buffer(), bibfile,
158                      formats.getFormatFromFile(bibfile));
159         }
160 }
161
162
163 docstring InsetBibtex::screenLabel() const
164 {
165         return _("BibTeX Generated Bibliography");
166 }
167
168
169 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
170 {
171         docstring item = from_ascii("* ");
172         docstring tip = _("Databases:") + "\n";
173         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
174
175         if (bibfilelist.empty()) {
176                 tip += item;
177                 tip += _("none");
178         } else {
179                 vector<docstring>::const_iterator it = bibfilelist.begin();
180                 vector<docstring>::const_iterator en = bibfilelist.end();
181                 for (; it != en; ++it) {
182                         tip += item;
183                         tip += *it + "\n";
184                 }
185         }
186
187         // Style-Options
188         bool toc = false;
189         docstring style = getParam("options"); // maybe empty! and with bibtotoc
190         docstring bibtotoc = from_ascii("bibtotoc");
191         if (prefixIs(style, bibtotoc)) {
192                 toc = true;
193                 if (contains(style, char_type(',')))
194                         style = split(style, bibtotoc, char_type(','));
195         }
196
197         tip += _("Style File:") +"\n";
198         tip += item;
199         if (!style.empty())
200                 tip += style;
201         else
202                 tip += _("none");
203
204         tip += "\n" + _("Lists:") + " ";
205         docstring btprint = getParam("btprint");
206                 if (btprint == "btPrintAll")
207                         tip += _("all references");
208                 else if (btprint == "btPrintNotCited")
209                         tip += _("all uncited references");
210                 else
211                         tip += _("all cited references");
212         
213         if (toc) {
214                 tip += ", ";
215                 tip += _("included in TOC");
216         }
217
218         return tip;
219 }
220
221
222 static string normalizeName(Buffer const & buffer,
223         OutputParams const & runparams, string const & name, string const & ext)
224 {
225         string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
226         if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
227                 return name;
228         if (!runparams.nice)
229                 return fname;
230
231         // FIXME UNICODE
232         return to_utf8(makeRelPath(from_utf8(fname),
233                                          from_utf8(buffer.masterBuffer()->filePath())));
234 }
235
236
237 void InsetBibtex::updateBuffer(ParIterator const &, UpdateType)
238 {
239         if (buffer().isBibInfoCacheValid())
240                 return;
241         parseBibTeXFiles();
242 }
243
244
245 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
246 {
247         // the sequence of the commands:
248         // 1. \bibliographystyle{style}
249         // 2. \addcontentsline{...} - if option bibtotoc set
250         // 3. \bibliography{database}
251         // and with bibtopic:
252         // 1. \bibliographystyle{style}
253         // 2. \begin{btSect}{database}
254         // 3. \btPrint{Cited|NotCited|All}
255         // 4. \end{btSect}
256
257         // Database(s)
258         // If we are processing the LaTeX file in a temp directory then
259         // copy the .bib databases to this temp directory, mangling their
260         // names in the process. Store this mangled name in the list of
261         // all databases.
262         // (We need to do all this because BibTeX *really*, *really*
263         // can't handle "files with spaces" and Windows users tend to
264         // use such filenames.)
265         // Otherwise, store the (maybe absolute) path to the original,
266         // unmangled database name.
267         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
268         vector<docstring>::const_iterator it = bibfilelist.begin();
269         vector<docstring>::const_iterator en = bibfilelist.end();
270         odocstringstream dbs;
271         bool didone = false;
272
273         for (; it != en; ++it) {
274                 string utf8input = to_utf8(*it);
275                 string database =
276                         normalizeName(buffer(), runparams, utf8input, ".bib");
277                 FileName const try_in_file =
278                         makeAbsPath(database + ".bib", buffer().filePath());
279                 bool const not_from_texmf = try_in_file.isReadableFile();
280
281                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
282                     not_from_texmf) {
283                         // mangledFileName() needs the extension
284                         DocFileName const in_file = DocFileName(try_in_file);
285                         database = removeExtension(in_file.mangledFileName());
286                         FileName const out_file = makeAbsPath(database + ".bib",
287                                         buffer().masterBuffer()->temppath());
288
289                         bool const success = in_file.copyTo(out_file);
290                         if (!success) {
291                                 lyxerr << "Failed to copy '" << in_file
292                                        << "' to '" << out_file << "'"
293                                        << endl;
294                         }
295                 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
296                         if (!isValidLaTeXFileName(database)) {
297                                 frontend::Alert::warning(_("Invalid filename"),
298                                          _("The following filename will cause troubles "
299                                                "when running the exported file through LaTeX: ") +
300                                              from_utf8(database));
301                         }
302                         if (!isValidDVIFileName(database)) {
303                                 frontend::Alert::warning(_("Problematic filename for DVI"),
304                                          _("The following filename can cause troubles "
305                                                "when running the exported file through LaTeX "
306                                                    "and opening the resulting DVI: ") +
307                                              from_utf8(database), true);
308                         }
309                 }
310
311                 if (didone)
312                         dbs << ',';
313                 else 
314                         didone = true;
315                 // FIXME UNICODE
316                 dbs << from_utf8(latex_path(database));
317         }
318         docstring const db_out = dbs.str();
319
320         // Post this warning only once.
321         static bool warned_about_spaces = false;
322         if (!warned_about_spaces &&
323             runparams.nice && db_out.find(' ') != docstring::npos) {
324                 warned_about_spaces = true;
325                 Alert::warning(_("Export Warning!"),
326                                _("There are spaces in the paths to your BibTeX databases.\n"
327                                               "BibTeX will be unable to find them."));
328         }
329         // Style-Options
330         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
331         string bibtotoc;
332         if (prefixIs(style, "bibtotoc")) {
333                 bibtotoc = "bibtotoc";
334                 if (contains(style, ','))
335                         style = split(style, bibtotoc, ',');
336         }
337
338         // line count
339         int nlines = 0;
340
341         if (!style.empty()) {
342                 string base = normalizeName(buffer(), runparams, style, ".bst");
343                 FileName const try_in_file = 
344                         makeAbsPath(base + ".bst", buffer().filePath());
345                 bool const not_from_texmf = try_in_file.isReadableFile();
346                 // If this style does not come from texmf and we are not
347                 // exporting to .tex copy it to the tmp directory.
348                 // This prevents problems with spaces and 8bit charcaters
349                 // in the file name.
350                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
351                     not_from_texmf) {
352                         // use new style name
353                         DocFileName const in_file = DocFileName(try_in_file);
354                         base = removeExtension(in_file.mangledFileName());
355                         FileName const out_file = makeAbsPath(base + ".bst",
356                                         buffer().masterBuffer()->temppath());
357                         bool const success = in_file.copyTo(out_file);
358                         if (!success) {
359                                 lyxerr << "Failed to copy '" << in_file
360                                        << "' to '" << out_file << "'"
361                                        << endl;
362                         }
363                 }
364                 // FIXME UNICODE
365                 os << "\\bibliographystyle{"
366                    << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
367                    << "}\n";
368                 nlines += 1;
369         }
370
371         // Post this warning only once.
372         static bool warned_about_bst_spaces = false;
373         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
374                 warned_about_bst_spaces = true;
375                 Alert::warning(_("Export Warning!"),
376                                _("There are spaces in the path to your BibTeX style file.\n"
377                                               "BibTeX will be unable to find it."));
378         }
379
380         if (!db_out.empty() && buffer().params().use_bibtopic) {
381                 os << "\\begin{btSect}{" << db_out << "}\n";
382                 docstring btprint = getParam("btprint");
383                 if (btprint.empty())
384                         // default
385                         btprint = from_ascii("btPrintCited");
386                 os << "\\" << btprint << "\n"
387                    << "\\end{btSect}\n";
388                 nlines += 3;
389         }
390
391         // bibtotoc-Option
392         if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
393                 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
394                 if (buffer().params().pdfoptions().use_hyperref)
395                                 os << "\\phantomsection";
396                 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
397                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
398                 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
399                         os << "\\addcontentsline{toc}{section}{\\refname}";
400         }
401
402         if (!db_out.empty() && !buffer().params().use_bibtopic) {
403                 docstring btprint = getParam("btprint");
404                 if (btprint == "btPrintAll") {
405                         os << "\\nocite{*}\n";
406                         nlines += 1;
407                 }
408                 os << "\\bibliography{" << db_out << "}\n";
409                 nlines += 1;
410         }
411
412         return nlines;
413 }
414
415
416 support::FileNameList InsetBibtex::getBibFiles() const
417 {
418         FileName path(buffer().filePath());
419         support::PathChanger p(path);
420         
421         support::FileNameList vec;
422         
423         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
424         vector<docstring>::const_iterator it = bibfilelist.begin();
425         vector<docstring>::const_iterator en = bibfilelist.end();
426         for (; it != en; ++it) {
427                 FileName const file = getBibTeXPath(*it, buffer());
428
429                 if (!file.empty())
430                         vec.push_back(file);
431                 else
432                         LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
433         }
434         
435         return vec;
436
437 }
438
439 namespace {
440
441         // methods for parsing bibtex files
442
443         typedef map<docstring, docstring> VarMap;
444
445         /// remove whitespace characters, optionally a single comma,
446         /// and further whitespace characters from the stream.
447         /// @return true if a comma was found, false otherwise
448         ///
449         bool removeWSAndComma(ifdocstream & ifs) {
450                 char_type ch;
451
452                 if (!ifs)
453                         return false;
454
455                 // skip whitespace
456                 do {
457                         ifs.get(ch);
458                 } while (ifs && isSpace(ch));
459
460                 if (!ifs)
461                         return false;
462
463                 if (ch != ',') {
464                         ifs.putback(ch);
465                         return false;
466                 }
467
468                 // skip whitespace
469                 do {
470                         ifs.get(ch);
471                 } while (ifs && isSpace(ch));
472
473                 if (ifs) {
474                         ifs.putback(ch);
475                 }
476
477                 return true;
478         }
479
480
481         enum charCase {
482                 makeLowerCase,
483                 keepCase
484         };
485
486         /// remove whitespace characters, read characer sequence
487         /// not containing whitespace characters or characters in
488         /// delimChars, and remove further whitespace characters.
489         ///
490         /// @return true if a string of length > 0 could be read.
491         ///
492         bool readTypeOrKey(docstring & val, ifdocstream & ifs,
493                 docstring const & delimChars, docstring const & illegalChars, 
494                 charCase chCase) {
495
496                 char_type ch;
497
498                 val.clear();
499
500                 if (!ifs)
501                         return false;
502
503                 // skip whitespace
504                 do {
505                         ifs.get(ch);
506                 } while (ifs && isSpace(ch));
507
508                 if (!ifs)
509                         return false;
510
511                 // read value
512                 bool legalChar = true;
513                 while (ifs && !isSpace(ch) && 
514                                                  delimChars.find(ch) == docstring::npos &&
515                                                  (legalChar = (illegalChars.find(ch) == docstring::npos))
516                                         ) 
517                 {
518                         if (chCase == makeLowerCase)
519                                 val += lowercase(ch);
520                         else
521                                 val += ch;
522                         ifs.get(ch);
523                 }
524                 
525                 if (!legalChar) {
526                         ifs.putback(ch);
527                         return false;
528                 }
529
530                 // skip whitespace
531                 while (ifs && isSpace(ch)) {
532                         ifs.get(ch);
533                 }
534
535                 if (ifs) {
536                         ifs.putback(ch);
537                 }
538
539                 return val.length() > 0;
540         }
541
542         /// read subsequent bibtex values that are delimited with a #-character.
543         /// Concatenate all parts and replace names with the associated string in
544         /// the variable strings.
545         /// @return true if reading was successfull (all single parts were delimited
546         /// correctly)
547         bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
548
549                 char_type ch;
550
551                 val.clear();
552
553                 if (!ifs)
554                         return false;
555
556                 do {
557                         // skip whitespace
558                         do {
559                                 ifs.get(ch);
560                         } while (ifs && isSpace(ch));
561
562                         if (!ifs)
563                                 return false;
564
565                         // check for field type
566                         if (isDigit(ch)) {
567
568                                 // read integer value
569                                 do {
570                                         val += ch;
571                                         ifs.get(ch);
572                                 } while (ifs && isDigit(ch));
573
574                                 if (!ifs)
575                                         return false;
576
577                         } else if (ch == '"' || ch == '{') {
578                                 // set end delimiter
579                                 char_type delim = ch == '"' ? '"': '}';
580
581                                 // Skip whitespace
582                                 do {
583                                         ifs.get(ch);
584                                 } while (ifs && isSpace(ch));
585                                 
586                                 if (!ifs)
587                                         return false;
588                                 
589                                 // We now have the first non-whitespace character
590                                 // We'll collapse adjacent whitespace.
591                                 bool lastWasWhiteSpace = false;
592                                 
593                                 // inside this delimited text braces must match.
594                                 // Thus we can have a closing delimiter only
595                                 // when nestLevel == 0
596                                 int nestLevel = 0;
597  
598                                 while (ifs && (nestLevel > 0 || ch != delim)) {
599                                         if (isSpace(ch)) {
600                                                 lastWasWhiteSpace = true;
601                                                 ifs.get(ch);
602                                                 continue;
603                                         }
604                                         // We output the space only after we stop getting 
605                                         // whitespace so as not to output any whitespace
606                                         // at the end of the value.
607                                         if (lastWasWhiteSpace) {
608                                                 lastWasWhiteSpace = false;
609                                                 val += ' ';
610                                         }
611                                         
612                                         val += ch;
613
614                                         // update nesting level
615                                         switch (ch) {
616                                                 case '{':
617                                                         ++nestLevel;
618                                                         break;
619                                                 case '}':
620                                                         --nestLevel;
621                                                         if (nestLevel < 0) 
622                                                                 return false;
623                                                         break;
624                                         }
625
626                                         if (ifs)
627                                                 ifs.get(ch);
628                                 }
629
630                                 if (!ifs)
631                                         return false;
632
633                                 // FIXME Why is this here?
634                                 ifs.get(ch);
635
636                                 if (!ifs)
637                                         return false;
638
639                         } else {
640
641                                 // reading a string name
642                                 docstring strName;
643
644                                 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
645                                         strName += lowercase(ch);
646                                         ifs.get(ch);
647                                 }
648
649                                 if (!ifs)
650                                         return false;
651
652                                 // replace the string with its assigned value or
653                                 // discard it if it's not assigned
654                                 if (strName.length()) {
655                                         VarMap::const_iterator pos = strings.find(strName);
656                                         if (pos != strings.end()) {
657                                                 val += pos->second;
658                                         }
659                                 }
660                         }
661
662                         // skip WS
663                         while (ifs && isSpace(ch)) {
664                                 ifs.get(ch);
665                         }
666
667                         if (!ifs)
668                                 return false;
669
670                         // continue reading next value on concatenate with '#'
671                 } while (ch == '#');
672
673                 ifs.putback(ch);
674
675                 return true;
676         }
677 }
678
679
680 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
681 {
682         parseBibTeXFiles();
683 }
684
685
686 void InsetBibtex::parseBibTeXFiles() const
687 {
688         // This bibtex parser is a first step to parse bibtex files
689         // more precisely.
690         //
691         // - it reads the whole bibtex entry and does a syntax check
692         //   (matching delimiters, missing commas,...
693         // - it recovers from errors starting with the next @-character
694         // - it reads @string definitions and replaces them in the
695         //   field values.
696         // - it accepts more characters in keys or value names than
697         //   bibtex does.
698         //
699         // Officially bibtex does only support ASCII, but in practice
700         // you can use the encoding of the main document as long as
701         // some elements like keys and names are pure ASCII. Therefore
702         // we convert the file from the buffer encoding.
703         // We don't restrict keys to ASCII in LyX, since our own
704         // InsetBibitem can generate non-ASCII keys, and nonstandard
705         // 8bit clean bibtex forks exist.
706
707         BiblioInfo keylist;
708
709         support::FileNameList const files = getBibFiles();
710         support::FileNameList::const_iterator it = files.begin();
711         support::FileNameList::const_iterator en = files.end();
712         for (; it != en; ++ it) {
713                 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
714                         ios_base::in, buffer().params().encoding().iconvName());
715
716                 char_type ch;
717                 VarMap strings;
718
719                 while (ifs) {
720
721                         ifs.get(ch);
722                         if (!ifs)
723                                 break;
724
725                         if (ch != '@')
726                                 continue;
727
728                         docstring entryType;
729
730                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
731                                 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
732                                 continue;
733                         }
734
735                         if (!ifs) {
736                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
737                                 continue;
738                         }
739
740                         if (entryType == from_ascii("comment")) {
741                                 ifs.ignore(numeric_limits<int>::max(), '\n');
742                                 continue;
743                         }
744
745                         ifs.get(ch);
746                         if (!ifs) {
747                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
748                                 break;
749                         }
750
751                         if ((ch != '(') && (ch != '{')) {
752                                 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
753                                 ifs.putback(ch);
754                                 continue;
755                         }
756
757                         // process the entry
758                         if (entryType == from_ascii("string")) {
759
760                                 // read string and add it to the strings map
761                                 // (or replace it's old value)
762                                 docstring name;
763                                 docstring value;
764
765                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
766                                         lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
767                                         continue;
768                                 }
769
770                                 if (!ifs) {
771                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
772                                         continue;
773                                 }
774
775                                 // next char must be an equal sign
776                                 ifs.get(ch);
777                                 if (!ifs || ch != '=') {
778                                         lyxerr << "BibTeX Parser: No `=' after string name: " << 
779                                                         name << "." << std::endl;
780                                         continue;
781                                 }
782
783                                 if (!readValue(value, ifs, strings)) {
784                                         lyxerr << "BibTeX Parser: Unable to read value for string: " << 
785                                                         name << "." << std::endl;
786                                         continue;
787                                 }
788
789                                 strings[name] = value;
790
791                         } else if (entryType == from_ascii("preamble")) {
792
793                                 // preamble definitions are discarded.
794                                 // can they be of any use in lyx?
795                                 docstring value;
796
797                                 if (!readValue(value, ifs, strings)) {
798                                         lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
799                                         continue;
800                                 }
801
802                         } else {
803
804                                 // Citation entry. Try to read the key.
805                                 docstring key;
806
807                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
808                                         lyxerr << "BibTeX Parser: Unable to read key for entry type:" << 
809                                                         entryType << "." << std::endl;
810                                         continue;
811                                 }
812
813                                 if (!ifs) {
814                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
815                                         continue;
816                                 }
817
818                                 /////////////////////////////////////////////
819                                 // now we have a key, so we will add an entry 
820                                 // (even if it's empty, as bibtex does)
821                                 //
822                                 // we now read the field = value pairs.
823                                 // all items must be separated by a comma. If
824                                 // it is missing the scanning of this entry is
825                                 // stopped and the next is searched.
826                                 docstring name;
827                                 docstring value;
828                                 docstring data;
829                                 BibTeXInfo keyvalmap(key, entryType);
830                                 
831                                 bool readNext = removeWSAndComma(ifs);
832  
833                                 while (ifs && readNext) {
834
835                                         // read field name
836                                         if (!readTypeOrKey(name, ifs, from_ascii("="), 
837                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
838                                                 break;
839
840                                         // next char must be an equal sign
841                                         // FIXME Whitespace??
842                                         ifs.get(ch);
843                                         if (!ifs) {
844                                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
845                                                 break;
846                                         }
847                                         if (ch != '=') {
848                                                 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
849                                                                 name << ", for key: " << key << "." << std::endl;
850                                                 ifs.putback(ch);
851                                                 break;
852                                         }
853
854                                         // read field value
855                                         if (!readValue(value, ifs, strings)) {
856                                                 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
857                                                                 name << ", for key: " << key << "." << std::endl;
858                                                 break;
859                                         }
860
861                                         keyvalmap[name] = value;
862                                         data += "\n\n" + value;
863                                         keylist.addFieldName(name);
864                                         readNext = removeWSAndComma(ifs);
865                                 }
866
867                                 // add the new entry
868                                 keylist.addEntryType(entryType);
869                                 keyvalmap.setAllData(data);
870                                 keylist[key] = keyvalmap;
871                         } //< else (citation entry)
872                 } //< searching '@'
873         } //< for loop over files
874
875         buffer().addBiblioInfo(keylist);
876 }
877
878
879 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
880 {
881         string texfile = changeExtension(to_utf8(filename), "bib");
882         // note that, if the filename can be found directly from the path, 
883         // findtexfile will just return a FileName object for that path.
884         FileName file(findtexfile(texfile, "bib"));
885         if (file.empty())
886                 file = FileName(makeAbsPath(texfile, buf.filePath()));
887         return file;
888 }
889  
890
891 bool InsetBibtex::addDatabase(docstring const & db)
892 {
893         docstring bibfiles = getParam("bibfiles");
894         if (tokenPos(bibfiles, ',', db) != -1)
895                 return false;
896         if (!bibfiles.empty())
897                 bibfiles += ',';
898         setParam("bibfiles", bibfiles + db);
899         return true;
900 }
901
902
903 bool InsetBibtex::delDatabase(docstring const & db)
904 {
905         docstring bibfiles = getParam("bibfiles");
906         if (contains(bibfiles, db)) {
907                 int const n = tokenPos(bibfiles, ',', db);
908                 docstring bd = db;
909                 if (n > 0) {
910                         // this is not the first database
911                         docstring tmp = ',' + bd;
912                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
913                 } else if (n == 0)
914                         // this is the first (or only) database
915                         setParam("bibfiles", split(bibfiles, bd, ','));
916                 else
917                         return false;
918         }
919         return true;
920 }
921
922
923 void InsetBibtex::validate(LaTeXFeatures & features) const
924 {
925         if (features.bufferParams().use_bibtopic)
926                 features.require("bibtopic");
927         // FIXME XHTML
928         // It'd be better to be able to get this from an InsetLayout, but at present
929         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
930         if (features.runparams().flavor == OutputParams::HTML)
931                 features.addPreambleSnippet("<style type=\"text/css\">\n"
932                         "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
933                         "span.bibtexlabel:before{ content: \"[\"; }\n"
934                         "span.bibtexlabel:after{ content: \"] \"; }\n"
935                         "</style>");
936 }
937
938
939 // FIXME 
940 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
941 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
942 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
943 {
944         BiblioInfo const & bibinfo = buffer().masterBibInfo();
945         vector<docstring> const & cites = bibinfo.citedEntries();
946         CiteEngine const engine = buffer().params().citeEngine();
947         bool const numbers = 
948                 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
949
950         docstring reflabel = from_ascii("References");
951         Language const * l = buffer().params().language;
952         if (l)
953                 reflabel = translateIfPossible(reflabel, l->code());
954                 
955         xs << html::StartTag("h2", "class='bibtex'")
956                 << reflabel
957                 << html::EndTag("h2")
958                 << html::StartTag("div", "class='bibtex'");
959
960         // Now we loop over the entries
961         vector<docstring>::const_iterator vit = cites.begin();
962         vector<docstring>::const_iterator const ven = cites.end();
963         for (; vit != ven; ++vit) {
964                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
965                 if (biit == bibinfo.end())
966                         continue;
967                 BibTeXInfo const & entry = biit->second;
968                 xs << html::StartTag("div", "class='bibtexentry'");
969                 // FIXME XHTML
970                 // The same name/id problem we have elsewhere.
971                 string const attr = "id='" + to_utf8(entry.key()) + "'";
972                 xs << html::CompTag("a", attr);
973                 docstring citekey;
974                 if (numbers)
975                         citekey = entry.citeNumber();
976                 else {
977                         docstring const auth = entry.getAbbreviatedAuthor();
978                         // we do it this way so as to access the xref, if necessary
979                         // note that this also gives us the modifier
980                         docstring const year = bibinfo.getYear(*vit, true);
981                         if (!auth.empty() && !year.empty())
982                                 citekey = auth + ' ' + year;
983                 }
984                 if (citekey.empty()) {
985                         citekey = entry.label();
986                         if (citekey.empty())
987                                 citekey = entry.key();
988                 }
989                 xs << html::StartTag("span", "class='bibtexlabel'")
990                         << citekey
991                         << html::EndTag("span");
992                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
993                 // which will give us all the cross-referenced info. But for every
994                 // entry, so there's a lot of repitition. This should be fixed.
995                 xs << html::StartTag("span", "class='bibtexinfo'") 
996                         << XHTMLStream::ESCAPE_AND
997                         << bibinfo.getInfo(entry.key(), buffer(), true)
998                         << html::EndTag("span")
999                         << html::EndTag("div");
1000                 xs.cr();
1001         }
1002         xs << html::EndTag("div");
1003         return docstring();
1004 }
1005
1006
1007 docstring InsetBibtex::contextMenuName() const
1008 {
1009         return from_ascii("context-bibtex");
1010 }
1011
1012
1013 } // namespace lyx