]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
a3affb4d9363d2dea8a65164157618294cf6a0c7
[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                         // mangledFilename() needs the extension
272                         DocFileName const in_file = DocFileName(try_in_file);
273                         database = removeExtension(in_file.mangledFilename());
274                         FileName const out_file = makeAbsPath(database + ".bib",
275                                         buffer().masterBuffer()->temppath());
276
277                         bool const success = in_file.copyTo(out_file);
278                         if (!success) {
279                                 lyxerr << "Failed to copy '" << in_file
280                                        << "' to '" << out_file << "'"
281                                        << endl;
282                         }
283                 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
284                            !isValidLaTeXFilename(database)) {
285                                 frontend::Alert::warning(_("Invalid filename"),
286                                                          _("The following filename is likely to cause trouble "
287                                                            "when running the exported file through LaTeX: ") +
288                                                             from_utf8(database));
289                 }
290
291                 if (didone)
292                         dbs << ',';
293                 else 
294                         didone = true;
295                 // FIXME UNICODE
296                 dbs << from_utf8(latex_path(database));
297         }
298         docstring const db_out = dbs.str();
299
300         // Post this warning only once.
301         static bool warned_about_spaces = false;
302         if (!warned_about_spaces &&
303             runparams.nice && db_out.find(' ') != docstring::npos) {
304                 warned_about_spaces = true;
305                 Alert::warning(_("Export Warning!"),
306                                _("There are spaces in the paths to your BibTeX databases.\n"
307                                               "BibTeX will be unable to find them."));
308         }
309         // Style-Options
310         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
311         string bibtotoc;
312         if (prefixIs(style, "bibtotoc")) {
313                 bibtotoc = "bibtotoc";
314                 if (contains(style, ','))
315                         style = split(style, bibtotoc, ',');
316         }
317
318         // line count
319         int nlines = 0;
320
321         if (!style.empty()) {
322                 string base = normalizeName(buffer(), runparams, style, ".bst");
323                 FileName const try_in_file = 
324                         makeAbsPath(base + ".bst", buffer().filePath());
325                 bool const not_from_texmf = try_in_file.isReadableFile();
326                 // If this style does not come from texmf and we are not
327                 // exporting to .tex copy it to the tmp directory.
328                 // This prevents problems with spaces and 8bit charcaters
329                 // in the file name.
330                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
331                     not_from_texmf) {
332                         // use new style name
333                         DocFileName const in_file = DocFileName(try_in_file);
334                         base = removeExtension(in_file.mangledFilename());
335                         FileName const out_file = makeAbsPath(base + ".bst",
336                                         buffer().masterBuffer()->temppath());
337                         bool const success = in_file.copyTo(out_file);
338                         if (!success) {
339                                 lyxerr << "Failed to copy '" << in_file
340                                        << "' to '" << out_file << "'"
341                                        << endl;
342                         }
343                 }
344                 // FIXME UNICODE
345                 os << "\\bibliographystyle{"
346                    << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
347                    << "}\n";
348                 nlines += 1;
349         }
350
351         // Post this warning only once.
352         static bool warned_about_bst_spaces = false;
353         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
354                 warned_about_bst_spaces = true;
355                 Alert::warning(_("Export Warning!"),
356                                _("There are spaces in the path to your BibTeX style file.\n"
357                                               "BibTeX will be unable to find it."));
358         }
359
360         if (!db_out.empty() && buffer().params().use_bibtopic) {
361                 os << "\\begin{btSect}{" << db_out << "}\n";
362                 docstring btprint = getParam("btprint");
363                 if (btprint.empty())
364                         // default
365                         btprint = from_ascii("btPrintCited");
366                 os << "\\" << btprint << "\n"
367                    << "\\end{btSect}\n";
368                 nlines += 3;
369         }
370
371         // bibtotoc-Option
372         if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
373                 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
374                         if (buffer().params().sides == OneSide) {
375                                 // oneside
376                                 os << "\\clearpage";
377                         } else {
378                                 // twoside
379                                 os << "\\cleardoublepage";
380                         }
381                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
382                 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
383                         os << "\\addcontentsline{toc}{section}{\\refname}";
384         }
385
386         if (!db_out.empty() && !buffer().params().use_bibtopic) {
387                 docstring btprint = getParam("btprint");
388                 if (btprint == "btPrintAll") {
389                         os << "\\nocite{*}\n";
390                         nlines += 1;
391                 }
392                 os << "\\bibliography{" << db_out << "}\n";
393                 nlines += 1;
394         }
395
396         return nlines;
397 }
398
399
400 support::FileNameList InsetBibtex::getBibFiles() const
401 {
402         FileName path(buffer().filePath());
403         support::PathChanger p(path);
404         
405         support::FileNameList vec;
406         
407         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
408         vector<docstring>::const_iterator it = bibfilelist.begin();
409         vector<docstring>::const_iterator en = bibfilelist.end();
410         for (; it != en; ++it) {
411                 FileName const file = 
412                         findtexfile(changeExtension(to_utf8(*it), "bib"), "bib");
413
414                 if (!file.empty())
415                         vec.push_back(file);
416                 else
417                         LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
418         }
419         
420         return vec;
421
422 }
423
424 namespace {
425
426         // methods for parsing bibtex files
427
428         typedef map<docstring, docstring> VarMap;
429
430         /// remove whitespace characters, optionally a single comma,
431         /// and further whitespace characters from the stream.
432         /// @return true if a comma was found, false otherwise
433         ///
434         bool removeWSAndComma(ifdocstream & ifs) {
435                 char_type ch;
436
437                 if (!ifs)
438                         return false;
439
440                 // skip whitespace
441                 do {
442                         ifs.get(ch);
443                 } while (ifs && isSpace(ch));
444
445                 if (!ifs)
446                         return false;
447
448                 if (ch != ',') {
449                         ifs.putback(ch);
450                         return false;
451                 }
452
453                 // skip whitespace
454                 do {
455                         ifs.get(ch);
456                 } while (ifs && isSpace(ch));
457
458                 if (ifs) {
459                         ifs.putback(ch);
460                 }
461
462                 return true;
463         }
464
465
466         enum charCase {
467                 makeLowerCase,
468                 keepCase
469         };
470
471         /// remove whitespace characters, read characer sequence
472         /// not containing whitespace characters or characters in
473         /// delimChars, and remove further whitespace characters.
474         ///
475         /// @return true if a string of length > 0 could be read.
476         ///
477         bool readTypeOrKey(docstring & val, ifdocstream & ifs,
478                 docstring const & delimChars, docstring const &illegalChars, 
479                 charCase chCase) {
480
481                 char_type ch;
482
483                 val.clear();
484
485                 if (!ifs)
486                         return false;
487
488                 // skip whitespace
489                 do {
490                         ifs.get(ch);
491                 } while (ifs && isSpace(ch));
492
493                 if (!ifs)
494                         return false;
495
496                 // read value
497                 bool legalChar = true;
498                 while (ifs && !isSpace(ch) && 
499                                                  delimChars.find(ch) == docstring::npos &&
500                                                  (legalChar = (illegalChars.find(ch) == docstring::npos))
501                                         ) 
502                 {
503                         if (chCase == makeLowerCase)
504                                 val += lowercase(ch);
505                         else
506                                 val += ch;
507                         ifs.get(ch);
508                 }
509                 
510                 if (!legalChar) {
511                         ifs.putback(ch);
512                         return false;
513                 }
514
515                 // skip whitespace
516                 while (ifs && isSpace(ch)) {
517                         ifs.get(ch);
518                 }
519
520                 if (ifs) {
521                         ifs.putback(ch);
522                 }
523
524                 return val.length() > 0;
525         }
526
527         /// read subsequent bibtex values that are delimited with a #-character.
528         /// Concatenate all parts and replace names with the associated string in
529         /// the variable strings.
530         /// @return true if reading was successfull (all single parts were delimited
531         /// correctly)
532         bool readValue(docstring & value, ifdocstream & ifs, const VarMap & strings) {
533
534                 char_type ch;
535
536                 value.clear();
537
538                 if (!ifs)
539                         return false;
540
541                 docstring val;
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                 // Ok, we now have the value. Now we are going to go
659                 // through it and replace e.g. \"a with its unicode value.
660                 // We'll also strip commands, like \emph, and the like, so 
661                 // it will look nice in the UI.
662                 bool scanning_cmd = false;
663                 bool scanning_math = false;
664                 bool escaped = false; // used to catch \$, etc.
665                 while (val.size()) {
666                         char_type const ch = val[0];
667
668                         // if we're scanning math, we output everything until we
669                         // find an unescaped $, at which point we break out.
670                         if (scanning_math) {
671                                 if (escaped)
672                                         escaped = false;
673                                 else if (ch == '\\')
674                                         escaped = true;
675                                 else if (ch == '$') 
676                                         scanning_math = false;
677                                 value += ch;
678                                 val = val.substr(1);
679                                 continue;
680                         }
681
682                         // if we're scanning a command name, then we just
683                         // discard characters until we hit something that
684                         // isn't alpha.
685                         if (scanning_cmd) {
686                                 if (isAlphaASCII(ch)) {
687                                         val = val.substr(1);
688                                         escaped = false;
689                                         continue;
690                                 }
691                                 // so we're done with this command.
692                                 // now we fall through and check this character.
693                                 scanning_cmd = false;
694                         }
695
696                         // was the last character a \? If so, then this is something like: \\,
697                         // or \$, so we'll just output it. That's probably not always right...
698                         if (escaped) {
699                                 value += ch;
700                                 val = val.substr(1);
701                                 escaped = false;
702                                 continue;
703                         }
704
705                         if (ch == '$') {
706                                 value += ch;
707                                 val = val.substr(1);
708                                 scanning_math = true;
709                                 continue;
710                         }
711
712                         // we just ignore braces
713                         if (ch == '{' || ch == '}') {
714                                 val = val.substr(1);
715                                 continue;
716                         }
717
718                         // we're going to check things that look like commands, so if
719                         // this doesn't, just output it.
720                         if (ch != '\\') {
721                                 value += ch;
722                                 val = val.substr(1);
723                                 continue;
724                         }
725
726                         // ok, could be a command of some sort
727                         // let's see if it corresponds to some unicode
728                         docstring rem;
729                         docstring const cnvtd = Encodings::fromLaTeXCommand(val, rem);
730                         if (!cnvtd.empty()) {
731                                 // it did, so we'll take that bit and proceed with what's left
732                                 value += cnvtd;
733                                 val = rem;
734                                 continue;
735                         }
736                         // it's a command of some sort
737                         scanning_cmd = true;
738                         escaped = true;
739                         val = val.substr(1);
740                 }
741
742                 return true;
743         }
744 }
745
746
747 // This method returns a comma separated list of Bibtex entries
748 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
749         InsetIterator const & /*di*/) const
750 {
751         // This bibtex parser is a first step to parse bibtex files
752         // more precisely.
753         //
754         // - it reads the whole bibtex entry and does a syntax check
755         //   (matching delimiters, missing commas,...
756         // - it recovers from errors starting with the next @-character
757         // - it reads @string definitions and replaces them in the
758         //   field values.
759         // - it accepts more characters in keys or value names than
760         //   bibtex does.
761         //
762         // Officially bibtex does only support ASCII, but in practice
763         // you can use the encoding of the main document as long as
764         // some elements like keys and names are pure ASCII. Therefore
765         // we convert the file from the buffer encoding.
766         // We don't restrict keys to ASCII in LyX, since our own
767         // InsetBibitem can generate non-ASCII keys, and nonstandard
768         // 8bit clean bibtex forks exist.
769         support::FileNameList const files = getBibFiles();
770         support::FileNameList::const_iterator it = files.begin();
771         support::FileNameList::const_iterator en = files.end();
772         for (; it != en; ++ it) {
773                 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
774                         ios_base::in, buffer().params().encoding().iconvName());
775
776                 char_type ch;
777                 VarMap strings;
778
779                 while (ifs) {
780
781                         ifs.get(ch);
782                         if (!ifs)
783                                 break;
784
785                         if (ch != '@')
786                                 continue;
787
788                         docstring entryType;
789
790                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
791                                 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
792                                 continue;
793                         }
794
795                         if (!ifs) {
796                                 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
797                                 continue;
798                         }
799
800                         if (entryType == from_ascii("comment")) {
801                                 ifs.ignore(numeric_limits<int>::max(), '\n');
802                                 continue;
803                         }
804
805                         ifs.get(ch);
806                         if (!ifs) {
807                                 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
808                                 break;
809                         }
810
811                         if ((ch != '(') && (ch != '{')) {
812                                 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
813                                 ifs.putback(ch);
814                                 continue;
815                         }
816
817                         // process the entry
818                         if (entryType == from_ascii("string")) {
819
820                                 // read string and add it to the strings map
821                                 // (or replace it's old value)
822                                 docstring name;
823                                 docstring value;
824
825                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
826                                         lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
827                                         continue;
828                                 }
829
830                                 if (!ifs) {
831                                         lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
832                                         continue;
833                                 }
834
835                                 // next char must be an equal sign
836                                 ifs.get(ch);
837                                 if (!ifs || ch != '=') {
838                                         lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " << 
839                                                         name << "." << std::endl;
840                                         continue;
841                                 }
842
843                                 if (!readValue(value, ifs, strings)) {
844                                         lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " << 
845                                                         name << "." << std::endl;
846                                         continue;
847                                 }
848
849                                 strings[name] = value;
850
851                         } else if (entryType == from_ascii("preamble")) {
852
853                                 // preamble definitions are discarded.
854                                 // can they be of any use in lyx?
855                                 docstring value;
856
857                                 if (!readValue(value, ifs, strings)) {
858                                         lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
859                                         continue;
860                                 }
861
862                         } else {
863
864                                 // Citation entry. Try to read the key.
865                                 docstring key;
866
867                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
868                                         lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" << 
869                                                         entryType << "." << std::endl;
870                                         continue;
871                                 }
872
873                                 if (!ifs) {
874                                         lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
875                                         continue;
876                                 }
877
878                                 /////////////////////////////////////////////
879                                 // now we have a key, so we will add an entry 
880                                 // (even if it's empty, as bibtex does)
881                                 //
882                                 // we now read the field = value pairs.
883                                 // all items must be separated by a comma. If
884                                 // it is missing the scanning of this entry is
885                                 // stopped and the next is searched.
886                                 docstring fields;
887                                 docstring name;
888                                 docstring value;
889                                 docstring commaNewline;
890                                 docstring data;
891                                 BibTeXInfo keyvalmap(key, entryType);
892                                 
893                                 bool readNext = removeWSAndComma(ifs);
894  
895                                 while (ifs && readNext) {
896
897                                         // read field name
898                                         if (!readTypeOrKey(name, ifs, from_ascii("="), 
899                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
900                                                 break;
901
902                                         // next char must be an equal sign
903                                         ifs.get(ch);
904                                         if (!ifs) {
905                                                 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
906                                                 break;
907                                         }
908                                         if (ch != '=') {
909                                                 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
910                                                                 name << ", for key: " << key << "." << std::endl;
911                                                 ifs.putback(ch);
912                                                 break;
913                                         }
914
915                                         // read field value
916                                         if (!readValue(value, ifs, strings)) {
917                                                 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
918                                                                 name << ", for key: " << key << "." << std::endl;
919                                                 break;
920                                         }
921
922                                         keyvalmap[name] = value;
923                                         data += "\n\n" + value;
924                                         keylist.addFieldName(name);
925                                         readNext = removeWSAndComma(ifs);
926                                 }
927
928                                 // add the new entry
929                                 keylist.addEntryType(entryType);
930                                 keyvalmap.setAllData(data);
931                                 keylist[key] = keyvalmap;
932                         } //< else (citation entry)
933                 } //< searching '@'
934         } //< for loop over files
935 }
936
937
938 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
939 {
940         string texfile = changeExtension(to_utf8(filename), "bib");
941         // note that, if the filename can be found directly from the path, 
942         // findtexfile will just return a FileName object for that path.
943         FileName file(findtexfile(texfile, "bib"));
944         if (file.empty())
945                 file = FileName(makeAbsPath(texfile, buf.filePath()));
946         return file;
947 }
948  
949
950 bool InsetBibtex::addDatabase(docstring const & db)
951 {
952         docstring bibfiles = getParam("bibfiles");
953         if (tokenPos(bibfiles, ',', db) != -1)
954                 return false;
955         if (!bibfiles.empty())
956                 bibfiles += ',';
957         setParam("bibfiles", bibfiles + db);
958         return true;
959 }
960
961
962 bool InsetBibtex::delDatabase(docstring const & db)
963 {
964         docstring bibfiles = getParam("bibfiles");
965         if (contains(bibfiles, db)) {
966                 int const n = tokenPos(bibfiles, ',', db);
967                 docstring bd = db;
968                 if (n > 0) {
969                         // this is not the first database
970                         docstring tmp = ',' + bd;
971                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
972                 } else if (n == 0)
973                         // this is the first (or only) database
974                         setParam("bibfiles", split(bibfiles, bd, ','));
975                 else
976                         return false;
977         }
978         return true;
979 }
980
981
982 void InsetBibtex::validate(LaTeXFeatures & features) const
983 {
984         if (features.bufferParams().use_bibtopic)
985                 features.require("bibtopic");
986 }
987
988
989 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
990 {
991         return from_ascii("context-bibtex");
992 }
993
994
995 } // namespace lyx