]> git.lyx.org Git - features.git/blob - src/insets/InsetBibtex.cpp
Beautify ToolTips in work area
[features.git] / src / insets / InsetBibtex.cpp
1 /**
2  * \file InsetBibtex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Richard Heck (BibTeX parser improvements)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetBibtex.h"
15
16 #include "BiblioInfo.h"
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "Cursor.h"
20 #include "DispatchResult.h"
21 #include "Encoding.h"
22 #include "Exporter.h"
23 #include "Format.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "output_xhtml.h"
28 #include "OutputParams.h"
29 #include "PDFOptions.h"
30 #include "TextClass.h"
31
32 #include "frontends/alert.h"
33
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/ExceptionMessage.h"
38 #include "support/FileNameList.h"
39 #include "support/filetools.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/os.h"
43 #include "support/PathChanger.h"
44 #include "support/textutils.h"
45
46 #include <limits>
47
48 using namespace std;
49 using namespace lyx::support;
50
51 namespace lyx {
52
53 namespace Alert = frontend::Alert;
54 namespace os = support::os;
55
56
57 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
58         : InsetCommand(buf, p)
59 {
60         buffer().invalidateBibfileCache();
61         buffer().removeBiblioTempFiles();
62 }
63
64
65 InsetBibtex::~InsetBibtex()
66 {
67         if (isBufferLoaded()) {
68                 buffer().invalidateBibfileCache();
69                 buffer().removeBiblioTempFiles();
70         }
71 }
72
73
74 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
75 {
76         static ParamInfo param_info_;
77         if (param_info_.empty()) {
78                 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
79                 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
80                 param_info_.add("options", ParamInfo::LYX_INTERNAL);
81         }
82         return param_info_;
83 }
84
85
86 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
87 {
88         switch (cmd.action()) {
89
90         case LFUN_INSET_EDIT:
91                 editDatabases();
92                 break;
93
94         case LFUN_INSET_MODIFY: {
95                 InsetCommandParams p(BIBTEX_CODE);
96                 try {
97                         if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
98                                 cur.noScreenUpdate();
99                                 break;
100                         }
101                 } catch (ExceptionMessage const & message) {
102                         if (message.type_ == WarningException) {
103                                 Alert::warning(message.title_, message.details_);
104                                 cur.noScreenUpdate();
105                         } else
106                                 throw;
107                         break;
108                 }
109
110                 cur.recordUndo();
111                 setParams(p);
112                 buffer().invalidateBibfileCache();
113                 buffer().removeBiblioTempFiles();
114                 cur.forceBufferUpdate();
115                 break;
116         }
117
118         default:
119                 InsetCommand::doDispatch(cur, cmd);
120                 break;
121         }
122 }
123
124
125 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
126                 FuncStatus & flag) const
127 {
128         switch (cmd.action()) {
129         case LFUN_INSET_EDIT:
130                 flag.setEnabled(true);
131                 return true;
132
133         default:
134                 return InsetCommand::getStatus(cur, cmd, flag);
135         }
136 }
137
138
139 void InsetBibtex::editDatabases() const
140 {
141         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
142
143         if (bibfilelist.empty())
144                 return;
145
146         int nr_databases = bibfilelist.size();
147         if (nr_databases > 1) {
148                         docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
149                                                        "If you proceed, all of them will be opened."),
150                                                         convert<docstring>(nr_databases));
151                         int const ret = Alert::prompt(_("Open Databases?"),
152                                 message, 0, 1, _("&Cancel"), _("&Proceed"));
153
154                         if (ret == 0)
155                                 return;
156         }
157
158         vector<docstring>::const_iterator it = bibfilelist.begin();
159         vector<docstring>::const_iterator en = bibfilelist.end();
160         for (; it != en; ++it) {
161                 FileName const bibfile = getBibTeXPath(*it, buffer());
162                 formats.edit(buffer(), bibfile,
163                      formats.getFormatFromFile(bibfile));
164         }
165 }
166
167
168 docstring InsetBibtex::screenLabel() const
169 {
170         return _("BibTeX Generated Bibliography");
171 }
172
173
174 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
175 {
176         docstring tip = _("Databases:");
177         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
178
179         tip += "<ul>";
180         if (bibfilelist.empty())
181                 tip += "<li>" + _("none") + "</li>";
182         else
183                 for (docstring const & bibfile : bibfilelist)
184                         tip += "<li>" + bibfile + "</li>";
185         tip += "</ul>";
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:");
198         tip += "<ul><li>" + (style.empty() ? _("none") : style) + "</li></ul>";
199
200         tip += _("Lists:") + " ";
201         docstring btprint = getParam("btprint");
202                 if (btprint == "btPrintAll")
203                         tip += _("all references");
204                 else if (btprint == "btPrintNotCited")
205                         tip += _("all uncited references");
206                 else
207                         tip += _("all cited references");
208
209         if (toc) {
210                 tip += ", ";
211                 tip += _("included in TOC");
212         }
213
214         return tip;
215 }
216
217
218 static string normalizeName(Buffer const & buffer,
219         OutputParams const & runparams, string const & name, string const & ext)
220 {
221         string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
222         if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
223                 return name;
224         if (!runparams.nice)
225                 return fname;
226
227         // FIXME UNICODE
228         return to_utf8(makeRelPath(from_utf8(fname),
229                                          from_utf8(buffer.masterBuffer()->filePath())));
230 }
231
232
233 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
234 {
235         // the sequence of the commands:
236         // 1. \bibliographystyle{style}
237         // 2. \addcontentsline{...} - if option bibtotoc set
238         // 3. \bibliography{database}
239         // and with bibtopic:
240         // 1. \bibliographystyle{style}
241         // 2. \begin{btSect}{database}
242         // 3. \btPrint{Cited|NotCited|All}
243         // 4. \end{btSect}
244
245         // Database(s)
246         // If we are processing the LaTeX file in a temp directory then
247         // copy the .bib databases to this temp directory, mangling their
248         // names in the process. Store this mangled name in the list of
249         // all databases.
250         // (We need to do all this because BibTeX *really*, *really*
251         // can't handle "files with spaces" and Windows users tend to
252         // use such filenames.)
253         // Otherwise, store the (maybe absolute) path to the original,
254         // unmangled database name.
255         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
256         vector<docstring>::const_iterator it = bibfilelist.begin();
257         vector<docstring>::const_iterator en = bibfilelist.end();
258         odocstringstream dbs;
259         bool didone = false;
260
261         // determine the export format
262         string const tex_format = flavor2format(runparams.flavor);
263
264         for (; it != en; ++it) {
265                 string utf8input = to_utf8(*it);
266                 string database =
267                         normalizeName(buffer(), runparams, utf8input, ".bib");
268                 FileName const try_in_file =
269                         makeAbsPath(database + ".bib", buffer().filePath());
270                 bool const not_from_texmf = try_in_file.isReadableFile();
271
272                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
273                     not_from_texmf) {
274                         // mangledFileName() needs the extension
275                         DocFileName const in_file = DocFileName(try_in_file);
276                         database = removeExtension(in_file.mangledFileName());
277                         FileName const out_file = makeAbsPath(database + ".bib",
278                                         buffer().masterBuffer()->temppath());
279                         bool const success = in_file.copyTo(out_file);
280                         if (!success) {
281                                 lyxerr << "Failed to copy '" << in_file
282                                        << "' to '" << out_file << "'"
283                                        << endl;
284                         }
285                 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
286                         runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
287                         if (!isValidLaTeXFileName(database)) {
288                                 frontend::Alert::warning(_("Invalid filename"),
289                                          _("The following filename will cause troubles "
290                                                "when running the exported file through LaTeX: ") +
291                                              from_utf8(database));
292                         }
293                         if (!isValidDVIFileName(database)) {
294                                 frontend::Alert::warning(_("Problematic filename for DVI"),
295                                          _("The following filename can cause troubles "
296                                                "when running the exported file through LaTeX "
297                                                    "and opening the resulting DVI: ") +
298                                              from_utf8(database), true);
299                         }
300                 }
301
302                 if (didone)
303                         dbs << ',';
304                 else
305                         didone = true;
306                 // FIXME UNICODE
307                 dbs << from_utf8(latex_path(database));
308         }
309         docstring const db_out = dbs.str();
310
311         // Post this warning only once.
312         static bool warned_about_spaces = false;
313         if (!warned_about_spaces &&
314             runparams.nice && db_out.find(' ') != docstring::npos) {
315                 warned_about_spaces = true;
316                 Alert::warning(_("Export Warning!"),
317                                _("There are spaces in the paths to your BibTeX databases.\n"
318                                               "BibTeX will be unable to find them."));
319         }
320         // Style-Options
321         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
322         string bibtotoc;
323         if (prefixIs(style, "bibtotoc")) {
324                 bibtotoc = "bibtotoc";
325                 if (contains(style, ','))
326                         style = split(style, bibtotoc, ',');
327         }
328
329         if (style == "default")
330                 style = buffer().params().biblio_style;
331
332         if (!style.empty() && !buffer().params().use_bibtopic) {
333                 string base = normalizeName(buffer(), runparams, style, ".bst");
334                 FileName const try_in_file =
335                         makeAbsPath(base + ".bst", buffer().filePath());
336                 bool const not_from_texmf = try_in_file.isReadableFile();
337                 // If this style does not come from texmf and we are not
338                 // exporting to .tex copy it to the tmp directory.
339                 // This prevents problems with spaces and 8bit charcaters
340                 // in the file name.
341                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
342                     not_from_texmf) {
343                         // use new style name
344                         DocFileName const in_file = DocFileName(try_in_file);
345                         base = removeExtension(in_file.mangledFileName());
346                         FileName const out_file = makeAbsPath(base + ".bst",
347                                         buffer().masterBuffer()->temppath());
348                         bool const success = in_file.copyTo(out_file);
349                         if (!success) {
350                                 lyxerr << "Failed to copy '" << in_file
351                                        << "' to '" << out_file << "'"
352                                        << endl;
353                         }
354                 }
355                 // FIXME UNICODE
356                 os << "\\bibliographystyle{"
357                    << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
358                    << "}\n";
359         }
360
361         // Post this warning only once.
362         static bool warned_about_bst_spaces = false;
363         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
364                 warned_about_bst_spaces = true;
365                 Alert::warning(_("Export Warning!"),
366                                _("There are spaces in the path to your BibTeX style file.\n"
367                                               "BibTeX will be unable to find it."));
368         }
369
370         if (!db_out.empty() && buffer().params().use_bibtopic) {
371                 os << "\\begin{btSect}";
372                 if (!style.empty())
373                         os << "[" << style << "]";
374                 os << "{" << 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.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
920                         "span.bibtexlabel:before{ content: \"[\"; }\n"
921                         "span.bibtexlabel:after{ content: \"] \"; }");
922 }
923
924
925 int InsetBibtex::plaintext(odocstringstream & os,
926        OutputParams const & op, size_t max_length) const
927 {
928         docstring const reflabel = buffer().B_("References");
929
930         // We could output more information here, e.g., what databases are included
931         // and information about options. But I don't necessarily see any reason to
932         // do this right now.
933         if (op.for_tooltip || op.for_toc || op.for_search) {
934                 os << '[' << reflabel << ']' << '\n';
935                 return PLAINTEXT_NEWLINE;
936         }
937
938         BiblioInfo bibinfo = buffer().masterBibInfo();
939         bibinfo.makeCitationLabels(buffer());
940         vector<docstring> const & cites = bibinfo.citedEntries();
941
942         size_t start_size = os.str().size();
943         docstring refoutput;
944         refoutput += reflabel + "\n\n";
945
946         // Now we loop over the entries
947         vector<docstring>::const_iterator vit = cites.begin();
948         vector<docstring>::const_iterator const ven = cites.end();
949         for (; vit != ven; ++vit) {
950                 if (start_size + refoutput.size() >= max_length)
951                         break;
952                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
953                 if (biit == bibinfo.end())
954                         continue;
955                 BibTeXInfo const & entry = biit->second;
956                 refoutput += "[" + entry.label() + "] ";
957                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
958                 // which will give us all the cross-referenced info. But for every
959                 // entry, so there's a lot of repitition. This should be fixed.
960                 refoutput += bibinfo.getInfo(entry.key(), buffer(), false) + "\n\n";
961         }
962         os << refoutput;
963         return refoutput.size();
964 }
965
966
967 // FIXME
968 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
969 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
970 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
971 {
972         BiblioInfo const & bibinfo = buffer().masterBibInfo();
973         bool const all_entries = getParam("btprint") == "btPrintAll";
974         vector<docstring> const & cites = 
975             all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
976
977         docstring const reflabel = buffer().B_("References");
978
979         xs << html::StartTag("h2", "class='bibtex'")
980                 << reflabel
981                 << html::EndTag("h2")
982                 << html::StartTag("div", "class='bibtex'");
983
984         // Now we loop over the entries
985         vector<docstring>::const_iterator vit = cites.begin();
986         vector<docstring>::const_iterator const ven = cites.end();
987         for (; vit != ven; ++vit) {
988                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
989                 if (biit == bibinfo.end())
990                         continue;
991
992                 BibTeXInfo const & entry = biit->second;
993                 string const attr = "class='bibtexentry' id='LyXCite-" 
994                     + to_utf8(html::cleanAttr(entry.key())) + "'";
995                 xs << html::StartTag("div", attr);
996                 
997                 // don't print labels if we're outputting all entries
998                 if (!all_entries) {
999                         xs << html::StartTag("span", "class='bibtexlabel'")
1000                                 << entry.label()
1001                                 << html::EndTag("span");
1002                 }
1003                 
1004                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1005                 // which will give us all the cross-referenced info. But for every
1006                 // entry, so there's a lot of repitition. This should be fixed.
1007                 xs << html::StartTag("span", "class='bibtexinfo'")
1008                    << XHTMLStream::ESCAPE_AND
1009                    << bibinfo.getInfo(entry.key(), buffer(), true)
1010                    << html::EndTag("span")
1011                    << html::EndTag("div")
1012                    << html::CR();
1013         }
1014         xs << html::EndTag("div");
1015         return docstring();
1016 }
1017
1018
1019 void InsetBibtex::write(ostream & os) const
1020 {
1021         params().Write(os, &buffer());
1022 }
1023
1024
1025 string InsetBibtex::contextMenuName() const
1026 {
1027         return "context-bibtex";
1028 }
1029
1030
1031 } // namespace lyx