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