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