]> git.lyx.org Git - features.git/blob - src/insets/InsetBibtex.cpp
Rename legacy input encoding settings.
[features.git] / src / insets / InsetBibtex.cpp
1 /**
2  * \file InsetBibtex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Richard Heck (BibTeX parser improvements)
8  * \author Jürgen Spitzmüller
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "InsetBibtex.h"
16
17 #include "BiblioInfo.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "CiteEnginesList.h"
21 #include "Cursor.h"
22 #include "DispatchResult.h"
23 #include "Encoding.h"
24 #include "Exporter.h"
25 #include "Format.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "PDFOptions.h"
33 #include "texstream.h"
34 #include "TextClass.h"
35 #include "TocBackend.h"
36
37 #include "frontends/alert.h"
38
39 #include "support/convert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/docstring_list.h"
43 #include "support/ExceptionMessage.h"
44 #include "support/FileNameList.h"
45 #include "support/filetools.h"
46 #include "support/gettext.h"
47 #include "support/lstrings.h"
48 #include "support/os.h"
49 #include "support/PathChanger.h"
50 #include "support/textutils.h"
51
52 #include <limits>
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58
59 namespace Alert = frontend::Alert;
60 namespace os = support::os;
61
62
63 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
64         : InsetCommand(buf, p)
65 {}
66
67
68 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
69 {
70         static ParamInfo param_info_;
71         if (param_info_.empty()) {
72                 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
73                 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
74                 param_info_.add("options", ParamInfo::LYX_INTERNAL);
75                 param_info_.add("encoding", ParamInfo::LYX_INTERNAL);
76                 param_info_.add("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                         // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
368                         if (buffer().masterParams().pdfoptions().use_hyperref)
369                                         os << "\\phantomsection";
370                         if (buffer().masterParams().documentClass().hasLaTeXLayout("chapter"))
371                                 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
372                         else if (buffer().masterParams().documentClass().hasLaTeXLayout("section"))
373                                 os << "\\addcontentsline{toc}{section}{\\refname}";
374                 }
375                 // The bibliography command
376                 if (!db_out.empty() && !buffer().masterParams().useBibtopic()) {
377                         docstring btprint = getParam("btprint");
378                         if (btprint == "btPrintAll") {
379                                 os << "\\nocite{*}\n";
380                         }
381                         os << "\\bibliography{" << getStringFromVector(db_out) << "}\n";
382                 }
383                 if (encoding_switched){
384                         // Switch back
385                         switchEncoding(os.os(), buffer().params(),
386                                        runparams, *save_enc, true, true);
387                         os << "\\egroup" << breakln;
388                         runparams.encoding = save_enc;
389                 }
390         }
391 }
392
393
394 docstring_list InsetBibtex::getBibFiles() const
395 {
396         return getVectorFromString(getParam("bibfiles"));
397 }
398
399 namespace {
400
401         // methods for parsing bibtex files
402
403         typedef map<docstring, docstring> VarMap;
404
405         /// remove whitespace characters, optionally a single comma,
406         /// and further whitespace characters from the stream.
407         /// @return true if a comma was found, false otherwise
408         ///
409         bool removeWSAndComma(ifdocstream & ifs) {
410                 char_type ch;
411
412                 if (!ifs)
413                         return false;
414
415                 // skip whitespace
416                 do {
417                         ifs.get(ch);
418                 } while (ifs && isSpace(ch));
419
420                 if (!ifs)
421                         return false;
422
423                 if (ch != ',') {
424                         ifs.putback(ch);
425                         return false;
426                 }
427
428                 // skip whitespace
429                 do {
430                         ifs.get(ch);
431                 } while (ifs && isSpace(ch));
432
433                 if (ifs) {
434                         ifs.putback(ch);
435                 }
436
437                 return true;
438         }
439
440
441         enum charCase {
442                 makeLowerCase,
443                 keepCase
444         };
445
446         /// remove whitespace characters, read characer sequence
447         /// not containing whitespace characters or characters in
448         /// delimChars, and remove further whitespace characters.
449         ///
450         /// @return true if a string of length > 0 could be read.
451         ///
452         bool readTypeOrKey(docstring & val, ifdocstream & ifs,
453                 docstring const & delimChars, docstring const & illegalChars,
454                 charCase chCase) {
455
456                 char_type ch;
457
458                 val.clear();
459
460                 if (!ifs)
461                         return false;
462
463                 // skip whitespace
464                 do {
465                         ifs.get(ch);
466                 } while (ifs && isSpace(ch));
467
468                 if (!ifs)
469                         return false;
470
471                 // read value
472                 while (ifs && !isSpace(ch) &&
473                        delimChars.find(ch) == docstring::npos &&
474                        illegalChars.find(ch) == docstring::npos)
475                 {
476                         if (chCase == makeLowerCase)
477                                 val += lowercase(ch);
478                         else
479                                 val += ch;
480                         ifs.get(ch);
481                 }
482
483                 if (illegalChars.find(ch) != docstring::npos) {
484                         ifs.putback(ch);
485                         return false;
486                 }
487
488                 // skip whitespace
489                 while (ifs && isSpace(ch)) {
490                         ifs.get(ch);
491                 }
492
493                 if (ifs) {
494                         ifs.putback(ch);
495                 }
496
497                 return val.length() > 0;
498         }
499
500         /// read subsequent bibtex values that are delimited with a #-character.
501         /// Concatenate all parts and replace names with the associated string in
502         /// the variable strings.
503         /// @return true if reading was successfull (all single parts were delimited
504         /// correctly)
505         bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
506
507                 char_type ch;
508
509                 val.clear();
510
511                 if (!ifs)
512                         return false;
513
514                 do {
515                         // skip whitespace
516                         do {
517                                 ifs.get(ch);
518                         } while (ifs && isSpace(ch));
519
520                         if (!ifs)
521                                 return false;
522
523                         // check for field type
524                         if (isDigitASCII(ch)) {
525
526                                 // read integer value
527                                 do {
528                                         val += ch;
529                                         ifs.get(ch);
530                                 } while (ifs && isDigitASCII(ch));
531
532                                 if (!ifs)
533                                         return false;
534
535                         } else if (ch == '"' || ch == '{') {
536                                 // set end delimiter
537                                 char_type delim = ch == '"' ? '"': '}';
538
539                                 // Skip whitespace
540                                 do {
541                                         ifs.get(ch);
542                                 } while (ifs && isSpace(ch));
543
544                                 if (!ifs)
545                                         return false;
546
547                                 // We now have the first non-whitespace character
548                                 // We'll collapse adjacent whitespace.
549                                 bool lastWasWhiteSpace = false;
550
551                                 // inside this delimited text braces must match.
552                                 // Thus we can have a closing delimiter only
553                                 // when nestLevel == 0
554                                 int nestLevel = 0;
555
556                                 while (ifs && (nestLevel > 0 || ch != delim)) {
557                                         if (isSpace(ch)) {
558                                                 lastWasWhiteSpace = true;
559                                                 ifs.get(ch);
560                                                 continue;
561                                         }
562                                         // We output the space only after we stop getting
563                                         // whitespace so as not to output any whitespace
564                                         // at the end of the value.
565                                         if (lastWasWhiteSpace) {
566                                                 lastWasWhiteSpace = false;
567                                                 val += ' ';
568                                         }
569
570                                         val += ch;
571
572                                         // update nesting level
573                                         switch (ch) {
574                                                 case '{':
575                                                         ++nestLevel;
576                                                         break;
577                                                 case '}':
578                                                         --nestLevel;
579                                                         if (nestLevel < 0)
580                                                                 return false;
581                                                         break;
582                                         }
583
584                                         if (ifs)
585                                                 ifs.get(ch);
586                                 }
587
588                                 if (!ifs)
589                                         return false;
590
591                                 // FIXME Why is this here?
592                                 ifs.get(ch);
593
594                                 if (!ifs)
595                                         return false;
596
597                         } else {
598
599                                 // reading a string name
600                                 docstring strName;
601
602                                 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
603                                         strName += lowercase(ch);
604                                         ifs.get(ch);
605                                 }
606
607                                 if (!ifs)
608                                         return false;
609
610                                 // replace the string with its assigned value or
611                                 // discard it if it's not assigned
612                                 if (strName.length()) {
613                                         VarMap::const_iterator pos = strings.find(strName);
614                                         if (pos != strings.end()) {
615                                                 val += pos->second;
616                                         }
617                                 }
618                         }
619
620                         // skip WS
621                         while (ifs && isSpace(ch)) {
622                                 ifs.get(ch);
623                         }
624
625                         if (!ifs)
626                                 return false;
627
628                         // continue reading next value on concatenate with '#'
629                 } while (ch == '#');
630
631                 ifs.putback(ch);
632
633                 return true;
634         }
635 } // namespace
636
637
638 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
639 {
640         parseBibTeXFiles(checkedFiles);
641 }
642
643
644 void InsetBibtex::parseBibTeXFiles(FileNameList & checkedFiles) const
645 {
646         // This bibtex parser is a first step to parse bibtex files
647         // more precisely.
648         //
649         // - it reads the whole bibtex entry and does a syntax check
650         //   (matching delimiters, missing commas,...
651         // - it recovers from errors starting with the next @-character
652         // - it reads @string definitions and replaces them in the
653         //   field values.
654         // - it accepts more characters in keys or value names than
655         //   bibtex does.
656         //
657         // Officially bibtex does only support ASCII, but in practice
658         // you can use any encoding as long as some elements like keys
659         // and names are pure ASCII. We support specifying an encoding,
660         // and we convert the file from that (default is buffer encoding).
661         // We don't restrict keys to ASCII in LyX, since our own
662         // InsetBibitem can generate non-ASCII keys, and nonstandard
663         // 8bit clean bibtex forks exist.
664
665         BiblioInfo keylist;
666
667         docstring_list const files = getBibFiles();
668         for (auto const & bf : files) {
669                 FileName const bibfile = buffer().getBibfilePath(bf);
670                 if (bibfile.empty()) {
671                         LYXERR0("Unable to find path for " << bf << "!");
672                         continue;
673                 }
674                 if (find(checkedFiles.begin(), checkedFiles.end(), bibfile) != checkedFiles.end())
675                         // already checked this one. Skip.
676                         continue;
677                 else
678                         // record that we check this.
679                         checkedFiles.push_back(bibfile);
680                 string encoding = buffer().masterParams().encoding().iconvName();
681                 string ienc = buffer().masterParams().bibFileEncoding(to_utf8(bf));
682                 if (ienc.empty() || ienc == "general")
683                         ienc = to_ascii(params()["encoding"]);
684
685                 if (!ienc.empty() && ienc != "auto-legacy-plain" && ienc != "auto-legacy" && encodings.fromLyXName(ienc))
686                         encoding = encodings.fromLyXName(ienc)->iconvName();
687                 ifdocstream ifs(bibfile.toFilesystemEncoding().c_str(),
688                         ios_base::in, encoding);
689
690                 char_type ch;
691                 VarMap strings;
692
693                 while (ifs) {
694                         ifs.get(ch);
695                         if (!ifs)
696                                 break;
697
698                         if (ch != '@')
699                                 continue;
700
701                         docstring entryType;
702
703                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
704                                 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
705                                 continue;
706                         }
707
708                         if (!ifs) {
709                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
710                                 continue;
711                         }
712
713                         if (entryType == from_ascii("comment")) {
714                                 ifs.ignore(numeric_limits<int>::max(), '\n');
715                                 continue;
716                         }
717
718                         ifs.get(ch);
719                         if (!ifs) {
720                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
721                                 break;
722                         }
723
724                         if ((ch != '(') && (ch != '{')) {
725                                 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
726                                 ifs.putback(ch);
727                                 continue;
728                         }
729
730                         // process the entry
731                         if (entryType == from_ascii("string")) {
732
733                                 // read string and add it to the strings map
734                                 // (or replace it's old value)
735                                 docstring name;
736                                 docstring value;
737
738                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
739                                         lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
740                                         continue;
741                                 }
742
743                                 if (!ifs) {
744                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
745                                         continue;
746                                 }
747
748                                 // next char must be an equal sign
749                                 ifs.get(ch);
750                                 if (!ifs || ch != '=') {
751                                         lyxerr << "BibTeX Parser: No `=' after string name: " <<
752                                                         name << "." << std::endl;
753                                         continue;
754                                 }
755
756                                 if (!readValue(value, ifs, strings)) {
757                                         lyxerr << "BibTeX Parser: Unable to read value for string: " <<
758                                                         name << "." << std::endl;
759                                         continue;
760                                 }
761
762                                 strings[name] = value;
763
764                         } else if (entryType == from_ascii("preamble")) {
765
766                                 // preamble definitions are discarded.
767                                 // can they be of any use in lyx?
768                                 docstring value;
769
770                                 if (!readValue(value, ifs, strings)) {
771                                         lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
772                                         continue;
773                                 }
774
775                         } else {
776
777                                 // Citation entry. Try to read the key.
778                                 docstring key;
779
780                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
781                                         lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
782                                                         entryType << "." << std::endl;
783                                         continue;
784                                 }
785
786                                 if (!ifs) {
787                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
788                                         continue;
789                                 }
790
791                                 /////////////////////////////////////////////
792                                 // now we have a key, so we will add an entry
793                                 // (even if it's empty, as bibtex does)
794                                 //
795                                 // we now read the field = value pairs.
796                                 // all items must be separated by a comma. If
797                                 // it is missing the scanning of this entry is
798                                 // stopped and the next is searched.
799                                 docstring name;
800                                 docstring value;
801                                 docstring data;
802                                 BibTeXInfo keyvalmap(key, entryType);
803
804                                 bool readNext = removeWSAndComma(ifs);
805
806                                 while (ifs && readNext) {
807
808                                         // read field name
809                                         if (!readTypeOrKey(name, ifs, from_ascii("="),
810                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
811                                                 break;
812
813                                         // next char must be an equal sign
814                                         // FIXME Whitespace??
815                                         ifs.get(ch);
816                                         if (!ifs) {
817                                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
818                                                 break;
819                                         }
820                                         if (ch != '=') {
821                                                 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
822                                                                 name << ", for key: " << key << "." << std::endl;
823                                                 ifs.putback(ch);
824                                                 break;
825                                         }
826
827                                         // read field value
828                                         if (!readValue(value, ifs, strings)) {
829                                                 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
830                                                                 name << ", for key: " << key << "." << std::endl;
831                                                 break;
832                                         }
833
834                                         keyvalmap[name] = value;
835                                         data += "\n\n" + value;
836                                         keylist.addFieldName(name);
837                                         readNext = removeWSAndComma(ifs);
838                                 }
839
840                                 // add the new entry
841                                 keylist.addEntryType(entryType);
842                                 keyvalmap.setAllData(data);
843                                 keylist[key] = keyvalmap;
844                         } //< else (citation entry)
845                 } //< searching '@'
846         } //< for loop over files
847
848         buffer().addBiblioInfo(keylist);
849 }
850
851
852 bool InsetBibtex::addDatabase(docstring const & db)
853 {
854         docstring bibfiles = getParam("bibfiles");
855         if (tokenPos(bibfiles, ',', db) != -1)
856                 return false;
857         if (!bibfiles.empty())
858                 bibfiles += ',';
859         setParam("bibfiles", bibfiles + db);
860         return true;
861 }
862
863
864 bool InsetBibtex::delDatabase(docstring const & db)
865 {
866         docstring bibfiles = getParam("bibfiles");
867         if (contains(bibfiles, db)) {
868                 int const n = tokenPos(bibfiles, ',', db);
869                 docstring bd = db;
870                 if (n > 0) {
871                         // this is not the first database
872                         docstring tmp = ',' + bd;
873                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
874                 } else if (n == 0)
875                         // this is the first (or only) database
876                         setParam("bibfiles", split(bibfiles, bd, ','));
877                 else
878                         return false;
879         }
880         return true;
881 }
882
883
884 void InsetBibtex::validate(LaTeXFeatures & features) const
885 {
886         BufferParams const & mparams = features.buffer().masterParams();
887         if (mparams.useBibtopic())
888                 features.require("bibtopic");
889         else if (!mparams.useBiblatex() && mparams.multibib == "child")
890                 features.require("chapterbib");
891         // FIXME XHTML
892         // It'd be better to be able to get this from an InsetLayout, but at present
893         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
894         if (features.runparams().flavor == OutputParams::HTML)
895                 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
896                         "span.bibtexlabel:before{ content: \"[\"; }\n"
897                         "span.bibtexlabel:after{ content: \"] \"; }");
898 }
899
900
901 void InsetBibtex::updateBuffer(ParIterator const &, UpdateType)
902 {
903         buffer().registerBibfiles(getBibFiles());
904         // record encoding of bib files for biblatex
905         string const enc = (params()["encoding"] == from_ascii("default")) ?
906                                 string() : to_ascii(params()["encoding"]);
907         bool invalidate = false;
908         if (buffer().params().bibEncoding() != enc) {
909                 buffer().params().setBibEncoding(enc);
910                 invalidate = true;
911         }
912         map<string, string> encs = getFileEncodings();
913         map<string, string>::const_iterator it = encs.begin();
914         for (; it != encs.end(); ++it) {
915                 if (buffer().params().bibFileEncoding(it->first) != it->second) {
916                         buffer().params().setBibFileEncoding(it->first, it->second);
917                         invalidate = true;
918                 }
919         }
920         if (invalidate)
921                 buffer().invalidateBibinfoCache();
922 }
923
924
925 map<string, string> InsetBibtex::getFileEncodings() const
926 {
927         vector<string> ps =
928                 getVectorFromString(to_utf8(getParam("file_encodings")), "\t");
929         std::map<string, string> res;
930         for (string const & s: ps) {
931                 string key;
932                 string val = split(s, key, ' ');
933                 res[key] = val;
934         }
935         return res;
936 }
937
938
939 docstring InsetBibtex::getRefLabel() const
940 {
941         if (buffer().masterParams().documentClass().hasLaTeXLayout("chapter"))
942                 return buffer().B_("Bibliography");
943         return buffer().B_("References");
944 }
945
946
947 void InsetBibtex::addToToc(DocIterator const & cpit, bool output_active,
948                            UpdateType, TocBackend & backend) const
949 {
950         if (!prefixIs(to_utf8(getParam("options")), "bibtotoc"))
951                 return;
952
953         docstring const str = getRefLabel();
954         TocBuilder & b = backend.builder("tableofcontents");
955         b.pushItem(cpit, str, output_active);
956         b.pop();
957 }
958
959
960 int InsetBibtex::plaintext(odocstringstream & os,
961        OutputParams const & op, size_t max_length) const
962 {
963         docstring const reflabel = getRefLabel();
964
965         // We could output more information here, e.g., what databases are included
966         // and information about options. But I don't necessarily see any reason to
967         // do this right now.
968         if (op.for_tooltip || op.for_toc || op.for_search) {
969                 os << '[' << reflabel << ']' << '\n';
970                 return PLAINTEXT_NEWLINE;
971         }
972
973         BiblioInfo bibinfo = buffer().masterBibInfo();
974         bibinfo.makeCitationLabels(buffer());
975         vector<docstring> const & cites = bibinfo.citedEntries();
976
977         size_t start_size = os.str().size();
978         docstring refoutput;
979         refoutput += reflabel + "\n\n";
980
981         // Tell BiblioInfo our purpose
982         CiteItem ci;
983         ci.context = CiteItem::Export;
984
985         // Now we loop over the entries
986         vector<docstring>::const_iterator vit = cites.begin();
987         vector<docstring>::const_iterator const ven = cites.end();
988         for (; vit != ven; ++vit) {
989                 if (start_size + refoutput.size() >= max_length)
990                         break;
991                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
992                 if (biit == bibinfo.end())
993                         continue;
994                 BibTeXInfo const & entry = biit->second;
995                 refoutput += "[" + entry.label() + "] ";
996                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
997                 // which will give us all the cross-referenced info. But for every
998                 // entry, so there's a lot of repitition. This should be fixed.
999                 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
1000         }
1001         os << refoutput;
1002         return int(refoutput.size());
1003 }
1004
1005
1006 // FIXME
1007 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
1008 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
1009 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
1010 {
1011         BiblioInfo const & bibinfo = buffer().masterBibInfo();
1012         bool const all_entries = getParam("btprint") == "btPrintAll";
1013         vector<docstring> const & cites =
1014             all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
1015
1016         docstring const reflabel = buffer().B_("References");
1017
1018         // tell BiblioInfo our purpose
1019         CiteItem ci;
1020         ci.context = CiteItem::Export;
1021         ci.richtext = true;
1022         ci.max_key_size = UINT_MAX;
1023
1024         xs << html::StartTag("h2", "class='bibtex'")
1025                 << reflabel
1026                 << html::EndTag("h2")
1027                 << html::StartTag("div", "class='bibtex'");
1028
1029         // Now we loop over the entries
1030         vector<docstring>::const_iterator vit = cites.begin();
1031         vector<docstring>::const_iterator const ven = cites.end();
1032         for (; vit != ven; ++vit) {
1033                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
1034                 if (biit == bibinfo.end())
1035                         continue;
1036
1037                 BibTeXInfo const & entry = biit->second;
1038                 string const attr = "class='bibtexentry' id='LyXCite-"
1039                     + to_utf8(html::cleanAttr(entry.key())) + "'";
1040                 xs << html::StartTag("div", attr);
1041
1042                 // don't print labels if we're outputting all entries
1043                 if (!all_entries) {
1044                         xs << html::StartTag("span", "class='bibtexlabel'")
1045                                 << entry.label()
1046                                 << html::EndTag("span");
1047                 }
1048
1049                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1050                 // which will give us all the cross-referenced info. But for every
1051                 // entry, so there's a lot of repitition. This should be fixed.
1052                 xs << html::StartTag("span", "class='bibtexinfo'")
1053                    << XHTMLStream::ESCAPE_AND
1054                    << bibinfo.getInfo(entry.key(), buffer(), ci)
1055                    << html::EndTag("span")
1056                    << html::EndTag("div")
1057                    << html::CR();
1058         }
1059         xs << html::EndTag("div");
1060         return docstring();
1061 }
1062
1063
1064 void InsetBibtex::write(ostream & os) const
1065 {
1066         params().Write(os, &buffer());
1067 }
1068
1069
1070 string InsetBibtex::contextMenuName() const
1071 {
1072         return "context-bibtex";
1073 }
1074
1075
1076 } // namespace lyx