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