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