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