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