]> git.lyx.org Git - features.git/blob - src/insets/InsetBibtex.cpp
Merge branch 'master' into biblatex2
[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 "texstream.h"
31 #include "TextClass.h"
32
33 #include "frontends/alert.h"
34
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/FileNameList.h"
40 #include "support/filetools.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/os.h"
44 #include "support/PathChanger.h"
45 #include "support/textutils.h"
46
47 #include <limits>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace lyx {
53
54 namespace Alert = frontend::Alert;
55 namespace os = support::os;
56
57
58 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
59         : InsetCommand(buf, p)
60 {
61         buffer().invalidateBibfileCache();
62         buffer().removeBiblioTempFiles();
63 }
64
65
66 InsetBibtex::~InsetBibtex()
67 {
68         if (isBufferLoaded()) {
69                 buffer().invalidateBibfileCache();
70                 buffer().removeBiblioTempFiles();
71         }
72 }
73
74
75 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
76 {
77         static ParamInfo param_info_;
78         if (param_info_.empty()) {
79                 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
80                 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
81                 param_info_.add("options", ParamInfo::LYX_INTERNAL);
82         }
83         return param_info_;
84 }
85
86
87 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
88 {
89         switch (cmd.action()) {
90
91         case LFUN_INSET_EDIT:
92                 editDatabases();
93                 break;
94
95         case LFUN_INSET_MODIFY: {
96                 InsetCommandParams p(BIBTEX_CODE);
97                 try {
98                         if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
99                                 cur.noScreenUpdate();
100                                 break;
101                         }
102                 } catch (ExceptionMessage const & message) {
103                         if (message.type_ == WarningException) {
104                                 Alert::warning(message.title_, message.details_);
105                                 cur.noScreenUpdate();
106                         } else
107                                 throw;
108                         break;
109                 }
110
111                 cur.recordUndo();
112                 setParams(p);
113                 buffer().invalidateBibfileCache();
114                 buffer().removeBiblioTempFiles();
115                 cur.forceBufferUpdate();
116                 break;
117         }
118
119         default:
120                 InsetCommand::doDispatch(cur, cmd);
121                 break;
122         }
123 }
124
125
126 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
127                 FuncStatus & flag) const
128 {
129         switch (cmd.action()) {
130         case LFUN_INSET_EDIT:
131                 flag.setEnabled(true);
132                 return true;
133
134         default:
135                 return InsetCommand::getStatus(cur, cmd, flag);
136         }
137 }
138
139
140 void InsetBibtex::editDatabases() const
141 {
142         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
143
144         if (bibfilelist.empty())
145                 return;
146
147         int nr_databases = bibfilelist.size();
148         if (nr_databases > 1) {
149                         docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
150                                                        "If you proceed, all of them will be opened."),
151                                                         convert<docstring>(nr_databases));
152                         int const ret = Alert::prompt(_("Open Databases?"),
153                                 message, 0, 1, _("&Cancel"), _("&Proceed"));
154
155                         if (ret == 0)
156                                 return;
157         }
158
159         vector<docstring>::const_iterator it = bibfilelist.begin();
160         vector<docstring>::const_iterator en = bibfilelist.end();
161         for (; it != en; ++it) {
162                 FileName const bibfile = getBibTeXPath(*it, buffer());
163                 formats.edit(buffer(), bibfile,
164                      formats.getFormatFromFile(bibfile));
165         }
166 }
167
168
169 docstring InsetBibtex::screenLabel() const
170 {
171         return _("BibTeX Generated Bibliography");
172 }
173
174
175 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
176 {
177         docstring tip = _("Databases:");
178         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
179
180         tip += "<ul>";
181         if (bibfilelist.empty())
182                 tip += "<li>" + _("none") + "</li>";
183         else
184                 for (docstring const & bibfile : bibfilelist)
185                         tip += "<li>" + bibfile + "</li>";
186         tip += "</ul>";
187
188         // Style-Options
189         bool toc = false;
190         docstring style = getParam("options"); // maybe empty! and with bibtotoc
191         docstring bibtotoc = from_ascii("bibtotoc");
192         if (prefixIs(style, bibtotoc)) {
193                 toc = true;
194                 if (contains(style, char_type(',')))
195                         style = split(style, bibtotoc, char_type(','));
196         }
197
198         tip += _("Style File:");
199         tip += "<ul><li>" + (style.empty() ? _("none") : style) + "</li></ul>";
200
201         tip += _("Lists:") + " ";
202         docstring btprint = getParam("btprint");
203                 if (btprint == "btPrintAll")
204                         tip += _("all references");
205                 else if (btprint == "btPrintNotCited")
206                         tip += _("all uncited references");
207                 else
208                         tip += _("all cited references");
209
210         if (toc) {
211                 tip += ", ";
212                 tip += _("included in TOC");
213         }
214
215         return tip;
216 }
217
218
219 static string normalizeName(Buffer const & buffer,
220         OutputParams const & runparams, string const & name, string const & ext)
221 {
222         string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
223         if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
224                 return name;
225         if (!runparams.nice)
226                 return fname;
227
228         // FIXME UNICODE
229         return to_utf8(makeRelPath(from_utf8(fname),
230                                          from_utf8(buffer.masterBuffer()->filePath())));
231 }
232
233
234 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
235 {
236         // the sequence of the commands:
237         // 1. \bibliographystyle{style}
238         // 2. \addcontentsline{...} - if option bibtotoc set
239         // 3. \bibliography{database}
240         // and with bibtopic:
241         // 1. \bibliographystyle{style}
242         // 2. \begin{btSect}{database}
243         // 3. \btPrint{Cited|NotCited|All}
244         // 4. \end{btSect}
245
246         // Database(s)
247         // If we are processing the LaTeX file in a temp directory then
248         // copy the .bib databases to this temp directory, mangling their
249         // names in the process. Store this mangled name in the list of
250         // all databases.
251         // (We need to do all this because BibTeX *really*, *really*
252         // can't handle "files with spaces" and Windows users tend to
253         // use such filenames.)
254         // Otherwise, store the (maybe absolute) path to the original,
255         // unmangled database name.
256         vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
257         vector<docstring>::const_iterator it = bibfilelist.begin();
258         vector<docstring>::const_iterator en = bibfilelist.end();
259         odocstringstream dbs;
260         bool didone = false;
261
262         // determine the export format
263         string const tex_format = flavor2format(runparams.flavor);
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                         bool const success = in_file.copyTo(out_file);
281                         if (!success) {
282                                 lyxerr << "Failed to copy '" << in_file
283                                        << "' to '" << out_file << "'"
284                                        << endl;
285                         }
286                 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
287                         runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
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         if (style == "default")
331                 style = buffer().params().defaultBiblioStyle();
332
333         if (!style.empty() && !buffer().params().use_bibtopic) {
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         }
361
362         // Post this warning only once.
363         static bool warned_about_bst_spaces = false;
364         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
365                 warned_about_bst_spaces = true;
366                 Alert::warning(_("Export Warning!"),
367                                _("There are spaces in the path to your BibTeX style file.\n"
368                                               "BibTeX will be unable to find it."));
369         }
370
371         if (!db_out.empty() && buffer().params().use_bibtopic) {
372                 os << "\\begin{btSect}";
373                 if (!style.empty())
374                         os << "[" << style << "]";
375                 os << "{" << db_out << "}\n";
376                 docstring btprint = getParam("btprint");
377                 if (btprint.empty())
378                         // default
379                         btprint = from_ascii("btPrintCited");
380                 os << "\\" << btprint << "\n"
381                    << "\\end{btSect}\n";
382         }
383
384         // bibtotoc-Option
385         if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
386                 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
387                 if (buffer().params().pdfoptions().use_hyperref)
388                                 os << "\\phantomsection";
389                 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
390                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
391                 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
392                         os << "\\addcontentsline{toc}{section}{\\refname}";
393         }
394
395         if (!db_out.empty() && !buffer().params().use_bibtopic) {
396                 docstring btprint = getParam("btprint");
397                 if (btprint == "btPrintAll") {
398                         os << "\\nocite{*}\n";
399                 }
400                 os << "\\bibliography{" << db_out << "}\n";
401         }
402 }
403
404
405 support::FileNamePairList InsetBibtex::getBibFiles() const
406 {
407         FileName path(buffer().filePath());
408         support::PathChanger p(path);
409
410         // We need to store both the real FileName and the way it is entered
411         // (with full path, rel path or as a single file name).
412         // The latter is needed for biblatex's central bibfile macro.
413         support::FileNamePairList 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(make_pair(*it, 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 (isDigitASCII(ch)) {
559
560                                 // read integer value
561                                 do {
562                                         val += ch;
563                                         ifs.get(ch);
564                                 } while (ifs && isDigitASCII(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 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
673 {
674         parseBibTeXFiles();
675 }
676
677
678 void InsetBibtex::parseBibTeXFiles() const
679 {
680         // This bibtex parser is a first step to parse bibtex files
681         // more precisely.
682         //
683         // - it reads the whole bibtex entry and does a syntax check
684         //   (matching delimiters, missing commas,...
685         // - it recovers from errors starting with the next @-character
686         // - it reads @string definitions and replaces them in the
687         //   field values.
688         // - it accepts more characters in keys or value names than
689         //   bibtex does.
690         //
691         // Officially bibtex does only support ASCII, but in practice
692         // you can use the encoding of the main document as long as
693         // some elements like keys and names are pure ASCII. Therefore
694         // we convert the file from the buffer encoding.
695         // We don't restrict keys to ASCII in LyX, since our own
696         // InsetBibitem can generate non-ASCII keys, and nonstandard
697         // 8bit clean bibtex forks exist.
698
699         BiblioInfo keylist;
700
701         support::FileNamePairList const files = getBibFiles();
702         support::FileNamePairList::const_iterator it = files.begin();
703         support::FileNamePairList::const_iterator en = files.end();
704         for (; it != en; ++ it) {
705                 ifdocstream ifs(it->second.toFilesystemEncoding().c_str(),
706                         ios_base::in, buffer().params().encoding().iconvName());
707
708                 char_type ch;
709                 VarMap strings;
710
711                 while (ifs) {
712
713                         ifs.get(ch);
714                         if (!ifs)
715                                 break;
716
717                         if (ch != '@')
718                                 continue;
719
720                         docstring entryType;
721
722                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
723                                 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
724                                 continue;
725                         }
726
727                         if (!ifs) {
728                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
729                                 continue;
730                         }
731
732                         if (entryType == from_ascii("comment")) {
733                                 ifs.ignore(numeric_limits<int>::max(), '\n');
734                                 continue;
735                         }
736
737                         ifs.get(ch);
738                         if (!ifs) {
739                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
740                                 break;
741                         }
742
743                         if ((ch != '(') && (ch != '{')) {
744                                 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
745                                 ifs.putback(ch);
746                                 continue;
747                         }
748
749                         // process the entry
750                         if (entryType == from_ascii("string")) {
751
752                                 // read string and add it to the strings map
753                                 // (or replace it's old value)
754                                 docstring name;
755                                 docstring value;
756
757                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
758                                         lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
759                                         continue;
760                                 }
761
762                                 if (!ifs) {
763                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
764                                         continue;
765                                 }
766
767                                 // next char must be an equal sign
768                                 ifs.get(ch);
769                                 if (!ifs || ch != '=') {
770                                         lyxerr << "BibTeX Parser: No `=' after string name: " <<
771                                                         name << "." << std::endl;
772                                         continue;
773                                 }
774
775                                 if (!readValue(value, ifs, strings)) {
776                                         lyxerr << "BibTeX Parser: Unable to read value for string: " <<
777                                                         name << "." << std::endl;
778                                         continue;
779                                 }
780
781                                 strings[name] = value;
782
783                         } else if (entryType == from_ascii("preamble")) {
784
785                                 // preamble definitions are discarded.
786                                 // can they be of any use in lyx?
787                                 docstring value;
788
789                                 if (!readValue(value, ifs, strings)) {
790                                         lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
791                                         continue;
792                                 }
793
794                         } else {
795
796                                 // Citation entry. Try to read the key.
797                                 docstring key;
798
799                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
800                                         lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
801                                                         entryType << "." << std::endl;
802                                         continue;
803                                 }
804
805                                 if (!ifs) {
806                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
807                                         continue;
808                                 }
809
810                                 /////////////////////////////////////////////
811                                 // now we have a key, so we will add an entry
812                                 // (even if it's empty, as bibtex does)
813                                 //
814                                 // we now read the field = value pairs.
815                                 // all items must be separated by a comma. If
816                                 // it is missing the scanning of this entry is
817                                 // stopped and the next is searched.
818                                 docstring name;
819                                 docstring value;
820                                 docstring data;
821                                 BibTeXInfo keyvalmap(key, entryType);
822
823                                 bool readNext = removeWSAndComma(ifs);
824
825                                 while (ifs && readNext) {
826
827                                         // read field name
828                                         if (!readTypeOrKey(name, ifs, from_ascii("="),
829                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
830                                                 break;
831
832                                         // next char must be an equal sign
833                                         // FIXME Whitespace??
834                                         ifs.get(ch);
835                                         if (!ifs) {
836                                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
837                                                 break;
838                                         }
839                                         if (ch != '=') {
840                                                 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
841                                                                 name << ", for key: " << key << "." << std::endl;
842                                                 ifs.putback(ch);
843                                                 break;
844                                         }
845
846                                         // read field value
847                                         if (!readValue(value, ifs, strings)) {
848                                                 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
849                                                                 name << ", for key: " << key << "." << std::endl;
850                                                 break;
851                                         }
852
853                                         keyvalmap[name] = value;
854                                         data += "\n\n" + value;
855                                         keylist.addFieldName(name);
856                                         readNext = removeWSAndComma(ifs);
857                                 }
858
859                                 // add the new entry
860                                 keylist.addEntryType(entryType);
861                                 keyvalmap.setAllData(data);
862                                 keylist[key] = keyvalmap;
863                         } //< else (citation entry)
864                 } //< searching '@'
865         } //< for loop over files
866
867         buffer().addBiblioInfo(keylist);
868 }
869
870
871 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
872 {
873         string texfile = changeExtension(to_utf8(filename), "bib");
874         // note that, if the filename can be found directly from the path,
875         // findtexfile will just return a FileName object for that path.
876         FileName file(findtexfile(texfile, "bib"));
877         if (file.empty())
878                 file = FileName(makeAbsPath(texfile, buf.filePath()));
879         return file;
880 }
881
882
883 bool InsetBibtex::addDatabase(docstring const & db)
884 {
885         docstring bibfiles = getParam("bibfiles");
886         if (tokenPos(bibfiles, ',', db) != -1)
887                 return false;
888         if (!bibfiles.empty())
889                 bibfiles += ',';
890         setParam("bibfiles", bibfiles + db);
891         return true;
892 }
893
894
895 bool InsetBibtex::delDatabase(docstring const & db)
896 {
897         docstring bibfiles = getParam("bibfiles");
898         if (contains(bibfiles, db)) {
899                 int const n = tokenPos(bibfiles, ',', db);
900                 docstring bd = db;
901                 if (n > 0) {
902                         // this is not the first database
903                         docstring tmp = ',' + bd;
904                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
905                 } else if (n == 0)
906                         // this is the first (or only) database
907                         setParam("bibfiles", split(bibfiles, bd, ','));
908                 else
909                         return false;
910         }
911         return true;
912 }
913
914
915 void InsetBibtex::validate(LaTeXFeatures & features) const
916 {
917         if (features.bufferParams().use_bibtopic)
918                 features.require("bibtopic");
919         // FIXME XHTML
920         // It'd be better to be able to get this from an InsetLayout, but at present
921         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
922         if (features.runparams().flavor == OutputParams::HTML)
923                 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
924                         "span.bibtexlabel:before{ content: \"[\"; }\n"
925                         "span.bibtexlabel:after{ content: \"] \"; }");
926 }
927
928
929 int InsetBibtex::plaintext(odocstringstream & os,
930        OutputParams const & op, size_t max_length) const
931 {
932         docstring const reflabel = buffer().B_("References");
933
934         // We could output more information here, e.g., what databases are included
935         // and information about options. But I don't necessarily see any reason to
936         // do this right now.
937         if (op.for_tooltip || op.for_toc || op.for_search) {
938                 os << '[' << reflabel << ']' << '\n';
939                 return PLAINTEXT_NEWLINE;
940         }
941
942         BiblioInfo bibinfo = buffer().masterBibInfo();
943         bibinfo.makeCitationLabels(buffer());
944         vector<docstring> const & cites = bibinfo.citedEntries();
945
946         size_t start_size = os.str().size();
947         docstring refoutput;
948         refoutput += reflabel + "\n\n";
949
950         // Tell BiblioInfo our purpose
951         CiteItem ci;
952         ci.context = CiteItem::Export;
953
954         // Now we loop over the entries
955         vector<docstring>::const_iterator vit = cites.begin();
956         vector<docstring>::const_iterator const ven = cites.end();
957         for (; vit != ven; ++vit) {
958                 if (start_size + refoutput.size() >= max_length)
959                         break;
960                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
961                 if (biit == bibinfo.end())
962                         continue;
963                 BibTeXInfo const & entry = biit->second;
964                 refoutput += "[" + entry.label() + "] ";
965                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
966                 // which will give us all the cross-referenced info. But for every
967                 // entry, so there's a lot of repitition. This should be fixed.
968                 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
969         }
970         os << refoutput;
971         return refoutput.size();
972 }
973
974
975 // FIXME
976 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
977 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
978 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
979 {
980         BiblioInfo const & bibinfo = buffer().masterBibInfo();
981         bool const all_entries = getParam("btprint") == "btPrintAll";
982         vector<docstring> const & cites = 
983             all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
984
985         docstring const reflabel = buffer().B_("References");
986
987         // tell BiblioInfo our purpose
988         CiteItem ci;
989         ci.context = CiteItem::Export;
990         ci.richtext = true;
991         ci.max_key_size = UINT_MAX;
992
993         xs << html::StartTag("h2", "class='bibtex'")
994                 << reflabel
995                 << html::EndTag("h2")
996                 << html::StartTag("div", "class='bibtex'");
997
998         // Now we loop over the entries
999         vector<docstring>::const_iterator vit = cites.begin();
1000         vector<docstring>::const_iterator const ven = cites.end();
1001         for (; vit != ven; ++vit) {
1002                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
1003                 if (biit == bibinfo.end())
1004                         continue;
1005
1006                 BibTeXInfo const & entry = biit->second;
1007                 string const attr = "class='bibtexentry' id='LyXCite-" 
1008                     + to_utf8(html::cleanAttr(entry.key())) + "'";
1009                 xs << html::StartTag("div", attr);
1010                 
1011                 // don't print labels if we're outputting all entries
1012                 if (!all_entries) {
1013                         xs << html::StartTag("span", "class='bibtexlabel'")
1014                                 << entry.label()
1015                                 << html::EndTag("span");
1016                 }
1017                 
1018                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1019                 // which will give us all the cross-referenced info. But for every
1020                 // entry, so there's a lot of repitition. This should be fixed.
1021                 xs << html::StartTag("span", "class='bibtexinfo'")
1022                    << XHTMLStream::ESCAPE_AND
1023                    << bibinfo.getInfo(entry.key(), buffer(), ci)
1024                    << html::EndTag("span")
1025                    << html::EndTag("div")
1026                    << html::CR();
1027         }
1028         xs << html::EndTag("div");
1029         return docstring();
1030 }
1031
1032
1033 void InsetBibtex::write(ostream & os) const
1034 {
1035         params().Write(os, &buffer());
1036 }
1037
1038
1039 string InsetBibtex::contextMenuName() const
1040 {
1041         return "context-bibtex";
1042 }
1043
1044
1045 } // namespace lyx