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