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