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