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