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