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