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