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