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