]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
#11747 follow-up of change d94b708a0fec6ade04fc9d09bd86afd73e72fac7 to fix a compiler...
[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_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("file_encodings", ParamInfo::LYX_INTERNAL);
77                 param_info_.add("biblatexopts", ParamInfo::LATEX_OPTIONAL);
78         }
79         return param_info_;
80 }
81
82
83 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
84 {
85         switch (cmd.action()) {
86
87         case LFUN_INSET_EDIT:
88                 editDatabases(cmd.argument());
89                 break;
90
91         case LFUN_INSET_MODIFY: {
92                 InsetCommandParams p(BIBTEX_CODE);
93                 try {
94                         if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
95                                 cur.noScreenUpdate();
96                                 break;
97                         }
98                 } catch (ExceptionMessage const & message) {
99                         if (message.type_ == WarningException) {
100                                 Alert::warning(message.title_, message.details_);
101                                 cur.noScreenUpdate();
102                         } else
103                                 throw;
104                         break;
105                 }
106
107                 cur.recordUndo();
108                 setParams(p);
109                 cur.buffer()->clearBibFileCache();
110                 cur.forceBufferUpdate();
111                 break;
112         }
113
114         default:
115                 InsetCommand::doDispatch(cur, cmd);
116                 break;
117         }
118 }
119
120
121 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
122                 FuncStatus & flag) const
123 {
124         switch (cmd.action()) {
125         case LFUN_INSET_EDIT:
126                 flag.setEnabled(true);
127                 return true;
128
129         default:
130                 return InsetCommand::getStatus(cur, cmd, flag);
131         }
132 }
133
134
135 void InsetBibtex::editDatabases(docstring const & db) const
136 {
137         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
138
139         if (bibfilelist.empty())
140                 return;
141
142         size_t nr_databases = bibfilelist.size();
143         if (nr_databases > 1 && db.empty()) {
144                         docstring const engine = usingBiblatex() ? _("Biblatex") : _("BibTeX");
145                         docstring message = bformat(_("The %1$s[[BibTeX/Biblatex]] inset includes %2$s databases.\n"
146                                                        "If you proceed, all of them will be opened."),
147                                                         engine, convert<docstring>(nr_databases));
148                         int const ret = Alert::prompt(_("Open Databases?"),
149                                 message, 0, 1, _("&Cancel"), _("&Proceed"));
150
151                         if (ret == 0)
152                                 return;
153         }
154
155         vector<docstring>::const_iterator it = bibfilelist.begin();
156         vector<docstring>::const_iterator en = bibfilelist.end();
157         for (; it != en; ++it) {
158                 if (!db.empty() && db != *it)
159                         continue;
160                 FileName const bibfile = buffer().getBibfilePath(*it);
161                 theFormats().edit(buffer(), bibfile,
162                      theFormats().getFormatFromFile(bibfile));
163         }
164 }
165
166
167 bool InsetBibtex::usingBiblatex() const
168 {
169         return buffer().masterParams().useBiblatex();
170 }
171
172
173 docstring InsetBibtex::screenLabel() const
174 {
175         return usingBiblatex() ? _("Biblatex Generated Bibliography")
176                                : _("BibTeX Generated Bibliography");
177 }
178
179
180 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
181 {
182         docstring tip = _("Databases:");
183         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
184
185         tip += "<ul>";
186         if (bibfilelist.empty())
187                 tip += "<li>" + _("none") + "</li>";
188         else
189                 for (docstring const & bibfile : bibfilelist)
190                         tip += "<li>" + bibfile + "</li>";
191         tip += "</ul>";
192
193         // Style-Options
194         bool toc = false;
195         docstring style = getParam("options"); // maybe empty! and with bibtotoc
196         docstring bibtotoc = from_ascii("bibtotoc");
197         if (prefixIs(style, bibtotoc)) {
198                 toc = true;
199                 if (contains(style, char_type(',')))
200                         style = split(style, bibtotoc, char_type(','));
201         }
202
203         docstring const btprint = getParam("btprint");
204         if (!usingBiblatex()) {
205                 tip += _("Style File:");
206                 tip += "<ul><li>" + (style.empty() ? _("none") : style) + "</li></ul>";
207
208                 tip += _("Lists:") + " ";
209                 if (btprint == "btPrintAll")
210                         tip += _("all references");
211                 else if (btprint == "btPrintNotCited")
212                         tip += _("all uncited references");
213                 else
214                         tip += _("all cited references");
215                 if (toc) {
216                         tip += ", ";
217                         tip += _("included in TOC");
218                 }
219                 if (!buffer().parent()
220                     && buffer().params().multibib == "child") {
221                         tip += "<br />";
222                         tip += _("Note: This bibliography is not output, since bibliographies in the master file "
223                                  "are not allowed with the setting 'Multiple bibliographies per child document'");
224                 }
225         } else {
226                 tip += _("Lists:") + " ";
227                 if (btprint == "bibbysection")
228                         tip += _("all reference units");
229                 else if (btprint == "btPrintAll")
230                         tip += _("all references");
231                 else
232                         tip += _("all cited references");
233                 if (toc) {
234                         tip += ", ";
235                         tip += _("included in TOC");
236                 }
237                 if (!getParam("biblatexopts").empty()) {
238                         tip += "<br />";
239                         tip += _("Options: ") + getParam("biblatexopts");
240                 }
241         }
242
243         return tip;
244 }
245
246
247 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
248 {
249         // The sequence of the commands:
250         // With normal BibTeX:
251         // 1. \bibliographystyle{style}
252         // 2. \addcontentsline{...} - if option bibtotoc set
253         // 3. \bibliography{database}
254         // With bibtopic:
255         // 1. \bibliographystyle{style}
256         // 2. \begin{btSect}{database}
257         // 3. \btPrint{Cited|NotCited|All}
258         // 4. \end{btSect}
259         // With Biblatex:
260         // \printbibliography[biblatexopts]
261         // or
262         // \bibbysection[biblatexopts] - if btprint is "bibbysection"
263
264         // chapterbib does not allow bibliographies in the master
265         if (!usingBiblatex() && !runparams.is_child
266             && buffer().params().multibib == "child")
267                 return;
268
269         if (runparams.inDeletedInset) {
270                 // We cannot strike-out bibligraphies,
271                 // so we just output a note.
272                 os << "\\textbf{"
273                    << buffer().B_("[BIBLIOGRAPHY DELETED!]")
274                    << "}";
275                 return;
276         }
277
278         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
279         string bibtotoc;
280         if (prefixIs(style, "bibtotoc")) {
281                 bibtotoc = "bibtotoc";
282                 if (contains(style, ','))
283                         style = split(style, bibtotoc, ',');
284         }
285
286         if (usingBiblatex()) {
287                 // Options
288                 string opts = to_utf8(getParam("biblatexopts"));
289                 // bibtotoc-Option
290                 if (!bibtotoc.empty())
291                         opts = opts.empty() ? "heading=bibintoc" : "heading=bibintoc," + opts;
292                 // The bibliography command
293                 docstring btprint = getParam("btprint");
294                 if (btprint == "btPrintAll")
295                         os << "\\nocite{*}\n";
296                 if (btprint == "bibbysection" && !buffer().masterParams().multibib.empty())
297                         os << "\\bibbysection";
298                 else
299                         os << "\\printbibliography";
300                 if (!opts.empty())
301                         os << "[" << opts << "]";
302                 os << "\n";
303         } else {// using BibTeX
304                 // Database(s)
305                 vector<pair<docstring, string>> const dbs =
306                         buffer().prepareBibFilePaths(runparams, getBibFiles(), false);
307                 vector<docstring> db_out;
308                 for (pair<docstring, string> const & db : dbs)
309                         db_out.push_back(db.first);
310                 // Style options
311                 if (style == "default")
312                         style = buffer().masterParams().defaultBiblioStyle();
313                 if (!style.empty() && !buffer().masterParams().useBibtopic()) {
314                         string base = buffer().masterBuffer()->prepareFileNameForLaTeX(style, ".bst", runparams.nice);
315                         FileName const try_in_file =
316                                 makeAbsPath(base + ".bst", buffer().filePath());
317                         bool const not_from_texmf = try_in_file.isReadableFile();
318                         // If this style does not come from texmf and we are not
319                         // exporting to .tex copy it to the tmp directory.
320                         // This prevents problems with spaces and 8bit characters
321                         // in the file name.
322                         if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
323                             not_from_texmf) {
324                                 // use new style name
325                                 DocFileName const in_file = DocFileName(try_in_file);
326                                 base = removeExtension(in_file.mangledFileName());
327                                 FileName const out_file = makeAbsPath(base + ".bst",
328                                                 buffer().masterBuffer()->temppath());
329                                 bool const success = in_file.copyTo(out_file);
330                                 if (!success) {
331                                         LYXERR0("Failed to copy '" << in_file
332                                                << "' to '" << out_file << "'");
333                                 }
334                         }
335                         // FIXME UNICODE
336                         os << "\\bibliographystyle{"
337                            << from_utf8(latex_path(buffer().prepareFileNameForLaTeX(base, ".bst", runparams.nice)))
338                            << "}\n";
339                 }
340                 // Warn about spaces in bst path. Warn only once.
341                 static bool warned_about_bst_spaces = false;
342                 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
343                         warned_about_bst_spaces = true;
344                         Alert::warning(_("Export Warning!"),
345                                        _("There are spaces in the path to your BibTeX style file.\n"
346                                                       "BibTeX will be unable to find it."));
347                 }
348                 // Encoding
349                 bool encoding_switched = false;
350                 Encoding const * const save_enc = runparams.encoding;
351                 docstring const encoding = getParam("encoding");
352                 if (!encoding.empty() && encoding != from_ascii("default")) {
353                         Encoding const * const enc = encodings.fromLyXName(to_ascii(encoding));
354                         if (enc != runparams.encoding) {
355                                 os << "\\bgroup";
356                                 switchEncoding(os.os(), buffer().params(), runparams, *enc, true);
357                                 runparams.encoding = enc;
358                                 encoding_switched = true;
359                         }
360                 }
361                 // Handle the bibtopic case
362                 if (!db_out.empty() && buffer().masterParams().useBibtopic()) {
363                         os << "\\begin{btSect}";
364                         if (!style.empty())
365                                 os << "[" << style << "]";
366                         os << "{" << getStringFromVector(db_out) << "}\n";
367                         docstring btprint = getParam("btprint");
368                         if (btprint.empty())
369                                 // default
370                                 btprint = from_ascii("btPrintCited");
371                         os << "\\" << btprint << "\n"
372                            << "\\end{btSect}\n";
373                 }
374                 // bibtotoc option
375                 if (!bibtotoc.empty() && !buffer().masterParams().useBibtopic()
376                     && !buffer().masterParams().documentClass().bibInToc()) {
377                         // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
378                         if (buffer().masterParams().pdfoptions().use_hyperref)
379                                         os << "\\phantomsection";
380                         if (buffer().masterParams().documentClass().hasLaTeXLayout("chapter"))
381                                 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
382                         else if (buffer().masterParams().documentClass().hasLaTeXLayout("section"))
383                                 os << "\\addcontentsline{toc}{section}{\\refname}";
384                 }
385                 // The bibliography command
386                 if (!db_out.empty() && !buffer().masterParams().useBibtopic()) {
387                         docstring btprint = getParam("btprint");
388                         if (btprint == "btPrintAll") {
389                                 os << "\\nocite{*}\n";
390                         }
391                         os << "\\bibliography{" << getStringFromVector(db_out) << "}\n";
392                 }
393                 if (encoding_switched){
394                         // Switch back
395                         switchEncoding(os.os(), buffer().params(),
396                                        runparams, *save_enc, true, true);
397                         os << "\\egroup" << breakln;
398                         runparams.encoding = save_enc;
399                 }
400         }
401 }
402
403
404 docstring_list InsetBibtex::getBibFiles() const
405 {
406         return getVectorFromString(getParam("bibfiles"));
407 }
408
409 namespace {
410
411         // methods for parsing bibtex files
412
413         typedef map<docstring, docstring> VarMap;
414
415         /// remove whitespace characters, optionally a single comma,
416         /// and further whitespace characters from the stream.
417         /// @return true if a comma was found, false otherwise
418         ///
419         bool removeWSAndComma(ifdocstream & ifs) {
420                 char_type ch;
421
422                 if (!ifs)
423                         return false;
424
425                 // skip whitespace
426                 do {
427                         ifs.get(ch);
428                 } while (ifs && isSpace(ch));
429
430                 if (!ifs)
431                         return false;
432
433                 if (ch != ',') {
434                         ifs.putback(ch);
435                         return false;
436                 }
437
438                 // skip whitespace
439                 do {
440                         ifs.get(ch);
441                 } while (ifs && isSpace(ch));
442
443                 if (ifs) {
444                         ifs.putback(ch);
445                 }
446
447                 return true;
448         }
449
450
451         enum charCase {
452                 makeLowerCase,
453                 keepCase
454         };
455
456         /// remove whitespace characters, read characer sequence
457         /// not containing whitespace characters or characters in
458         /// delimChars, and remove further whitespace characters.
459         ///
460         /// @return true if a string of length > 0 could be read.
461         ///
462         bool readTypeOrKey(docstring & val, ifdocstream & ifs,
463                 docstring const & delimChars, docstring const & illegalChars,
464                 charCase chCase) {
465
466                 char_type ch;
467
468                 val.clear();
469
470                 if (!ifs)
471                         return false;
472
473                 // skip whitespace
474                 do {
475                         ifs.get(ch);
476                 } while (ifs && isSpace(ch));
477
478                 if (!ifs)
479                         return false;
480
481                 // read value
482                 while (ifs && !isSpace(ch) &&
483                        delimChars.find(ch) == docstring::npos &&
484                        illegalChars.find(ch) == docstring::npos)
485                 {
486                         if (chCase == makeLowerCase)
487                                 val += lowercase(ch);
488                         else
489                                 val += ch;
490                         ifs.get(ch);
491                 }
492
493                 if (illegalChars.find(ch) != docstring::npos) {
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 any encoding as long as some elements like keys
669         // and names are pure ASCII. We support specifying an encoding,
670         // and we convert the file from that (default is 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         docstring_list const files = getBibFiles();
678         for (auto const & bf : files) {
679                 FileName const bibfile = buffer().getBibfilePath(bf);
680                 if (bibfile.empty()) {
681                         LYXERR0("Unable to find path for " << bf << "!");
682                         continue;
683                 }
684                 if (find(checkedFiles.begin(), checkedFiles.end(), bibfile) != checkedFiles.end())
685                         // already checked this one. Skip.
686                         continue;
687                 else
688                         // record that we check this.
689                         checkedFiles.push_back(bibfile);
690                 string encoding = buffer().masterParams().encoding().iconvName();
691                 string ienc = buffer().masterParams().bibFileEncoding(to_utf8(bf));
692                 if (ienc.empty() || ienc == "general")
693                         ienc = to_ascii(params()["encoding"]);
694
695                 if (!ienc.empty() && ienc != "auto-legacy-plain" && ienc != "auto-legacy" && encodings.fromLyXName(ienc))
696                         encoding = encodings.fromLyXName(ienc)->iconvName();
697                 ifdocstream ifs(bibfile.toFilesystemEncoding().c_str(),
698                         ios_base::in, encoding);
699
700                 char_type ch;
701                 VarMap strings;
702
703                 while (ifs) {
704                         ifs.get(ch);
705                         if (!ifs)
706                                 break;
707
708                         if (ch != '@')
709                                 continue;
710
711                         docstring entryType;
712
713                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
714                                 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
715                                 continue;
716                         }
717
718                         if (!ifs) {
719                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
720                                 continue;
721                         }
722
723                         if (entryType == from_ascii("comment")) {
724                                 ifs.ignore(numeric_limits<int>::max(), '\n');
725                                 continue;
726                         }
727
728                         ifs.get(ch);
729                         if (!ifs) {
730                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
731                                 break;
732                         }
733
734                         if ((ch != '(') && (ch != '{')) {
735                                 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
736                                 ifs.putback(ch);
737                                 continue;
738                         }
739
740                         // process the entry
741                         if (entryType == from_ascii("string")) {
742
743                                 // read string and add it to the strings map
744                                 // (or replace it's old value)
745                                 docstring name;
746                                 docstring value;
747
748                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
749                                         lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
750                                         continue;
751                                 }
752
753                                 if (!ifs) {
754                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
755                                         continue;
756                                 }
757
758                                 // next char must be an equal sign
759                                 ifs.get(ch);
760                                 if (!ifs || ch != '=') {
761                                         lyxerr << "BibTeX Parser: No `=' after string name: " <<
762                                                         name << "." << std::endl;
763                                         continue;
764                                 }
765
766                                 if (!readValue(value, ifs, strings)) {
767                                         lyxerr << "BibTeX Parser: Unable to read value for string: " <<
768                                                         name << "." << std::endl;
769                                         continue;
770                                 }
771
772                                 strings[name] = value;
773
774                         } else if (entryType == from_ascii("preamble")) {
775
776                                 // preamble definitions are discarded.
777                                 // can they be of any use in lyx?
778                                 docstring value;
779
780                                 if (!readValue(value, ifs, strings)) {
781                                         lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
782                                         continue;
783                                 }
784
785                         } else {
786
787                                 // Citation entry. Try to read the key.
788                                 docstring key;
789
790                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
791                                         lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
792                                                         entryType << "." << std::endl;
793                                         continue;
794                                 }
795
796                                 if (!ifs) {
797                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
798                                         continue;
799                                 }
800
801                                 /////////////////////////////////////////////
802                                 // now we have a key, so we will add an entry
803                                 // (even if it's empty, as bibtex does)
804                                 //
805                                 // we now read the field = value pairs.
806                                 // all items must be separated by a comma. If
807                                 // it is missing the scanning of this entry is
808                                 // stopped and the next is searched.
809                                 docstring name;
810                                 docstring value;
811                                 docstring data;
812                                 BibTeXInfo keyvalmap(key, entryType);
813
814                                 bool readNext = removeWSAndComma(ifs);
815
816                                 while (ifs && readNext) {
817
818                                         // read field name
819                                         if (!readTypeOrKey(name, ifs, from_ascii("="),
820                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
821                                                 break;
822
823                                         // next char must be an equal sign
824                                         // FIXME Whitespace??
825                                         ifs.get(ch);
826                                         if (!ifs) {
827                                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
828                                                 break;
829                                         }
830                                         if (ch != '=') {
831                                                 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
832                                                                 name << ", for key: " << key << "." << std::endl;
833                                                 ifs.putback(ch);
834                                                 break;
835                                         }
836
837                                         // read field value
838                                         if (!readValue(value, ifs, strings)) {
839                                                 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
840                                                                 name << ", for key: " << key << "." << std::endl;
841                                                 break;
842                                         }
843
844                                         keyvalmap[name] = value;
845                                         data += "\n\n" + value;
846                                         keylist.addFieldName(name);
847                                         readNext = removeWSAndComma(ifs);
848                                 }
849
850                                 // add the new entry
851                                 keylist.addEntryType(entryType);
852                                 keyvalmap.setAllData(data);
853                                 keylist[key] = keyvalmap;
854                         } //< else (citation entry)
855                 } //< searching '@'
856         } //< for loop over files
857
858         buffer().addBiblioInfo(keylist);
859 }
860
861
862 bool InsetBibtex::addDatabase(docstring const & db)
863 {
864         docstring bibfiles = getParam("bibfiles");
865         if (tokenPos(bibfiles, ',', db) != -1)
866                 return false;
867         if (!bibfiles.empty())
868                 bibfiles += ',';
869         setParam("bibfiles", bibfiles + db);
870         return true;
871 }
872
873
874 bool InsetBibtex::delDatabase(docstring const & db)
875 {
876         docstring bibfiles = getParam("bibfiles");
877         if (contains(bibfiles, db)) {
878                 int const n = tokenPos(bibfiles, ',', db);
879                 docstring bd = db;
880                 if (n > 0) {
881                         // this is not the first database
882                         docstring tmp = ',' + bd;
883                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
884                 } else if (n == 0)
885                         // this is the first (or only) database
886                         setParam("bibfiles", split(bibfiles, bd, ','));
887                 else
888                         return false;
889         }
890         return true;
891 }
892
893
894 void InsetBibtex::validate(LaTeXFeatures & features) const
895 {
896         BufferParams const & mparams = features.buffer().masterParams();
897         if (mparams.useBibtopic())
898                 features.require("bibtopic");
899         else if (!mparams.useBiblatex() && mparams.multibib == "child")
900                 features.require("chapterbib");
901         // FIXME XHTML
902         // It'd be better to be able to get this from an InsetLayout, but at present
903         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
904         if (features.runparams().flavor == OutputParams::HTML)
905                 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
906                         "span.bibtexlabel:before{ content: \"[\"; }\n"
907                         "span.bibtexlabel:after{ content: \"] \"; }");
908 }
909
910
911 void InsetBibtex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
912 {
913         buffer().registerBibfiles(getBibFiles());
914         // record encoding of bib files for biblatex
915         string const enc = (params()["encoding"] == from_ascii("default")) ?
916                                 string() : to_ascii(params()["encoding"]);
917         bool invalidate = false;
918         if (buffer().params().bibEncoding() != enc) {
919                 buffer().params().setBibEncoding(enc);
920                 invalidate = true;
921         }
922         map<string, string> encs = getFileEncodings();
923         map<string, string>::const_iterator it = encs.begin();
924         for (; it != encs.end(); ++it) {
925                 if (buffer().params().bibFileEncoding(it->first) != it->second) {
926                         buffer().params().setBibFileEncoding(it->first, it->second);
927                         invalidate = true;
928                 }
929         }
930         if (invalidate)
931                 buffer().invalidateBibinfoCache();
932 }
933
934
935 map<string, string> InsetBibtex::getFileEncodings() const
936 {
937         vector<string> ps =
938                 getVectorFromString(to_utf8(getParam("file_encodings")), "\t");
939         std::map<string, string> res;
940         for (string const & s: ps) {
941                 string key;
942                 string val = split(s, key, ' ');
943                 res[key] = val;
944         }
945         return res;
946 }
947
948
949 docstring InsetBibtex::getRefLabel() const
950 {
951         if (buffer().masterParams().documentClass().hasLaTeXLayout("chapter"))
952                 return buffer().B_("Bibliography");
953         return buffer().B_("References");
954 }
955
956
957 void InsetBibtex::addToToc(DocIterator const & cpit, bool output_active,
958                            UpdateType, TocBackend & backend) const
959 {
960         if (!prefixIs(to_utf8(getParam("options")), "bibtotoc"))
961                 return;
962
963         docstring const str = getRefLabel();
964         TocBuilder & b = backend.builder("tableofcontents");
965         b.pushItem(cpit, str, output_active);
966         b.pop();
967 }
968
969
970 int InsetBibtex::plaintext(odocstringstream & os,
971        OutputParams const & op, size_t max_length) const
972 {
973         docstring const reflabel = getRefLabel();
974
975         // We could output more information here, e.g., what databases are included
976         // and information about options. But I don't necessarily see any reason to
977         // do this right now.
978         if (op.for_tooltip || op.for_toc || op.for_search) {
979                 os << '[' << reflabel << ']' << '\n';
980                 return PLAINTEXT_NEWLINE;
981         }
982
983         BiblioInfo bibinfo = buffer().masterBibInfo();
984         bibinfo.makeCitationLabels(buffer());
985         vector<docstring> const & cites = bibinfo.citedEntries();
986
987         size_t start_size = os.str().size();
988         docstring refoutput;
989         refoutput += reflabel + "\n\n";
990
991         // Tell BiblioInfo our purpose
992         CiteItem ci;
993         ci.context = CiteItem::Export;
994
995         // Now we loop over the entries
996         vector<docstring>::const_iterator vit = cites.begin();
997         vector<docstring>::const_iterator const ven = cites.end();
998         for (; vit != ven; ++vit) {
999                 if (start_size + refoutput.size() >= max_length)
1000                         break;
1001                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
1002                 if (biit == bibinfo.end())
1003                         continue;
1004                 BibTeXInfo const & entry = biit->second;
1005                 refoutput += "[" + entry.label() + "] ";
1006                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1007                 // which will give us all the cross-referenced info. But for every
1008                 // entry, so there's a lot of repitition. This should be fixed.
1009                 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
1010         }
1011         os << refoutput;
1012         return int(refoutput.size());
1013 }
1014
1015
1016 // FIXME
1017 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
1018 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
1019 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
1020 {
1021         BiblioInfo const & bibinfo = buffer().masterBibInfo();
1022         bool const all_entries = getParam("btprint") == "btPrintAll";
1023         vector<docstring> const & cites =
1024             all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
1025
1026         docstring const reflabel = buffer().B_("References");
1027
1028         // tell BiblioInfo our purpose
1029         CiteItem ci;
1030         ci.context = CiteItem::Export;
1031         ci.richtext = true;
1032         ci.max_key_size = UINT_MAX;
1033
1034         xs << html::StartTag("h2", "class='bibtex'")
1035                 << reflabel
1036                 << html::EndTag("h2")
1037                 << html::StartTag("div", "class='bibtex'");
1038
1039         // Now we loop over the entries
1040         vector<docstring>::const_iterator vit = cites.begin();
1041         vector<docstring>::const_iterator const ven = cites.end();
1042         for (; vit != ven; ++vit) {
1043                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
1044                 if (biit == bibinfo.end())
1045                         continue;
1046
1047                 BibTeXInfo const & entry = biit->second;
1048                 string const attr = "class='bibtexentry' id='LyXCite-"
1049                     + to_utf8(html::cleanAttr(entry.key())) + "'";
1050                 xs << html::StartTag("div", attr);
1051
1052                 // don't print labels if we're outputting all entries
1053                 if (!all_entries) {
1054                         xs << html::StartTag("span", "class='bibtexlabel'")
1055                                 << entry.label()
1056                                 << html::EndTag("span");
1057                 }
1058
1059                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1060                 // which will give us all the cross-referenced info. But for every
1061                 // entry, so there's a lot of repitition. This should be fixed.
1062                 xs << html::StartTag("span", "class='bibtexinfo'")
1063                    << XHTMLStream::ESCAPE_AND
1064                    << bibinfo.getInfo(entry.key(), buffer(), ci)
1065                    << html::EndTag("span")
1066                    << html::EndTag("div")
1067                    << html::CR();
1068         }
1069         xs << html::EndTag("div");
1070         return docstring();
1071 }
1072
1073
1074 void InsetBibtex::write(ostream & os) const
1075 {
1076         params().Write(os, &buffer());
1077 }
1078
1079
1080 string InsetBibtex::contextMenuName() const
1081 {
1082         return "context-bibtex";
1083 }
1084
1085
1086 } // namespace lyx