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