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