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