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