]> git.lyx.org Git - features.git/blob - src/insets/InsetBibtex.cpp
filetools.cpp: introduce a new method to be able to distinguish between valid LaTeX...
[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 "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 "Language.h"
24 #include "LaTeXFeatures.h"
25 #include "output_xhtml.h"
26 #include "OutputParams.h"
27 #include "TextClass.h"
28
29 #include "frontends/alert.h"
30
31 #include "support/convert.h"
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/ExceptionMessage.h"
35 #include "support/filetools.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38 #include "support/os.h"
39 #include "support/Path.h"
40 #include "support/textutils.h"
41
42 #include <limits>
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48
49 namespace Alert = frontend::Alert;
50 namespace os = support::os;
51
52
53 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
54         : InsetCommand(buf, p, "bibtex")
55 {
56         buffer().invalidateBibinfoCache();
57 }
58
59
60 InsetBibtex::~InsetBibtex()
61 {
62         if (isBufferLoaded())
63                 buffer().invalidateBibfileCache();
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.noScreenUpdate();
93                                 break;
94                         }
95                 } catch (ExceptionMessage const & message) {
96                         if (message.type_ == WarningException) {
97                                 Alert::warning(message.title_, message.details_);
98                                 cur.noScreenUpdate();
99                         } else 
100                                 throw message;
101                         break;
102                 }
103                 //
104                 setParams(p);
105                 buffer().invalidateBibfileCache();
106                 cur.forceBufferUpdate();
107                 break;
108         }
109
110         default:
111                 InsetCommand::doDispatch(cur, cmd);
112                 break;
113         }
114 }
115
116
117 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
118                 FuncStatus & flag) const
119 {
120         switch (cmd.action()) {
121         case LFUN_INSET_EDIT:
122                 flag.setEnabled(true);
123                 return true;
124
125         default:
126                 return InsetCommand::getStatus(cur, cmd, flag);
127         }
128 }
129
130
131 void InsetBibtex::editDatabases() const
132 {
133         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
134
135         if (bibfilelist.empty())
136                 return;
137
138         int nr_databases = bibfilelist.size();
139         if (nr_databases > 1) {
140                         docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
141                                                        "If you proceed, all of them will be opened."),
142                                                         convert<docstring>(nr_databases));
143                         int const ret = Alert::prompt(_("Open Databases?"),
144                                 message, 0, 1, _("&Cancel"), _("&Proceed"));
145
146                         if (ret == 0)
147                                 return;
148         }
149
150         vector<docstring>::const_iterator it = bibfilelist.begin();
151         vector<docstring>::const_iterator en = bibfilelist.end();
152         for (; it != en; ++it) {
153                 FileName bibfile = getBibTeXPath(*it, buffer());
154                 formats.edit(buffer(), bibfile,
155                      formats.getFormatFromFile(bibfile));
156         }
157 }
158
159
160 docstring InsetBibtex::screenLabel() const
161 {
162         return _("BibTeX Generated Bibliography");
163 }
164
165
166 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
167 {
168         docstring item = from_ascii("* ");
169         docstring tip = _("Databases:") + "\n";
170         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
171
172         if (bibfilelist.empty()) {
173                 tip += item;
174                 tip += _("none");
175         } else {
176                 vector<docstring>::const_iterator it = bibfilelist.begin();
177                 vector<docstring>::const_iterator en = bibfilelist.end();
178                 for (; it != en; ++it) {
179                         tip += item;
180                         tip += *it + "\n";
181                 }
182         }
183
184         // Style-Options
185         bool toc = false;
186         docstring style = getParam("options"); // maybe empty! and with bibtotoc
187         docstring bibtotoc = from_ascii("bibtotoc");
188         if (prefixIs(style, bibtotoc)) {
189                 toc = true;
190                 if (contains(style, char_type(',')))
191                         style = split(style, bibtotoc, char_type(','));
192         }
193
194         tip += _("Style File:") +"\n";
195         tip += item;
196         if (!style.empty())
197                 tip += style;
198         else
199                 tip += _("none");
200
201         tip += "\n" + _("Lists:") + " ";
202         docstring btprint = getParam("btprint");
203                 if (btprint == "btPrintAll")
204                         tip += _("all references");
205                 else if (btprint == "btPrintNotCited")
206                         tip += _("all uncited references");
207                 else
208                         tip += _("all cited references");
209         
210         if (toc) {
211                 tip += ", ";
212                 tip += _("included in TOC");
213         }
214
215         return tip;
216 }
217
218
219 static string normalizeName(Buffer const & buffer,
220         OutputParams const & runparams, string const & name, string const & ext)
221 {
222         string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
223         if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
224                 return name;
225         if (!runparams.nice)
226                 return fname;
227
228         // FIXME UNICODE
229         return to_utf8(makeRelPath(from_utf8(fname),
230                                          from_utf8(buffer.masterBuffer()->filePath())));
231 }
232
233
234 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
235 {
236         // the sequence of the commands:
237         // 1. \bibliographystyle{style}
238         // 2. \addcontentsline{...} - if option bibtotoc set
239         // 3. \bibliography{database}
240         // and with bibtopic:
241         // 1. \bibliographystyle{style}
242         // 2. \begin{btSect}{database}
243         // 3. \btPrint{Cited|NotCited|All}
244         // 4. \end{btSect}
245
246         // Database(s)
247         // If we are processing the LaTeX file in a temp directory then
248         // copy the .bib databases to this temp directory, mangling their
249         // names in the process. Store this mangled name in the list of
250         // all databases.
251         // (We need to do all this because BibTeX *really*, *really*
252         // can't handle "files with spaces" and Windows users tend to
253         // use such filenames.)
254         // Otherwise, store the (maybe absolute) path to the original,
255         // unmangled database name.
256         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
257         vector<docstring>::const_iterator it = bibfilelist.begin();
258         vector<docstring>::const_iterator en = bibfilelist.end();
259         odocstringstream dbs;
260         bool didone = false;
261
262         for (; it != en; ++it) {
263                 string utf8input = to_utf8(*it);
264                 string database =
265                         normalizeName(buffer(), runparams, utf8input, ".bib");
266                 FileName const try_in_file =
267                         makeAbsPath(database + ".bib", buffer().filePath());
268                 bool const not_from_texmf = try_in_file.isReadableFile();
269
270                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
271                     not_from_texmf) {
272                         // mangledFileName() needs the extension
273                         DocFileName const in_file = DocFileName(try_in_file);
274                         database = removeExtension(in_file.mangledFileName());
275                         FileName const out_file = makeAbsPath(database + ".bib",
276                                         buffer().masterBuffer()->temppath());
277
278                         bool const success = in_file.copyTo(out_file);
279                         if (!success) {
280                                 lyxerr << "Failed to copy '" << in_file
281                                        << "' to '" << out_file << "'"
282                                        << endl;
283                         }
284                 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
285                         if (!isValidLaTeXFileName(database)) {
286                                 frontend::Alert::warning(_("Invalid filename"),
287                                          _("The following filename will cause troubles "
288                                                "when running the exported file through LaTeX: ") +
289                                              from_utf8(database));
290                         }
291                         if (!isValidDVIFileName(database)) {
292                                 frontend::Alert::warning(_("Problematic filename for DVI"),
293                                          _("The following filename can cause troubles "
294                                                "when running the exported file through LaTeX "
295                                                    "and opening the resulting DVI: ") +
296                                              from_utf8(database), true);
297                         }
298                 }
299
300                 if (didone)
301                         dbs << ',';
302                 else 
303                         didone = true;
304                 // FIXME UNICODE
305                 dbs << from_utf8(latex_path(database));
306         }
307         docstring const db_out = dbs.str();
308
309         // Post this warning only once.
310         static bool warned_about_spaces = false;
311         if (!warned_about_spaces &&
312             runparams.nice && db_out.find(' ') != docstring::npos) {
313                 warned_about_spaces = true;
314                 Alert::warning(_("Export Warning!"),
315                                _("There are spaces in the paths to your BibTeX databases.\n"
316                                               "BibTeX will be unable to find them."));
317         }
318         // Style-Options
319         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
320         string bibtotoc;
321         if (prefixIs(style, "bibtotoc")) {
322                 bibtotoc = "bibtotoc";
323                 if (contains(style, ','))
324                         style = split(style, bibtotoc, ',');
325         }
326
327         // line count
328         int nlines = 0;
329
330         if (!style.empty()) {
331                 string base = normalizeName(buffer(), runparams, style, ".bst");
332                 FileName const try_in_file = 
333                         makeAbsPath(base + ".bst", buffer().filePath());
334                 bool const not_from_texmf = try_in_file.isReadableFile();
335                 // If this style does not come from texmf and we are not
336                 // exporting to .tex copy it to the tmp directory.
337                 // This prevents problems with spaces and 8bit charcaters
338                 // in the file name.
339                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
340                     not_from_texmf) {
341                         // use new style name
342                         DocFileName const in_file = DocFileName(try_in_file);
343                         base = removeExtension(in_file.mangledFileName());
344                         FileName const out_file = makeAbsPath(base + ".bst",
345                                         buffer().masterBuffer()->temppath());
346                         bool const success = in_file.copyTo(out_file);
347                         if (!success) {
348                                 lyxerr << "Failed to copy '" << in_file
349                                        << "' to '" << out_file << "'"
350                                        << endl;
351                         }
352                 }
353                 // FIXME UNICODE
354                 os << "\\bibliographystyle{"
355                    << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
356                    << "}\n";
357                 nlines += 1;
358         }
359
360         // Post this warning only once.
361         static bool warned_about_bst_spaces = false;
362         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
363                 warned_about_bst_spaces = true;
364                 Alert::warning(_("Export Warning!"),
365                                _("There are spaces in the path to your BibTeX style file.\n"
366                                               "BibTeX will be unable to find it."));
367         }
368
369         if (!db_out.empty() && buffer().params().use_bibtopic) {
370                 os << "\\begin{btSect}{" << db_out << "}\n";
371                 docstring btprint = getParam("btprint");
372                 if (btprint.empty())
373                         // default
374                         btprint = from_ascii("btPrintCited");
375                 os << "\\" << btprint << "\n"
376                    << "\\end{btSect}\n";
377                 nlines += 3;
378         }
379
380         // bibtotoc-Option
381         if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
382                 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
383                         if (buffer().params().sides == OneSide) {
384                                 // oneside
385                                 os << "\\clearpage";
386                         } else {
387                                 // twoside
388                                 os << "\\cleardoublepage";
389                         }
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 (isDigit(ch)) {
560
561                                 // read integer value
562                                 do {
563                                         val += ch;
564                                         ifs.get(ch);
565                                 } while (ifs && isDigit(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 // This method returns a comma separated list of Bibtex entries
674 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
675         InsetIterator const & /*di*/) const
676 {
677         // This bibtex parser is a first step to parse bibtex files
678         // more precisely.
679         //
680         // - it reads the whole bibtex entry and does a syntax check
681         //   (matching delimiters, missing commas,...
682         // - it recovers from errors starting with the next @-character
683         // - it reads @string definitions and replaces them in the
684         //   field values.
685         // - it accepts more characters in keys or value names than
686         //   bibtex does.
687         //
688         // Officially bibtex does only support ASCII, but in practice
689         // you can use the encoding of the main document as long as
690         // some elements like keys and names are pure ASCII. Therefore
691         // we convert the file from the buffer encoding.
692         // We don't restrict keys to ASCII in LyX, since our own
693         // InsetBibitem can generate non-ASCII keys, and nonstandard
694         // 8bit clean bibtex forks exist.
695         support::FileNameList const files = getBibFiles();
696         support::FileNameList::const_iterator it = files.begin();
697         support::FileNameList::const_iterator en = files.end();
698         for (; it != en; ++ it) {
699                 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
700                         ios_base::in, buffer().params().encoding().iconvName());
701
702                 char_type ch;
703                 VarMap strings;
704
705                 while (ifs) {
706
707                         ifs.get(ch);
708                         if (!ifs)
709                                 break;
710
711                         if (ch != '@')
712                                 continue;
713
714                         docstring entryType;
715
716                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
717                                 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
718                                 continue;
719                         }
720
721                         if (!ifs) {
722                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
723                                 continue;
724                         }
725
726                         if (entryType == from_ascii("comment")) {
727                                 ifs.ignore(numeric_limits<int>::max(), '\n');
728                                 continue;
729                         }
730
731                         ifs.get(ch);
732                         if (!ifs) {
733                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
734                                 break;
735                         }
736
737                         if ((ch != '(') && (ch != '{')) {
738                                 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
739                                 ifs.putback(ch);
740                                 continue;
741                         }
742
743                         // process the entry
744                         if (entryType == from_ascii("string")) {
745
746                                 // read string and add it to the strings map
747                                 // (or replace it's old value)
748                                 docstring name;
749                                 docstring value;
750
751                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
752                                         lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
753                                         continue;
754                                 }
755
756                                 if (!ifs) {
757                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
758                                         continue;
759                                 }
760
761                                 // next char must be an equal sign
762                                 ifs.get(ch);
763                                 if (!ifs || ch != '=') {
764                                         lyxerr << "BibTeX Parser: No `=' after string name: " << 
765                                                         name << "." << std::endl;
766                                         continue;
767                                 }
768
769                                 if (!readValue(value, ifs, strings)) {
770                                         lyxerr << "BibTeX Parser: Unable to read value for string: " << 
771                                                         name << "." << std::endl;
772                                         continue;
773                                 }
774
775                                 strings[name] = value;
776
777                         } else if (entryType == from_ascii("preamble")) {
778
779                                 // preamble definitions are discarded.
780                                 // can they be of any use in lyx?
781                                 docstring value;
782
783                                 if (!readValue(value, ifs, strings)) {
784                                         lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
785                                         continue;
786                                 }
787
788                         } else {
789
790                                 // Citation entry. Try to read the key.
791                                 docstring key;
792
793                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
794                                         lyxerr << "BibTeX Parser: Unable to read key for entry type:" << 
795                                                         entryType << "." << std::endl;
796                                         continue;
797                                 }
798
799                                 if (!ifs) {
800                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
801                                         continue;
802                                 }
803
804                                 /////////////////////////////////////////////
805                                 // now we have a key, so we will add an entry 
806                                 // (even if it's empty, as bibtex does)
807                                 //
808                                 // we now read the field = value pairs.
809                                 // all items must be separated by a comma. If
810                                 // it is missing the scanning of this entry is
811                                 // stopped and the next is searched.
812                                 docstring name;
813                                 docstring value;
814                                 docstring data;
815                                 BibTeXInfo keyvalmap(key, entryType);
816                                 
817                                 bool readNext = removeWSAndComma(ifs);
818  
819                                 while (ifs && readNext) {
820
821                                         // read field name
822                                         if (!readTypeOrKey(name, ifs, from_ascii("="), 
823                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
824                                                 break;
825
826                                         // next char must be an equal sign
827                                         // FIXME Whitespace??
828                                         ifs.get(ch);
829                                         if (!ifs) {
830                                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
831                                                 break;
832                                         }
833                                         if (ch != '=') {
834                                                 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
835                                                                 name << ", for key: " << key << "." << std::endl;
836                                                 ifs.putback(ch);
837                                                 break;
838                                         }
839
840                                         // read field value
841                                         if (!readValue(value, ifs, strings)) {
842                                                 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
843                                                                 name << ", for key: " << key << "." << std::endl;
844                                                 break;
845                                         }
846
847                                         keyvalmap[name] = value;
848                                         data += "\n\n" + value;
849                                         keylist.addFieldName(name);
850                                         readNext = removeWSAndComma(ifs);
851                                 }
852
853                                 // add the new entry
854                                 keylist.addEntryType(entryType);
855                                 keyvalmap.setAllData(data);
856                                 keylist[key] = keyvalmap;
857                         } //< else (citation entry)
858                 } //< searching '@'
859         } //< for loop over files
860 }
861
862
863 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
864 {
865         string texfile = changeExtension(to_utf8(filename), "bib");
866         // note that, if the filename can be found directly from the path, 
867         // findtexfile will just return a FileName object for that path.
868         FileName file(findtexfile(texfile, "bib"));
869         if (file.empty())
870                 file = FileName(makeAbsPath(texfile, buf.filePath()));
871         return file;
872 }
873  
874
875 bool InsetBibtex::addDatabase(docstring const & db)
876 {
877         docstring bibfiles = getParam("bibfiles");
878         if (tokenPos(bibfiles, ',', db) != -1)
879                 return false;
880         if (!bibfiles.empty())
881                 bibfiles += ',';
882         setParam("bibfiles", bibfiles + db);
883         return true;
884 }
885
886
887 bool InsetBibtex::delDatabase(docstring const & db)
888 {
889         docstring bibfiles = getParam("bibfiles");
890         if (contains(bibfiles, db)) {
891                 int const n = tokenPos(bibfiles, ',', db);
892                 docstring bd = db;
893                 if (n > 0) {
894                         // this is not the first database
895                         docstring tmp = ',' + bd;
896                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
897                 } else if (n == 0)
898                         // this is the first (or only) database
899                         setParam("bibfiles", split(bibfiles, bd, ','));
900                 else
901                         return false;
902         }
903         return true;
904 }
905
906
907 void InsetBibtex::validate(LaTeXFeatures & features) const
908 {
909         if (features.bufferParams().use_bibtopic)
910                 features.require("bibtopic");
911         // FIXME XHTML
912         // It'd be better to be able to get this from an InsetLayout, but at present
913         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
914         if (features.runparams().flavor == OutputParams::HTML)
915                 features.addPreambleSnippet("<style type=\"text/css\">\n"
916                         "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
917                         "span.bibtexlabel:before{ content: \"[\"; }\n"
918                         "span.bibtexlabel:after{ content: \"] \"; }\n"
919                         "</style>");
920 }
921
922
923 // FIXME 
924 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
925 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
926 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
927 {
928         BiblioInfo const & bibinfo = buffer().masterBibInfo();
929         vector<docstring> const & cites = bibinfo.citedEntries();
930         CiteEngine const engine = buffer().params().citeEngine();
931         bool const numbers = 
932                 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
933
934         docstring reflabel = from_ascii("References");
935         Language const * l = buffer().params().language;
936         if (l)
937                 reflabel = translateIfPossible(reflabel, l->code());
938                 
939         xs << html::StartTag("h2", "class='bibtex'")
940                 << reflabel
941                 << html::EndTag("h2")
942                 << html::StartTag("div", "class='bibtex'");
943
944         // Now we loop over the entries
945         vector<docstring>::const_iterator vit = cites.begin();
946         vector<docstring>::const_iterator const ven = cites.end();
947         for (; vit != ven; ++vit) {
948                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
949                 if (biit == bibinfo.end())
950                         continue;
951                 BibTeXInfo const & entry = biit->second;
952                 xs << html::StartTag("div", "class='bibtexentry'");
953                 // FIXME XHTML
954                 // The same name/id problem we have elsewhere.
955                 string const attr = "id='" + to_utf8(entry.key()) + "'";
956                 xs << html::CompTag("a", attr);
957                 docstring citekey;
958                 if (numbers)
959                         citekey = entry.citeNumber();
960                 else {
961                         docstring const auth = entry.getAbbreviatedAuthor();
962                         // we do it this way so as to access the xref, if necessary
963                         // note that this also gives us the modifier
964                         docstring const year = bibinfo.getYear(*vit, true);
965                         if (!auth.empty() && !year.empty())
966                                 citekey = auth + ' ' + year;
967                 }
968                 if (citekey.empty()) {
969                         citekey = entry.label();
970                         if (citekey.empty())
971                                 citekey = entry.key();
972                 }
973                 xs << html::StartTag("span", "class='bibtexlabel'")
974                         << citekey
975                         << html::EndTag("span");
976                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
977                 // which will give us all the cross-referenced info. But for every
978                 // entry, so there's a lot of repitition. This should be fixed.
979                 xs << html::StartTag("span", "class='bibtexinfo'") 
980                         << XHTMLStream::NextRaw()
981                         << bibinfo.getInfo(entry.key(), buffer(), true)
982                         << html::EndTag("span")
983                         << html::EndTag("div");
984                 xs.cr();
985         }
986         xs << html::EndTag("div");
987         return docstring();
988 }
989
990
991 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
992 {
993         return from_ascii("context-bibtex");
994 }
995
996
997 } // namespace lyx