]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
Prevent a crash when destroying insets whose Buffers have been closed.
[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 "OutputParams.h"
26 #include "TextClass.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/convert.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/ExceptionMessage.h"
34 #include "support/filetools.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/os.h"
38 #include "support/Path.h"
39 #include "support/textutils.h"
40
41 #include <limits>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47
48 namespace Alert = frontend::Alert;
49 namespace os = support::os;
50
51
52 InsetBibtex::InsetBibtex(Buffer const & buf, InsetCommandParams const & p)
53         : InsetCommand(p, "bibtex")
54 {
55         Inset::setBuffer(const_cast<Buffer &>(buf));
56         buffer_->invalidateBibinfoCache();
57 }
58
59
60 InsetBibtex::~InsetBibtex()
61 {
62         if (isBufferValid())
63                 buffer_->invalidateBibinfoCache();
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.noUpdate();
93                                 break;
94                         }
95                 } catch (ExceptionMessage const & message) {
96                         if (message.type_ == WarningException) {
97                                 Alert::warning(message.title_, message.details_);
98                                 cur.noUpdate();
99                         } else 
100                                 throw message;
101                         break;
102                 }
103                 //
104                 setParams(p);
105                 buffer().updateBibfilesCache();
106                 break;
107         }
108
109         default:
110                 InsetCommand::doDispatch(cur, cmd);
111                 break;
112         }
113 }
114
115
116 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
117                 FuncStatus & flag) const
118 {
119         switch (cmd.action) {
120         case LFUN_INSET_EDIT:
121                 flag.setEnabled(true);
122                 return true;
123
124         default:
125                 return InsetCommand::getStatus(cur, cmd, flag);
126         }
127 }
128
129
130 void InsetBibtex::editDatabases() const
131 {
132         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
133
134         if (bibfilelist.empty())
135                 return;
136
137         int nr_databases = bibfilelist.size();
138         if (nr_databases > 1) {
139                         docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
140                                                        "If you proceed, all of them will be opened."),
141                                                         convert<docstring>(nr_databases));
142                         int const ret = Alert::prompt(_("Open Databases?"),
143                                 message, 0, 1, _("&Cancel"), _("&Proceed"));
144
145                         if (ret == 0)
146                                 return;
147         }
148
149         vector<docstring>::const_iterator it = bibfilelist.begin();
150         vector<docstring>::const_iterator en = bibfilelist.end();
151         for (; it != en; ++it) {
152                 FileName bibfile = getBibTeXPath(*it, buffer());
153                 formats.edit(buffer(), bibfile,
154                      formats.getFormatFromFile(bibfile));
155         }
156 }
157
158
159 docstring InsetBibtex::screenLabel() const
160 {
161         return _("BibTeX Generated Bibliography");
162 }
163
164
165 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
166 {
167         docstring item = from_ascii("* ");
168         docstring tip = _("Databases:") + "\n";
169         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
170
171         if (bibfilelist.empty()) {
172                 tip += item;
173                 tip += _("none");
174         } else {
175                 vector<docstring>::const_iterator it = bibfilelist.begin();
176                 vector<docstring>::const_iterator en = bibfilelist.end();
177                 for (; it != en; ++it) {
178                         tip += item;
179                         tip += *it + "\n";
180                 }
181         }
182
183         // Style-Options
184         bool toc = false;
185         docstring style = getParam("options"); // maybe empty! and with bibtotoc
186         docstring bibtotoc = from_ascii("bibtotoc");
187         if (prefixIs(style, bibtotoc)) {
188                 toc = true;
189                 if (contains(style, char_type(',')))
190                         style = split(style, bibtotoc, char_type(','));
191         }
192
193         tip += _("Style File:") +"\n";
194         tip += item;
195         if (!style.empty())
196                 tip += style;
197         else
198                 tip += _("none");
199
200         tip += "\n" + _("Lists:") + " ";
201         docstring btprint = getParam("btprint");
202                 if (btprint == "btPrintAll")
203                         tip += _("all references");
204                 else if (btprint == "btPrintNotCited")
205                         tip += _("all uncited references");
206                 else
207                         tip += _("all cited references");
208         
209         if (toc) {
210                 tip += ", ";
211                 tip += _("included in TOC");
212         }
213
214         return tip;
215 }
216
217
218 static string normalizeName(Buffer const & buffer,
219         OutputParams const & runparams, string const & name, string const & ext)
220 {
221         string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
222         if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
223                 return name;
224         if (!runparams.nice)
225                 return fname;
226
227         // FIXME UNICODE
228         return to_utf8(makeRelPath(from_utf8(fname),
229                                          from_utf8(buffer.masterBuffer()->filePath())));
230 }
231
232
233 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
234 {
235         // the sequence of the commands:
236         // 1. \bibliographystyle{style}
237         // 2. \addcontentsline{...} - if option bibtotoc set
238         // 3. \bibliography{database}
239         // and with bibtopic:
240         // 1. \bibliographystyle{style}
241         // 2. \begin{btSect}{database}
242         // 3. \btPrint{Cited|NotCited|All}
243         // 4. \end{btSect}
244
245         // Database(s)
246         // If we are processing the LaTeX file in a temp directory then
247         // copy the .bib databases to this temp directory, mangling their
248         // names in the process. Store this mangled name in the list of
249         // all databases.
250         // (We need to do all this because BibTeX *really*, *really*
251         // can't handle "files with spaces" and Windows users tend to
252         // use such filenames.)
253         // Otherwise, store the (maybe absolute) path to the original,
254         // unmangled database name.
255         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
256         vector<docstring>::const_iterator it = bibfilelist.begin();
257         vector<docstring>::const_iterator en = bibfilelist.end();
258         odocstringstream dbs;
259         bool didone = false;
260
261         for (; it != en; ++it) {
262                 string utf8input = to_utf8(*it);
263                 string database =
264                         normalizeName(buffer(), runparams, utf8input, ".bib");
265                 FileName const try_in_file =
266                         makeAbsPath(database + ".bib", buffer().filePath());
267                 bool const not_from_texmf = try_in_file.isReadableFile();
268
269                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
270                     not_from_texmf) {
271
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
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
321         // line count
322         int nlines = 0;
323
324         if (!style.empty()) {
325                 string base = normalizeName(buffer(), runparams, style, ".bst");
326                 FileName const try_in_file = 
327                         makeAbsPath(base + ".bst", buffer().filePath());
328                 bool const not_from_texmf = try_in_file.isReadableFile();
329                 // If this style does not come from texmf and we are not
330                 // exporting to .tex copy it to the tmp directory.
331                 // This prevents problems with spaces and 8bit charcaters
332                 // in the file name.
333                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
334                     not_from_texmf) {
335                         // use new style name
336                         DocFileName const in_file = DocFileName(try_in_file);
337                         base = removeExtension(in_file.mangledFilename());
338                         FileName const out_file = makeAbsPath(base + ".bst",
339                                         buffer().masterBuffer()->temppath());
340                         bool const success = in_file.copyTo(out_file);
341                         if (!success) {
342                                 lyxerr << "Failed to copy '" << in_file
343                                        << "' to '" << out_file << "'"
344                                        << endl;
345                         }
346                 }
347                 // FIXME UNICODE
348                 os << "\\bibliographystyle{"
349                    << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
350                    << "}\n";
351                 nlines += 1;
352         }
353
354         // Post this warning only once.
355         static bool warned_about_bst_spaces = false;
356         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
357                 warned_about_bst_spaces = true;
358                 Alert::warning(_("Export Warning!"),
359                                _("There are spaces in the path to your BibTeX style file.\n"
360                                               "BibTeX will be unable to find it."));
361         }
362
363         if (!db_out.empty() && buffer().params().use_bibtopic) {
364                 os << "\\begin{btSect}{" << db_out << "}\n";
365                 docstring btprint = getParam("btprint");
366                 if (btprint.empty())
367                         // default
368                         btprint = from_ascii("btPrintCited");
369                 os << "\\" << btprint << "\n"
370                    << "\\end{btSect}\n";
371                 nlines += 3;
372         }
373
374         // bibtotoc-Option
375         if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
376                 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
377                         if (buffer().params().sides == OneSide) {
378                                 // oneside
379                                 os << "\\clearpage";
380                         } else {
381                                 // twoside
382                                 os << "\\cleardoublepage";
383                         }
384                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
385                 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
386                         os << "\\addcontentsline{toc}{section}{\\refname}";
387         }
388
389         if (!db_out.empty() && !buffer().params().use_bibtopic) {
390                 docstring btprint = getParam("btprint");
391                 if (btprint == "btPrintAll") {
392                         os << "\\nocite{*}\n";
393                         nlines += 1;
394                 }
395                 os << "\\bibliography{" << db_out << "}\n";
396                 nlines += 1;
397         }
398
399         return nlines;
400 }
401
402
403 support::FileNameList InsetBibtex::getBibFiles() const
404 {
405         FileName path(buffer().filePath());
406         support::PathChanger p(path);
407         
408         support::FileNameList vec;
409         
410         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
411         vector<docstring>::const_iterator it = bibfilelist.begin();
412         vector<docstring>::const_iterator en = bibfilelist.end();
413         for (; it != en; ++it) {
414                 FileName const file = 
415                         findtexfile(changeExtension(to_utf8(*it), "bib"), "bib");
416
417                 if (!file.empty())
418                         vec.push_back(file);
419                 else
420                         LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
421         }
422         
423         return vec;
424
425 }
426
427 namespace {
428
429         // methods for parsing bibtex files
430
431         typedef map<docstring, docstring> VarMap;
432
433         /// remove whitespace characters, optionally a single comma,
434         /// and further whitespace characters from the stream.
435         /// @return true if a comma was found, false otherwise
436         ///
437         bool removeWSAndComma(idocfstream & ifs) {
438                 char_type ch;
439
440                 if (!ifs)
441                         return false;
442
443                 // skip whitespace
444                 do {
445                         ifs.get(ch);
446                 } while (ifs && isSpace(ch));
447
448                 if (!ifs)
449                         return false;
450
451                 if (ch != ',') {
452                         ifs.putback(ch);
453                         return false;
454                 }
455
456                 // skip whitespace
457                 do {
458                         ifs.get(ch);
459                 } while (ifs && isSpace(ch));
460
461                 if (ifs) {
462                         ifs.putback(ch);
463                 }
464
465                 return true;
466         }
467
468
469         enum charCase {
470                 makeLowerCase,
471                 keepCase
472         };
473
474         /// remove whitespace characters, read characer sequence
475         /// not containing whitespace characters or characters in
476         /// delimChars, and remove further whitespace characters.
477         ///
478         /// @return true if a string of length > 0 could be read.
479         ///
480         bool readTypeOrKey(docstring & val, idocfstream & ifs,
481                 docstring const & delimChars, docstring const &illegalChars, 
482                 charCase chCase) {
483
484                 char_type ch;
485
486                 val.clear();
487
488                 if (!ifs)
489                         return false;
490
491                 // skip whitespace
492                 do {
493                         ifs.get(ch);
494                 } while (ifs && isSpace(ch));
495
496                 if (!ifs)
497                         return false;
498
499                 // read value
500                 bool legalChar = true;
501                 while (ifs && !isSpace(ch) && 
502                                                  delimChars.find(ch) == docstring::npos &&
503                                                  (legalChar = (illegalChars.find(ch) == docstring::npos))
504                                         ) 
505                 {
506                         if (chCase == makeLowerCase)
507                                 val += lowercase(ch);
508                         else
509                                 val += ch;
510                         ifs.get(ch);
511                 }
512                 
513                 if (!legalChar) {
514                         ifs.putback(ch);
515                         return false;
516                 }
517
518                 // skip whitespace
519                 while (ifs && isSpace(ch)) {
520                         ifs.get(ch);
521                 }
522
523                 if (ifs) {
524                         ifs.putback(ch);
525                 }
526
527                 return val.length() > 0;
528         }
529
530         /// read subsequent bibtex values that are delimited with a #-character.
531         /// Concatenate all parts and replace names with the associated string in
532         /// the variable strings.
533         /// @return true if reading was successfull (all single parts were delimited
534         /// correctly)
535         bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
536
537                 char_type ch;
538
539                 val.clear();
540
541                 if (!ifs)
542                         return false;
543
544                 do {
545                         // skip whitespace
546                         do {
547                                 ifs.get(ch);
548                         } while (ifs && isSpace(ch));
549
550                         if (!ifs)
551                                 return false;
552
553                         // check for field type
554                         if (isDigit(ch)) {
555
556                                 // read integer value
557                                 do {
558                                         val += ch;
559                                         ifs.get(ch);
560                                 } while (ifs && isDigit(ch));
561
562                                 if (!ifs)
563                                         return false;
564
565                         } else if (ch == '"' || ch == '{') {
566                                 // set end delimiter
567                                 char_type delim = ch == '"' ? '"': '}';
568
569                                 // Skip whitespace
570                                 do {
571                                         ifs.get(ch);
572                                 } while (ifs && isSpace(ch));
573                                 
574                                 if (!ifs)
575                                         return false;
576                                 
577                                 // We now have the first non-whitespace character
578                                 // We'll collapse adjacent whitespace.
579                                 bool lastWasWhiteSpace = false;
580                                 
581                                 // inside this delimited text braces must match.
582                                 // Thus we can have a closing delimiter only
583                                 // when nestLevel == 0
584                                 int nestLevel = 0;
585  
586                                 while (ifs && (nestLevel > 0 || ch != delim)) {
587                                         if (isSpace(ch)) {
588                                                 lastWasWhiteSpace = true;
589                                                 ifs.get(ch);
590                                                 continue;
591                                         }
592                                         // We output the space only after we stop getting 
593                                         // whitespace so as not to output any whitespace
594                                         // at the end of the value.
595                                         if (lastWasWhiteSpace) {
596                                                 lastWasWhiteSpace = false;
597                                                 val += ' ';
598                                         }
599                                         
600                                         val += ch;
601
602                                         // update nesting level
603                                         switch (ch) {
604                                                 case '{':
605                                                         ++nestLevel;
606                                                         break;
607                                                 case '}':
608                                                         --nestLevel;
609                                                         if (nestLevel < 0) return false;
610                                                         break;
611                                         }
612
613                                         ifs.get(ch);
614                                 }
615
616                                 if (!ifs)
617                                         return false;
618
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                 idocfstream 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 << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
710                                 continue;
711                         }
712
713                         if (!ifs) {
714                                 lyxerr << "InsetBibtex::fillWithBibKeys: 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 << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
726                                 break;
727                         }
728
729                         if ((ch != '(') && (ch != '{')) {
730                                 lyxerr << "InsetBibtex::fillWithBibKeys: 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 << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
745                                         continue;
746                                 }
747
748                                 if (!ifs) {
749                                         lyxerr << "InsetBibtex::fillWithBibKeys: 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 << "InsetBibtex::fillWithBibKeys: No `=' after string name: " << 
757                                                         name << "." << std::endl;
758                                         continue;
759                                 }
760
761                                 if (!readValue(value, ifs, strings)) {
762                                         lyxerr << "InsetBibtex::fillWithBibKeys: 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 << "InsetBibtex::fillWithBibKeys: 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 << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" << 
787                                                         entryType << "." << std::endl;
788                                         continue;
789                                 }
790
791                                 if (!ifs) {
792                                         lyxerr << "InsetBibtex::fillWithBibKeys: 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 fields;
805                                 docstring name;
806                                 docstring value;
807                                 docstring commaNewline;
808                                 docstring data;
809                                 BibTeXInfo keyvalmap(key, entryType);
810                                 
811                                 bool readNext = removeWSAndComma(ifs);
812  
813                                 while (ifs && readNext) {
814
815                                         // read field name
816                                         if (!readTypeOrKey(name, ifs, from_ascii("="), 
817                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
818                                                 break;
819
820                                         // next char must be an equal sign
821                                         ifs.get(ch);
822                                         if (!ifs) {
823                                                 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
824                                                 break;
825                                         }
826                                         if (ch != '=') {
827                                                 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
828                                                                 name << ", for key: " << key << "." << std::endl;
829                                                 ifs.putback(ch);
830                                                 break;
831                                         }
832
833                                         // read field value
834                                         if (!readValue(value, ifs, strings)) {
835                                                 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
836                                                                 name << ", for key: " << key << "." << std::endl;
837                                                 break;
838                                         }
839
840                                         keyvalmap[name] = value;
841                                         data += "\n\n" + value;
842                                         keylist.addFieldName(name);
843                                         readNext = removeWSAndComma(ifs);
844                                 }
845
846                                 // add the new entry
847                                 keylist.addEntryType(entryType);
848                                 keyvalmap.setAllData(data);
849                                 keylist[key] = keyvalmap;
850                         } //< else (citation entry)
851                 } //< searching '@'
852         } //< for loop over files
853 }
854
855
856 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
857 {
858         string texfile = changeExtension(to_utf8(filename), "bib");
859         // note that, if the filename can be found directly from the path, 
860         // findtexfile will just return a FileName object for that path.
861         FileName file(findtexfile(texfile, "bib"));
862         if (file.empty())
863                 file = FileName(makeAbsPath(texfile, buf.filePath()));
864         return file;
865 }
866  
867
868 bool InsetBibtex::addDatabase(docstring const & db)
869 {
870         docstring bibfiles = getParam("bibfiles");
871         if (tokenPos(bibfiles, ',', db) != -1)
872                 return false;
873         if (!bibfiles.empty())
874                 bibfiles += ',';
875         setParam("bibfiles", bibfiles + db);
876         return true;
877 }
878
879
880 bool InsetBibtex::delDatabase(docstring const & db)
881 {
882         docstring bibfiles = getParam("bibfiles");
883         if (contains(bibfiles, db)) {
884                 int const n = tokenPos(bibfiles, ',', db);
885                 docstring bd = db;
886                 if (n > 0) {
887                         // this is not the first database
888                         docstring tmp = ',' + bd;
889                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
890                 } else if (n == 0)
891                         // this is the first (or only) database
892                         setParam("bibfiles", split(bibfiles, bd, ','));
893                 else
894                         return false;
895         }
896         return true;
897 }
898
899
900 void InsetBibtex::validate(LaTeXFeatures & features) const
901 {
902         if (features.bufferParams().use_bibtopic)
903                 features.require("bibtopic");
904 }
905
906
907 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
908 {
909         return from_ascii("context-bibtex");
910 }
911
912
913 } // namespace lyx