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