]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
Fix trailing whitespace in cpp files.
[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  * \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 }
646
647
648 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
649 {
650         parseBibTeXFiles();
651 }
652
653
654 void InsetBibtex::parseBibTeXFiles() 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                 ifdocstream ifs(it->second.toFilesystemEncoding().c_str(),
682                         ios_base::in, buffer().masterParams().encoding().iconvName());
683
684                 char_type ch;
685                 VarMap strings;
686
687                 while (ifs) {
688
689                         ifs.get(ch);
690                         if (!ifs)
691                                 break;
692
693                         if (ch != '@')
694                                 continue;
695
696                         docstring entryType;
697
698                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
699                                 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
700                                 continue;
701                         }
702
703                         if (!ifs) {
704                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
705                                 continue;
706                         }
707
708                         if (entryType == from_ascii("comment")) {
709                                 ifs.ignore(numeric_limits<int>::max(), '\n');
710                                 continue;
711                         }
712
713                         ifs.get(ch);
714                         if (!ifs) {
715                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
716                                 break;
717                         }
718
719                         if ((ch != '(') && (ch != '{')) {
720                                 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
721                                 ifs.putback(ch);
722                                 continue;
723                         }
724
725                         // process the entry
726                         if (entryType == from_ascii("string")) {
727
728                                 // read string and add it to the strings map
729                                 // (or replace it's old value)
730                                 docstring name;
731                                 docstring value;
732
733                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
734                                         lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
735                                         continue;
736                                 }
737
738                                 if (!ifs) {
739                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
740                                         continue;
741                                 }
742
743                                 // next char must be an equal sign
744                                 ifs.get(ch);
745                                 if (!ifs || ch != '=') {
746                                         lyxerr << "BibTeX Parser: No `=' after string name: " <<
747                                                         name << "." << std::endl;
748                                         continue;
749                                 }
750
751                                 if (!readValue(value, ifs, strings)) {
752                                         lyxerr << "BibTeX Parser: Unable to read value for string: " <<
753                                                         name << "." << std::endl;
754                                         continue;
755                                 }
756
757                                 strings[name] = value;
758
759                         } else if (entryType == from_ascii("preamble")) {
760
761                                 // preamble definitions are discarded.
762                                 // can they be of any use in lyx?
763                                 docstring value;
764
765                                 if (!readValue(value, ifs, strings)) {
766                                         lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
767                                         continue;
768                                 }
769
770                         } else {
771
772                                 // Citation entry. Try to read the key.
773                                 docstring key;
774
775                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
776                                         lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
777                                                         entryType << "." << std::endl;
778                                         continue;
779                                 }
780
781                                 if (!ifs) {
782                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
783                                         continue;
784                                 }
785
786                                 /////////////////////////////////////////////
787                                 // now we have a key, so we will add an entry
788                                 // (even if it's empty, as bibtex does)
789                                 //
790                                 // we now read the field = value pairs.
791                                 // all items must be separated by a comma. If
792                                 // it is missing the scanning of this entry is
793                                 // stopped and the next is searched.
794                                 docstring name;
795                                 docstring value;
796                                 docstring data;
797                                 BibTeXInfo keyvalmap(key, entryType);
798
799                                 bool readNext = removeWSAndComma(ifs);
800
801                                 while (ifs && readNext) {
802
803                                         // read field name
804                                         if (!readTypeOrKey(name, ifs, from_ascii("="),
805                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
806                                                 break;
807
808                                         // next char must be an equal sign
809                                         // FIXME Whitespace??
810                                         ifs.get(ch);
811                                         if (!ifs) {
812                                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
813                                                 break;
814                                         }
815                                         if (ch != '=') {
816                                                 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
817                                                                 name << ", for key: " << key << "." << std::endl;
818                                                 ifs.putback(ch);
819                                                 break;
820                                         }
821
822                                         // read field value
823                                         if (!readValue(value, ifs, strings)) {
824                                                 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
825                                                                 name << ", for key: " << key << "." << std::endl;
826                                                 break;
827                                         }
828
829                                         keyvalmap[name] = value;
830                                         data += "\n\n" + value;
831                                         keylist.addFieldName(name);
832                                         readNext = removeWSAndComma(ifs);
833                                 }
834
835                                 // add the new entry
836                                 keylist.addEntryType(entryType);
837                                 keyvalmap.setAllData(data);
838                                 keylist[key] = keyvalmap;
839                         } //< else (citation entry)
840                 } //< searching '@'
841         } //< for loop over files
842
843         buffer().addBiblioInfo(keylist);
844 }
845
846
847 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
848 {
849         string texfile = changeExtension(to_utf8(filename), "bib");
850         // note that, if the filename can be found directly from the path,
851         // findtexfile will just return a FileName object for that path.
852         FileName file(findtexfile(texfile, "bib"));
853         if (file.empty())
854                 file = FileName(makeAbsPath(texfile, buf.filePath()));
855         return file;
856 }
857
858
859 bool InsetBibtex::addDatabase(docstring const & db)
860 {
861         docstring bibfiles = getParam("bibfiles");
862         if (tokenPos(bibfiles, ',', db) != -1)
863                 return false;
864         if (!bibfiles.empty())
865                 bibfiles += ',';
866         setParam("bibfiles", bibfiles + db);
867         return true;
868 }
869
870
871 bool InsetBibtex::delDatabase(docstring const & db)
872 {
873         docstring bibfiles = getParam("bibfiles");
874         if (contains(bibfiles, db)) {
875                 int const n = tokenPos(bibfiles, ',', db);
876                 docstring bd = db;
877                 if (n > 0) {
878                         // this is not the first database
879                         docstring tmp = ',' + bd;
880                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
881                 } else if (n == 0)
882                         // this is the first (or only) database
883                         setParam("bibfiles", split(bibfiles, bd, ','));
884                 else
885                         return false;
886         }
887         return true;
888 }
889
890
891 void InsetBibtex::validate(LaTeXFeatures & features) const
892 {
893         BufferParams const & mparams = features.buffer().masterParams();
894         if (mparams.useBibtopic())
895                 features.require("bibtopic");
896         else if (!mparams.useBiblatex() && mparams.multibib == "child")
897                 features.require("chapterbib");
898         // FIXME XHTML
899         // It'd be better to be able to get this from an InsetLayout, but at present
900         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
901         if (features.runparams().flavor == OutputParams::HTML)
902                 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
903                         "span.bibtexlabel:before{ content: \"[\"; }\n"
904                         "span.bibtexlabel:after{ content: \"] \"; }");
905 }
906
907
908 int InsetBibtex::plaintext(odocstringstream & os,
909        OutputParams const & op, size_t max_length) const
910 {
911         docstring const reflabel = buffer().B_("References");
912
913         // We could output more information here, e.g., what databases are included
914         // and information about options. But I don't necessarily see any reason to
915         // do this right now.
916         if (op.for_tooltip || op.for_toc || op.for_search) {
917                 os << '[' << reflabel << ']' << '\n';
918                 return PLAINTEXT_NEWLINE;
919         }
920
921         BiblioInfo bibinfo = buffer().masterBibInfo();
922         bibinfo.makeCitationLabels(buffer());
923         vector<docstring> const & cites = bibinfo.citedEntries();
924
925         size_t start_size = os.str().size();
926         docstring refoutput;
927         refoutput += reflabel + "\n\n";
928
929         // Tell BiblioInfo our purpose
930         CiteItem ci;
931         ci.context = CiteItem::Export;
932
933         // Now we loop over the entries
934         vector<docstring>::const_iterator vit = cites.begin();
935         vector<docstring>::const_iterator const ven = cites.end();
936         for (; vit != ven; ++vit) {
937                 if (start_size + refoutput.size() >= max_length)
938                         break;
939                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
940                 if (biit == bibinfo.end())
941                         continue;
942                 BibTeXInfo const & entry = biit->second;
943                 refoutput += "[" + entry.label() + "] ";
944                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
945                 // which will give us all the cross-referenced info. But for every
946                 // entry, so there's a lot of repitition. This should be fixed.
947                 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
948         }
949         os << refoutput;
950         return refoutput.size();
951 }
952
953
954 // FIXME
955 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
956 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
957 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
958 {
959         BiblioInfo const & bibinfo = buffer().masterBibInfo();
960         bool const all_entries = getParam("btprint") == "btPrintAll";
961         vector<docstring> const & cites =
962             all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
963
964         docstring const reflabel = buffer().B_("References");
965
966         // tell BiblioInfo our purpose
967         CiteItem ci;
968         ci.context = CiteItem::Export;
969         ci.richtext = true;
970         ci.max_key_size = UINT_MAX;
971
972         xs << html::StartTag("h2", "class='bibtex'")
973                 << reflabel
974                 << html::EndTag("h2")
975                 << html::StartTag("div", "class='bibtex'");
976
977         // Now we loop over the entries
978         vector<docstring>::const_iterator vit = cites.begin();
979         vector<docstring>::const_iterator const ven = cites.end();
980         for (; vit != ven; ++vit) {
981                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
982                 if (biit == bibinfo.end())
983                         continue;
984
985                 BibTeXInfo const & entry = biit->second;
986                 string const attr = "class='bibtexentry' id='LyXCite-"
987                     + to_utf8(html::cleanAttr(entry.key())) + "'";
988                 xs << html::StartTag("div", attr);
989
990                 // don't print labels if we're outputting all entries
991                 if (!all_entries) {
992                         xs << html::StartTag("span", "class='bibtexlabel'")
993                                 << entry.label()
994                                 << html::EndTag("span");
995                 }
996
997                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
998                 // which will give us all the cross-referenced info. But for every
999                 // entry, so there's a lot of repitition. This should be fixed.
1000                 xs << html::StartTag("span", "class='bibtexinfo'")
1001                    << XHTMLStream::ESCAPE_AND
1002                    << bibinfo.getInfo(entry.key(), buffer(), ci)
1003                    << html::EndTag("span")
1004                    << html::EndTag("div")
1005                    << html::CR();
1006         }
1007         xs << html::EndTag("div");
1008         return docstring();
1009 }
1010
1011
1012 void InsetBibtex::write(ostream & os) const
1013 {
1014         params().Write(os, &buffer());
1015 }
1016
1017
1018 string InsetBibtex::contextMenuName() const
1019 {
1020         return "context-bibtex";
1021 }
1022
1023
1024 } // namespace lyx