]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
Wrap rotated cells with linebreaks in varwidth
[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                 while (ifs && !isSpace(ch) &&
463                        delimChars.find(ch) == docstring::npos &&
464                        illegalChars.find(ch) == docstring::npos)
465                 {
466                         if (chCase == makeLowerCase)
467                                 val += lowercase(ch);
468                         else
469                                 val += ch;
470                         ifs.get(ch);
471                 }
472
473                 if (illegalChars.find(ch) != docstring::npos) {
474                         ifs.putback(ch);
475                         return false;
476                 }
477
478                 // skip whitespace
479                 while (ifs && isSpace(ch)) {
480                         ifs.get(ch);
481                 }
482
483                 if (ifs) {
484                         ifs.putback(ch);
485                 }
486
487                 return val.length() > 0;
488         }
489
490         /// read subsequent bibtex values that are delimited with a #-character.
491         /// Concatenate all parts and replace names with the associated string in
492         /// the variable strings.
493         /// @return true if reading was successfull (all single parts were delimited
494         /// correctly)
495         bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
496
497                 char_type ch;
498
499                 val.clear();
500
501                 if (!ifs)
502                         return false;
503
504                 do {
505                         // skip whitespace
506                         do {
507                                 ifs.get(ch);
508                         } while (ifs && isSpace(ch));
509
510                         if (!ifs)
511                                 return false;
512
513                         // check for field type
514                         if (isDigitASCII(ch)) {
515
516                                 // read integer value
517                                 do {
518                                         val += ch;
519                                         ifs.get(ch);
520                                 } while (ifs && isDigitASCII(ch));
521
522                                 if (!ifs)
523                                         return false;
524
525                         } else if (ch == '"' || ch == '{') {
526                                 // set end delimiter
527                                 char_type delim = ch == '"' ? '"': '}';
528
529                                 // Skip whitespace
530                                 do {
531                                         ifs.get(ch);
532                                 } while (ifs && isSpace(ch));
533
534                                 if (!ifs)
535                                         return false;
536
537                                 // We now have the first non-whitespace character
538                                 // We'll collapse adjacent whitespace.
539                                 bool lastWasWhiteSpace = false;
540
541                                 // inside this delimited text braces must match.
542                                 // Thus we can have a closing delimiter only
543                                 // when nestLevel == 0
544                                 int nestLevel = 0;
545
546                                 while (ifs && (nestLevel > 0 || ch != delim)) {
547                                         if (isSpace(ch)) {
548                                                 lastWasWhiteSpace = true;
549                                                 ifs.get(ch);
550                                                 continue;
551                                         }
552                                         // We output the space only after we stop getting
553                                         // whitespace so as not to output any whitespace
554                                         // at the end of the value.
555                                         if (lastWasWhiteSpace) {
556                                                 lastWasWhiteSpace = false;
557                                                 val += ' ';
558                                         }
559
560                                         val += ch;
561
562                                         // update nesting level
563                                         switch (ch) {
564                                                 case '{':
565                                                         ++nestLevel;
566                                                         break;
567                                                 case '}':
568                                                         --nestLevel;
569                                                         if (nestLevel < 0)
570                                                                 return false;
571                                                         break;
572                                         }
573
574                                         if (ifs)
575                                                 ifs.get(ch);
576                                 }
577
578                                 if (!ifs)
579                                         return false;
580
581                                 // FIXME Why is this here?
582                                 ifs.get(ch);
583
584                                 if (!ifs)
585                                         return false;
586
587                         } else {
588
589                                 // reading a string name
590                                 docstring strName;
591
592                                 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
593                                         strName += lowercase(ch);
594                                         ifs.get(ch);
595                                 }
596
597                                 if (!ifs)
598                                         return false;
599
600                                 // replace the string with its assigned value or
601                                 // discard it if it's not assigned
602                                 if (strName.length()) {
603                                         VarMap::const_iterator pos = strings.find(strName);
604                                         if (pos != strings.end()) {
605                                                 val += pos->second;
606                                         }
607                                 }
608                         }
609
610                         // skip WS
611                         while (ifs && isSpace(ch)) {
612                                 ifs.get(ch);
613                         }
614
615                         if (!ifs)
616                                 return false;
617
618                         // continue reading next value on concatenate with '#'
619                 } while (ch == '#');
620
621                 ifs.putback(ch);
622
623                 return true;
624         }
625 } // namespace
626
627
628 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
629 {
630         parseBibTeXFiles(checkedFiles);
631 }
632
633
634 void InsetBibtex::parseBibTeXFiles(FileNameList & checkedFiles) const
635 {
636         // This bibtex parser is a first step to parse bibtex files
637         // more precisely.
638         //
639         // - it reads the whole bibtex entry and does a syntax check
640         //   (matching delimiters, missing commas,...
641         // - it recovers from errors starting with the next @-character
642         // - it reads @string definitions and replaces them in the
643         //   field values.
644         // - it accepts more characters in keys or value names than
645         //   bibtex does.
646         //
647         // Officially bibtex does only support ASCII, but in practice
648         // you can use the encoding of the main document as long as
649         // some elements like keys and names are pure ASCII. Therefore
650         // we convert the file from the buffer encoding.
651         // We don't restrict keys to ASCII in LyX, since our own
652         // InsetBibitem can generate non-ASCII keys, and nonstandard
653         // 8bit clean bibtex forks exist.
654
655         BiblioInfo keylist;
656
657         FileNamePairList const files = getBibFiles();
658         FileNamePairList::const_iterator it = files.begin();
659         FileNamePairList::const_iterator en = files.end();
660         for (; it != en; ++ it) {
661                 FileName const bibfile = it->second;
662                 if (find(checkedFiles.begin(), checkedFiles.end(), bibfile) != checkedFiles.end())
663                         // already checked this one. Skip.
664                         continue;
665                 else
666                         // record that we check this.
667                         checkedFiles.push_back(bibfile);
668                 ifdocstream ifs(bibfile.toFilesystemEncoding().c_str(),
669                         ios_base::in, buffer().masterParams().encoding().iconvName());
670
671                 char_type ch;
672                 VarMap strings;
673
674                 while (ifs) {
675
676                         ifs.get(ch);
677                         if (!ifs)
678                                 break;
679
680                         if (ch != '@')
681                                 continue;
682
683                         docstring entryType;
684
685                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
686                                 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
687                                 continue;
688                         }
689
690                         if (!ifs) {
691                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
692                                 continue;
693                         }
694
695                         if (entryType == from_ascii("comment")) {
696                                 ifs.ignore(numeric_limits<int>::max(), '\n');
697                                 continue;
698                         }
699
700                         ifs.get(ch);
701                         if (!ifs) {
702                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
703                                 break;
704                         }
705
706                         if ((ch != '(') && (ch != '{')) {
707                                 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
708                                 ifs.putback(ch);
709                                 continue;
710                         }
711
712                         // process the entry
713                         if (entryType == from_ascii("string")) {
714
715                                 // read string and add it to the strings map
716                                 // (or replace it's old value)
717                                 docstring name;
718                                 docstring value;
719
720                                 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
721                                         lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
722                                         continue;
723                                 }
724
725                                 if (!ifs) {
726                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
727                                         continue;
728                                 }
729
730                                 // next char must be an equal sign
731                                 ifs.get(ch);
732                                 if (!ifs || ch != '=') {
733                                         lyxerr << "BibTeX Parser: No `=' after string name: " <<
734                                                         name << "." << std::endl;
735                                         continue;
736                                 }
737
738                                 if (!readValue(value, ifs, strings)) {
739                                         lyxerr << "BibTeX Parser: Unable to read value for string: " <<
740                                                         name << "." << std::endl;
741                                         continue;
742                                 }
743
744                                 strings[name] = value;
745
746                         } else if (entryType == from_ascii("preamble")) {
747
748                                 // preamble definitions are discarded.
749                                 // can they be of any use in lyx?
750                                 docstring value;
751
752                                 if (!readValue(value, ifs, strings)) {
753                                         lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
754                                         continue;
755                                 }
756
757                         } else {
758
759                                 // Citation entry. Try to read the key.
760                                 docstring key;
761
762                                 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
763                                         lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
764                                                         entryType << "." << std::endl;
765                                         continue;
766                                 }
767
768                                 if (!ifs) {
769                                         lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
770                                         continue;
771                                 }
772
773                                 /////////////////////////////////////////////
774                                 // now we have a key, so we will add an entry
775                                 // (even if it's empty, as bibtex does)
776                                 //
777                                 // we now read the field = value pairs.
778                                 // all items must be separated by a comma. If
779                                 // it is missing the scanning of this entry is
780                                 // stopped and the next is searched.
781                                 docstring name;
782                                 docstring value;
783                                 docstring data;
784                                 BibTeXInfo keyvalmap(key, entryType);
785
786                                 bool readNext = removeWSAndComma(ifs);
787
788                                 while (ifs && readNext) {
789
790                                         // read field name
791                                         if (!readTypeOrKey(name, ifs, from_ascii("="),
792                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
793                                                 break;
794
795                                         // next char must be an equal sign
796                                         // FIXME Whitespace??
797                                         ifs.get(ch);
798                                         if (!ifs) {
799                                                 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
800                                                 break;
801                                         }
802                                         if (ch != '=') {
803                                                 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
804                                                                 name << ", for key: " << key << "." << std::endl;
805                                                 ifs.putback(ch);
806                                                 break;
807                                         }
808
809                                         // read field value
810                                         if (!readValue(value, ifs, strings)) {
811                                                 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
812                                                                 name << ", for key: " << key << "." << std::endl;
813                                                 break;
814                                         }
815
816                                         keyvalmap[name] = value;
817                                         data += "\n\n" + value;
818                                         keylist.addFieldName(name);
819                                         readNext = removeWSAndComma(ifs);
820                                 }
821
822                                 // add the new entry
823                                 keylist.addEntryType(entryType);
824                                 keyvalmap.setAllData(data);
825                                 keylist[key] = keyvalmap;
826                         } //< else (citation entry)
827                 } //< searching '@'
828         } //< for loop over files
829
830         buffer().addBiblioInfo(keylist);
831 }
832
833
834 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
835 {
836         string texfile = changeExtension(to_utf8(filename), "bib");
837         // note that, if the filename can be found directly from the path,
838         // findtexfile will just return a FileName object for that path.
839         FileName file(findtexfile(texfile, "bib"));
840         if (file.empty())
841                 file = FileName(makeAbsPath(texfile, buf.filePath()));
842         return file;
843 }
844
845
846 bool InsetBibtex::addDatabase(docstring const & db)
847 {
848         docstring bibfiles = getParam("bibfiles");
849         if (tokenPos(bibfiles, ',', db) != -1)
850                 return false;
851         if (!bibfiles.empty())
852                 bibfiles += ',';
853         setParam("bibfiles", bibfiles + db);
854         return true;
855 }
856
857
858 bool InsetBibtex::delDatabase(docstring const & db)
859 {
860         docstring bibfiles = getParam("bibfiles");
861         if (contains(bibfiles, db)) {
862                 int const n = tokenPos(bibfiles, ',', db);
863                 docstring bd = db;
864                 if (n > 0) {
865                         // this is not the first database
866                         docstring tmp = ',' + bd;
867                         setParam("bibfiles", subst(bibfiles, tmp, docstring()));
868                 } else if (n == 0)
869                         // this is the first (or only) database
870                         setParam("bibfiles", split(bibfiles, bd, ','));
871                 else
872                         return false;
873         }
874         return true;
875 }
876
877
878 void InsetBibtex::validate(LaTeXFeatures & features) const
879 {
880         BufferParams const & mparams = features.buffer().masterParams();
881         if (mparams.useBibtopic())
882                 features.require("bibtopic");
883         else if (!mparams.useBiblatex() && mparams.multibib == "child")
884                 features.require("chapterbib");
885         // FIXME XHTML
886         // It'd be better to be able to get this from an InsetLayout, but at present
887         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
888         if (features.runparams().flavor == OutputParams::HTML)
889                 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
890                         "span.bibtexlabel:before{ content: \"[\"; }\n"
891                         "span.bibtexlabel:after{ content: \"] \"; }");
892 }
893
894
895 void InsetBibtex::updateBuffer(ParIterator const &, UpdateType) {
896         buffer().registerBibfiles(getBibFiles());
897 }
898
899
900 int InsetBibtex::plaintext(odocstringstream & os,
901        OutputParams const & op, size_t max_length) const
902 {
903         docstring const reflabel = buffer().B_("References");
904
905         // We could output more information here, e.g., what databases are included
906         // and information about options. But I don't necessarily see any reason to
907         // do this right now.
908         if (op.for_tooltip || op.for_toc || op.for_search) {
909                 os << '[' << reflabel << ']' << '\n';
910                 return PLAINTEXT_NEWLINE;
911         }
912
913         BiblioInfo bibinfo = buffer().masterBibInfo();
914         bibinfo.makeCitationLabels(buffer());
915         vector<docstring> const & cites = bibinfo.citedEntries();
916
917         size_t start_size = os.str().size();
918         docstring refoutput;
919         refoutput += reflabel + "\n\n";
920
921         // Tell BiblioInfo our purpose
922         CiteItem ci;
923         ci.context = CiteItem::Export;
924
925         // Now we loop over the entries
926         vector<docstring>::const_iterator vit = cites.begin();
927         vector<docstring>::const_iterator const ven = cites.end();
928         for (; vit != ven; ++vit) {
929                 if (start_size + refoutput.size() >= max_length)
930                         break;
931                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
932                 if (biit == bibinfo.end())
933                         continue;
934                 BibTeXInfo const & entry = biit->second;
935                 refoutput += "[" + entry.label() + "] ";
936                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
937                 // which will give us all the cross-referenced info. But for every
938                 // entry, so there's a lot of repitition. This should be fixed.
939                 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
940         }
941         os << refoutput;
942         return refoutput.size();
943 }
944
945
946 // FIXME
947 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
948 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
949 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
950 {
951         BiblioInfo const & bibinfo = buffer().masterBibInfo();
952         bool const all_entries = getParam("btprint") == "btPrintAll";
953         vector<docstring> const & cites =
954             all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
955
956         docstring const reflabel = buffer().B_("References");
957
958         // tell BiblioInfo our purpose
959         CiteItem ci;
960         ci.context = CiteItem::Export;
961         ci.richtext = true;
962         ci.max_key_size = UINT_MAX;
963
964         xs << html::StartTag("h2", "class='bibtex'")
965                 << reflabel
966                 << html::EndTag("h2")
967                 << html::StartTag("div", "class='bibtex'");
968
969         // Now we loop over the entries
970         vector<docstring>::const_iterator vit = cites.begin();
971         vector<docstring>::const_iterator const ven = cites.end();
972         for (; vit != ven; ++vit) {
973                 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
974                 if (biit == bibinfo.end())
975                         continue;
976
977                 BibTeXInfo const & entry = biit->second;
978                 string const attr = "class='bibtexentry' id='LyXCite-"
979                     + to_utf8(html::cleanAttr(entry.key())) + "'";
980                 xs << html::StartTag("div", attr);
981
982                 // don't print labels if we're outputting all entries
983                 if (!all_entries) {
984                         xs << html::StartTag("span", "class='bibtexlabel'")
985                                 << entry.label()
986                                 << html::EndTag("span");
987                 }
988
989                 // FIXME Right now, we are calling BibInfo::getInfo on the key,
990                 // which will give us all the cross-referenced info. But for every
991                 // entry, so there's a lot of repitition. This should be fixed.
992                 xs << html::StartTag("span", "class='bibtexinfo'")
993                    << XHTMLStream::ESCAPE_AND
994                    << bibinfo.getInfo(entry.key(), buffer(), ci)
995                    << html::EndTag("span")
996                    << html::EndTag("div")
997                    << html::CR();
998         }
999         xs << html::EndTag("div");
1000         return docstring();
1001 }
1002
1003
1004 void InsetBibtex::write(ostream & os) const
1005 {
1006         params().Write(os, &buffer());
1007 }
1008
1009
1010 string InsetBibtex::contextMenuName() const
1011 {
1012         return "context-bibtex";
1013 }
1014
1015
1016 } // namespace lyx