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