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