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