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