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