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