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