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