]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
#7379 avoid the wrap spell check question when buffer is empty
[lyx.git] / src / insets / InsetBibtex.cpp
1 /**
2  * \file InsetBibtex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Richard Heck (BibTeX parser improvements)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetBibtex.h"
15
16 #include "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 void InsetBibtex::latex(otexstream & 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         if (!style.empty()) {
332                 string base = normalizeName(buffer(), runparams, style, ".bst");
333                 FileName const try_in_file = 
334                         makeAbsPath(base + ".bst", buffer().filePath());
335                 bool const not_from_texmf = try_in_file.isReadableFile();
336                 // If this style does not come from texmf and we are not
337                 // exporting to .tex copy it to the tmp directory.
338                 // This prevents problems with spaces and 8bit charcaters
339                 // in the file name.
340                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
341                     not_from_texmf) {
342                         // use new style name
343                         DocFileName const in_file = DocFileName(try_in_file);
344                         base = removeExtension(in_file.mangledFileName());
345                         FileName const out_file = makeAbsPath(base + ".bst",
346                                         buffer().masterBuffer()->temppath());
347                         bool const success = in_file.copyTo(out_file);
348                         if (!success) {
349                                 lyxerr << "Failed to copy '" << in_file
350                                        << "' to '" << out_file << "'"
351                                        << endl;
352                         }
353                 }
354                 // FIXME UNICODE
355                 os << "\\bibliographystyle{"
356                    << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
357                    << "}\n";
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         }
378
379         // bibtotoc-Option
380         if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
381                 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
382                 if (buffer().params().pdfoptions().use_hyperref)
383                                 os << "\\phantomsection";
384                 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
385                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
386                 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
387                         os << "\\addcontentsline{toc}{section}{\\refname}";
388         }
389
390         if (!db_out.empty() && !buffer().params().use_bibtopic) {
391                 docstring btprint = getParam("btprint");
392                 if (btprint == "btPrintAll") {
393                         os << "\\nocite{*}\n";
394                 }
395                 os << "\\bibliography{" << db_out << "}\n";
396         }
397 }
398
399
400 support::FileNameList InsetBibtex::getBibFiles() const
401 {
402         FileName path(buffer().filePath());
403         support::PathChanger p(path);
404         
405         support::FileNameList vec;
406         
407         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
408         vector<docstring>::const_iterator it = bibfilelist.begin();
409         vector<docstring>::const_iterator en = bibfilelist.end();
410         for (; it != en; ++it) {
411                 FileName const file = getBibTeXPath(*it, buffer());
412
413                 if (!file.empty())
414                         vec.push_back(file);
415                 else
416                         LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
417         }
418         
419         return vec;
420
421 }
422
423 namespace {
424
425         // methods for parsing bibtex files
426
427         typedef map<docstring, docstring> VarMap;
428
429         /// remove whitespace characters, optionally a single comma,
430         /// and further whitespace characters from the stream.
431         /// @return true if a comma was found, false otherwise
432         ///
433         bool removeWSAndComma(ifdocstream & ifs) {
434                 char_type ch;
435
436                 if (!ifs)
437                         return false;
438
439                 // skip whitespace
440                 do {
441                         ifs.get(ch);
442                 } while (ifs && isSpace(ch));
443
444                 if (!ifs)
445                         return false;
446
447                 if (ch != ',') {
448                         ifs.putback(ch);
449                         return false;
450                 }
451
452                 // skip whitespace
453                 do {
454                         ifs.get(ch);
455                 } while (ifs && isSpace(ch));
456
457                 if (ifs) {
458                         ifs.putback(ch);
459                 }
460
461                 return true;
462         }
463
464
465         enum charCase {
466                 makeLowerCase,
467                 keepCase
468         };
469
470         /// remove whitespace characters, read characer sequence
471         /// not containing whitespace characters or characters in
472         /// delimChars, and remove further whitespace characters.
473         ///
474         /// @return true if a string of length > 0 could be read.
475         ///
476         bool readTypeOrKey(docstring & val, ifdocstream & ifs,
477                 docstring const & delimChars, docstring const & illegalChars, 
478                 charCase chCase) {
479
480                 char_type ch;
481
482                 val.clear();
483
484                 if (!ifs)
485                         return false;
486
487                 // skip whitespace
488                 do {
489                         ifs.get(ch);
490                 } while (ifs && isSpace(ch));
491
492                 if (!ifs)
493                         return false;
494
495                 // read value
496                 bool legalChar = true;
497                 while (ifs && !isSpace(ch) && 
498                                                  delimChars.find(ch) == docstring::npos &&
499                                                  (legalChar = (illegalChars.find(ch) == docstring::npos))
500                                         ) 
501                 {
502                         if (chCase == makeLowerCase)
503                                 val += lowercase(ch);
504                         else
505                                 val += ch;
506                         ifs.get(ch);
507                 }
508                 
509                 if (!legalChar) {
510                         ifs.putback(ch);
511                         return false;
512                 }
513
514                 // skip whitespace
515                 while (ifs && isSpace(ch)) {
516                         ifs.get(ch);
517                 }
518
519                 if (ifs) {
520                         ifs.putback(ch);
521                 }
522
523                 return val.length() > 0;
524         }
525
526         /// read subsequent bibtex values that are delimited with a #-character.
527         /// Concatenate all parts and replace names with the associated string in
528         /// the variable strings.
529         /// @return true if reading was successfull (all single parts were delimited
530         /// correctly)
531         bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
532
533                 char_type ch;
534
535                 val.clear();
536
537                 if (!ifs)
538                         return false;
539
540                 do {
541                         // skip whitespace
542                         do {
543                                 ifs.get(ch);
544                         } while (ifs && isSpace(ch));
545
546                         if (!ifs)
547                                 return false;
548
549                         // check for field type
550                         if (isDigitASCII(ch)) {
551
552                                 // read integer value
553                                 do {
554                                         val += ch;
555                                         ifs.get(ch);
556                                 } while (ifs && isDigitASCII(ch));
557
558                                 if (!ifs)
559                                         return false;
560
561                         } else if (ch == '"' || ch == '{') {
562                                 // set end delimiter
563                                 char_type delim = ch == '"' ? '"': '}';
564
565                                 // Skip whitespace
566                                 do {
567                                         ifs.get(ch);
568                                 } while (ifs && isSpace(ch));
569                                 
570                                 if (!ifs)
571                                         return false;
572                                 
573                                 // We now have the first non-whitespace character
574                                 // We'll collapse adjacent whitespace.
575                                 bool lastWasWhiteSpace = false;
576                                 
577                                 // inside this delimited text braces must match.
578                                 // Thus we can have a closing delimiter only
579                                 // when nestLevel == 0
580                                 int nestLevel = 0;
581  
582                                 while (ifs && (nestLevel > 0 || ch != delim)) {
583                                         if (isSpace(ch)) {
584                                                 lastWasWhiteSpace = true;
585                                                 ifs.get(ch);
586                                                 continue;
587                                         }
588                                         // We output the space only after we stop getting 
589                                         // whitespace so as not to output any whitespace
590                                         // at the end of the value.
591                                         if (lastWasWhiteSpace) {
592                                                 lastWasWhiteSpace = false;
593                                                 val += ' ';
594                                         }
595                                         
596                                         val += ch;
597
598                                         // update nesting level
599                                         switch (ch) {
600                                                 case '{':
601                                                         ++nestLevel;
602                                                         break;
603                                                 case '}':
604                                                         --nestLevel;
605                                                         if (nestLevel < 0) 
606                                                                 return false;
607                                                         break;
608                                         }
609
610                                         if (ifs)
611                                                 ifs.get(ch);
612                                 }
613
614                                 if (!ifs)
615                                         return false;
616
617                                 // FIXME Why is this here?
618                                 ifs.get(ch);
619
620                                 if (!ifs)
621                                         return false;
622
623                         } else {
624
625                                 // reading a string name
626                                 docstring strName;
627
628                                 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
629                                         strName += lowercase(ch);
630                                         ifs.get(ch);
631                                 }
632
633                                 if (!ifs)
634                                         return false;
635
636                                 // replace the string with its assigned value or
637                                 // discard it if it's not assigned
638                                 if (strName.length()) {
639                                         VarMap::const_iterator pos = strings.find(strName);
640                                         if (pos != strings.end()) {
641                                                 val += pos->second;
642                                         }
643                                 }
644                         }
645
646                         // skip WS
647                         while (ifs && isSpace(ch)) {
648                                 ifs.get(ch);
649                         }
650
651                         if (!ifs)
652                                 return false;
653
654                         // continue reading next value on concatenate with '#'
655                 } while (ch == '#');
656
657                 ifs.putback(ch);
658
659                 return true;
660         }
661 }
662
663
664 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
665 {
666         parseBibTeXFiles();
667 }
668
669
670 void InsetBibtex::parseBibTeXFiles() const
671 {
672         // This bibtex parser is a first step to parse bibtex files
673         // more precisely.
674         //
675         // - it reads the whole bibtex entry and does a syntax check
676         //   (matching delimiters, missing commas,...
677         // - it recovers from errors starting with the next @-character
678         // - it reads @string definitions and replaces them in the
679         //   field values.
680         // - it accepts more characters in keys or value names than
681         //   bibtex does.
682         //
683         // Officially bibtex does only support ASCII, but in practice
684         // you can use the encoding of the main document as long as
685         // some elements like keys and names are pure ASCII. Therefore
686         // we convert the file from the buffer encoding.
687         // We don't restrict keys to ASCII in LyX, since our own
688         // InsetBibitem can generate non-ASCII keys, and nonstandard
689         // 8bit clean bibtex forks exist.
690
691         BiblioInfo keylist;
692
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         buffer().addBiblioInfo(keylist);
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::ESCAPE_AND
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::contextMenuName() const
992 {
993         return from_ascii("context-bibtex");
994 }
995
996
997 } // namespace lyx