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