2 * \file InsetBibtex.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Richard Heck (BibTeX parser improvements)
8 * \author Jürgen Spitzmüller
10 * Full author contact details are available in file CREDITS.
15 #include "InsetBibtex.h"
17 #include "BiblioInfo.h"
19 #include "BufferParams.h"
20 #include "CiteEnginesList.h"
22 #include "DispatchResult.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"
35 #include "frontends/alert.h"
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"
52 using namespace lyx::support;
56 namespace Alert = frontend::Alert;
57 namespace os = support::os;
60 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
61 : InsetCommand(buf, p)
63 buffer().invalidateBibfileCache();
64 buffer().removeBiblioTempFiles();
68 InsetBibtex::~InsetBibtex()
70 if (isBufferLoaded()) {
71 buffer().invalidateBibfileCache();
72 buffer().removeBiblioTempFiles();
77 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
79 static ParamInfo param_info_;
80 if (param_info_.empty()) {
81 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
82 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
83 param_info_.add("options", ParamInfo::LYX_INTERNAL);
84 param_info_.add("biblatexopts", ParamInfo::LATEX_OPTIONAL);
90 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
92 switch (cmd.action()) {
98 case LFUN_INSET_MODIFY: {
99 InsetCommandParams p(BIBTEX_CODE);
101 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
102 cur.noScreenUpdate();
105 } catch (ExceptionMessage const & message) {
106 if (message.type_ == WarningException) {
107 Alert::warning(message.title_, message.details_);
108 cur.noScreenUpdate();
116 buffer().invalidateBibfileCache();
117 buffer().removeBiblioTempFiles();
118 cur.forceBufferUpdate();
123 InsetCommand::doDispatch(cur, cmd);
129 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
130 FuncStatus & flag) const
132 switch (cmd.action()) {
133 case LFUN_INSET_EDIT:
134 flag.setEnabled(true);
138 return InsetCommand::getStatus(cur, cmd, flag);
143 void InsetBibtex::editDatabases() const
145 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
147 if (bibfilelist.empty())
150 int nr_databases = bibfilelist.size();
151 if (nr_databases > 1) {
152 docstring const engine = usingBiblatex() ? _("Biblatex") : _("BibTeX");
153 docstring message = bformat(_("The %1$s[[BibTeX/Biblatex]] inset includes %2$s databases.\n"
154 "If you proceed, all of them will be opened."),
155 engine, convert<docstring>(nr_databases));
156 int const ret = Alert::prompt(_("Open Databases?"),
157 message, 0, 1, _("&Cancel"), _("&Proceed"));
163 vector<docstring>::const_iterator it = bibfilelist.begin();
164 vector<docstring>::const_iterator en = bibfilelist.end();
165 for (; it != en; ++it) {
166 FileName const bibfile = getBibTeXPath(*it, buffer());
167 formats.edit(buffer(), bibfile,
168 formats.getFormatFromFile(bibfile));
173 bool InsetBibtex::usingBiblatex() const
175 return buffer().masterParams().useBiblatex();
179 docstring InsetBibtex::screenLabel() const
181 return usingBiblatex() ? _("Biblatex Generated Bibliography")
182 : _("BibTeX Generated Bibliography");
186 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
188 docstring tip = _("Databases:");
189 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
192 if (bibfilelist.empty())
193 tip += "<li>" + _("none") + "</li>";
195 for (docstring const & bibfile : bibfilelist)
196 tip += "<li>" + bibfile + "</li>";
201 docstring style = getParam("options"); // maybe empty! and with bibtotoc
202 docstring bibtotoc = from_ascii("bibtotoc");
203 if (prefixIs(style, bibtotoc)) {
205 if (contains(style, char_type(',')))
206 style = split(style, bibtotoc, char_type(','));
209 docstring const btprint = getParam("btprint");
210 if (!usingBiblatex()) {
211 tip += _("Style File:");
212 tip += "<ul><li>" + (style.empty() ? _("none") : style) + "</li></ul>";
214 tip += _("Lists:") + " ";
215 if (btprint == "btPrintAll")
216 tip += _("all references");
217 else if (btprint == "btPrintNotCited")
218 tip += _("all uncited references");
220 tip += _("all cited references");
223 tip += _("included in TOC");
225 if (!buffer().parent()
226 && buffer().params().multibib == "child") {
228 tip += _("Note: This bibliography is not output, since bibliographies in the master file "
229 "are not allowed with the setting 'Multiple bibliographies per child document'");
232 tip += _("Lists:") + " ";
233 if (btprint == "bibbysection")
234 tip += _("all reference units");
235 else if (btprint == "btPrintAll")
236 tip += _("all references");
238 tip += _("all cited references");
241 tip += _("included in TOC");
243 if (!getParam("biblatexopts").empty()) {
246 tip += _("Options: ") + getParam("biblatexopts");
254 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
256 // The sequence of the commands:
257 // With normal BibTeX:
258 // 1. \bibliographystyle{style}
259 // 2. \addcontentsline{...} - if option bibtotoc set
260 // 3. \bibliography{database}
262 // 1. \bibliographystyle{style}
263 // 2. \begin{btSect}{database}
264 // 3. \btPrint{Cited|NotCited|All}
267 // \printbibliography[biblatexopts]
269 // \bibbysection[biblatexopts] - if btprint is "bibbysection"
271 // chapterbib does not allow bibliographies in the master
272 if (!usingBiblatex() && !runparams.is_child
273 && buffer().params().multibib == "child")
276 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
278 if (prefixIs(style, "bibtotoc")) {
279 bibtotoc = "bibtotoc";
280 if (contains(style, ','))
281 style = split(style, bibtotoc, ',');
284 if (usingBiblatex()) {
286 string opts = to_utf8(getParam("biblatexopts"));
288 if (!bibtotoc.empty())
289 opts = opts.empty() ? "heading=bibintoc" : "heading=bibintoc," + opts;
290 // The bibliography command
291 docstring btprint = getParam("btprint");
292 if (btprint == "btPrintAll")
293 os << "\\nocite{*}\n";
294 if (btprint == "bibbysection" && !buffer().masterParams().multibib.empty())
295 os << "\\bibbysection";
297 os << "\\printbibliography";
299 os << "[" << opts << "]";
301 } else {// using BibTeX
303 vector<docstring> const db_out =
304 buffer().prepareBibFilePaths(runparams, getBibFiles(), false);
306 if (style == "default")
307 style = buffer().masterParams().defaultBiblioStyle();
308 if (!style.empty() && !buffer().masterParams().useBibtopic()) {
309 string base = buffer().masterBuffer()->prepareFileNameForLaTeX(style, ".bst", runparams.nice);
310 FileName const try_in_file =
311 makeAbsPath(base + ".bst", buffer().filePath());
312 bool const not_from_texmf = try_in_file.isReadableFile();
313 // If this style does not come from texmf and we are not
314 // exporting to .tex copy it to the tmp directory.
315 // This prevents problems with spaces and 8bit characters
317 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
319 // use new style name
320 DocFileName const in_file = DocFileName(try_in_file);
321 base = removeExtension(in_file.mangledFileName());
322 FileName const out_file = makeAbsPath(base + ".bst",
323 buffer().masterBuffer()->temppath());
324 bool const success = in_file.copyTo(out_file);
326 LYXERR0("Failed to copy '" << in_file
327 << "' to '" << out_file << "'");
331 os << "\\bibliographystyle{"
332 << from_utf8(latex_path(buffer().prepareFileNameForLaTeX(base, ".bst", runparams.nice)))
335 // Warn about spaces in bst path. Warn only once.
336 static bool warned_about_bst_spaces = false;
337 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
338 warned_about_bst_spaces = true;
339 Alert::warning(_("Export Warning!"),
340 _("There are spaces in the path to your BibTeX style file.\n"
341 "BibTeX will be unable to find it."));
343 // Handle the bibtopic case
344 if (!db_out.empty() && buffer().masterParams().useBibtopic()) {
345 os << "\\begin{btSect}";
347 os << "[" << style << "]";
348 os << "{" << getStringFromVector(db_out) << "}\n";
349 docstring btprint = getParam("btprint");
352 btprint = from_ascii("btPrintCited");
353 os << "\\" << btprint << "\n"
354 << "\\end{btSect}\n";
357 if (!bibtotoc.empty() && !buffer().masterParams().useBibtopic()) {
358 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
359 if (buffer().masterParams().pdfoptions().use_hyperref)
360 os << "\\phantomsection";
361 if (buffer().masterParams().documentClass().hasLaTeXLayout("chapter"))
362 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
363 else if (buffer().masterParams().documentClass().hasLaTeXLayout("section"))
364 os << "\\addcontentsline{toc}{section}{\\refname}";
366 // The bibliography command
367 if (!db_out.empty() && !buffer().masterParams().useBibtopic()) {
368 docstring btprint = getParam("btprint");
369 if (btprint == "btPrintAll") {
370 os << "\\nocite{*}\n";
372 os << "\\bibliography{" << getStringFromVector(db_out) << "}\n";
378 support::FileNamePairList InsetBibtex::getBibFiles() const
380 FileName path(buffer().filePath());
381 support::PathChanger p(path);
383 // We need to store both the real FileName and the way it is entered
384 // (with full path, rel path or as a single file name).
385 // The latter is needed for biblatex's central bibfile macro.
386 support::FileNamePairList vec;
388 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
389 vector<docstring>::const_iterator it = bibfilelist.begin();
390 vector<docstring>::const_iterator en = bibfilelist.end();
391 for (; it != en; ++it) {
392 FileName const file = getBibTeXPath(*it, buffer());
395 vec.push_back(make_pair(*it, file));
397 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
406 // methods for parsing bibtex files
408 typedef map<docstring, docstring> VarMap;
410 /// remove whitespace characters, optionally a single comma,
411 /// and further whitespace characters from the stream.
412 /// @return true if a comma was found, false otherwise
414 bool removeWSAndComma(ifdocstream & ifs) {
423 } while (ifs && isSpace(ch));
436 } while (ifs && isSpace(ch));
451 /// remove whitespace characters, read characer sequence
452 /// not containing whitespace characters or characters in
453 /// delimChars, and remove further whitespace characters.
455 /// @return true if a string of length > 0 could be read.
457 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
458 docstring const & delimChars, docstring const & illegalChars,
471 } while (ifs && isSpace(ch));
477 bool legalChar = true;
478 while (ifs && !isSpace(ch) &&
479 delimChars.find(ch) == docstring::npos &&
480 (legalChar = (illegalChars.find(ch) == docstring::npos))
483 if (chCase == makeLowerCase)
484 val += lowercase(ch);
496 while (ifs && isSpace(ch)) {
504 return val.length() > 0;
507 /// read subsequent bibtex values that are delimited with a #-character.
508 /// Concatenate all parts and replace names with the associated string in
509 /// the variable strings.
510 /// @return true if reading was successfull (all single parts were delimited
512 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
525 } while (ifs && isSpace(ch));
530 // check for field type
531 if (isDigitASCII(ch)) {
533 // read integer value
537 } while (ifs && isDigitASCII(ch));
542 } else if (ch == '"' || ch == '{') {
544 char_type delim = ch == '"' ? '"': '}';
549 } while (ifs && isSpace(ch));
554 // We now have the first non-whitespace character
555 // We'll collapse adjacent whitespace.
556 bool lastWasWhiteSpace = false;
558 // inside this delimited text braces must match.
559 // Thus we can have a closing delimiter only
560 // when nestLevel == 0
563 while (ifs && (nestLevel > 0 || ch != delim)) {
565 lastWasWhiteSpace = true;
569 // We output the space only after we stop getting
570 // whitespace so as not to output any whitespace
571 // at the end of the value.
572 if (lastWasWhiteSpace) {
573 lastWasWhiteSpace = false;
579 // update nesting level
598 // FIXME Why is this here?
606 // reading a string name
609 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
610 strName += lowercase(ch);
617 // replace the string with its assigned value or
618 // discard it if it's not assigned
619 if (strName.length()) {
620 VarMap::const_iterator pos = strings.find(strName);
621 if (pos != strings.end()) {
628 while (ifs && isSpace(ch)) {
635 // continue reading next value on concatenate with '#'
645 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
651 void InsetBibtex::parseBibTeXFiles() const
653 // This bibtex parser is a first step to parse bibtex files
656 // - it reads the whole bibtex entry and does a syntax check
657 // (matching delimiters, missing commas,...
658 // - it recovers from errors starting with the next @-character
659 // - it reads @string definitions and replaces them in the
661 // - it accepts more characters in keys or value names than
664 // Officially bibtex does only support ASCII, but in practice
665 // you can use the encoding of the main document as long as
666 // some elements like keys and names are pure ASCII. Therefore
667 // we convert the file from the buffer encoding.
668 // We don't restrict keys to ASCII in LyX, since our own
669 // InsetBibitem can generate non-ASCII keys, and nonstandard
670 // 8bit clean bibtex forks exist.
674 support::FileNamePairList const files = getBibFiles();
675 support::FileNamePairList::const_iterator it = files.begin();
676 support::FileNamePairList::const_iterator en = files.end();
677 for (; it != en; ++ it) {
678 ifdocstream ifs(it->second.toFilesystemEncoding().c_str(),
679 ios_base::in, buffer().masterParams().encoding().iconvName());
695 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
696 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
701 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
705 if (entryType == from_ascii("comment")) {
706 ifs.ignore(numeric_limits<int>::max(), '\n');
712 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
716 if ((ch != '(') && (ch != '{')) {
717 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
723 if (entryType == from_ascii("string")) {
725 // read string and add it to the strings map
726 // (or replace it's old value)
730 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
731 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
736 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
740 // next char must be an equal sign
742 if (!ifs || ch != '=') {
743 lyxerr << "BibTeX Parser: No `=' after string name: " <<
744 name << "." << std::endl;
748 if (!readValue(value, ifs, strings)) {
749 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
750 name << "." << std::endl;
754 strings[name] = value;
756 } else if (entryType == from_ascii("preamble")) {
758 // preamble definitions are discarded.
759 // can they be of any use in lyx?
762 if (!readValue(value, ifs, strings)) {
763 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
769 // Citation entry. Try to read the key.
772 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
773 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
774 entryType << "." << std::endl;
779 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
783 /////////////////////////////////////////////
784 // now we have a key, so we will add an entry
785 // (even if it's empty, as bibtex does)
787 // we now read the field = value pairs.
788 // all items must be separated by a comma. If
789 // it is missing the scanning of this entry is
790 // stopped and the next is searched.
794 BibTeXInfo keyvalmap(key, entryType);
796 bool readNext = removeWSAndComma(ifs);
798 while (ifs && readNext) {
801 if (!readTypeOrKey(name, ifs, from_ascii("="),
802 from_ascii("{}(),"), makeLowerCase) || !ifs)
805 // next char must be an equal sign
806 // FIXME Whitespace??
809 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
813 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
814 name << ", for key: " << key << "." << std::endl;
820 if (!readValue(value, ifs, strings)) {
821 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
822 name << ", for key: " << key << "." << std::endl;
826 keyvalmap[name] = value;
827 data += "\n\n" + value;
828 keylist.addFieldName(name);
829 readNext = removeWSAndComma(ifs);
833 keylist.addEntryType(entryType);
834 keyvalmap.setAllData(data);
835 keylist[key] = keyvalmap;
836 } //< else (citation entry)
838 } //< for loop over files
840 buffer().addBiblioInfo(keylist);
844 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
846 string texfile = changeExtension(to_utf8(filename), "bib");
847 // note that, if the filename can be found directly from the path,
848 // findtexfile will just return a FileName object for that path.
849 FileName file(findtexfile(texfile, "bib"));
851 file = FileName(makeAbsPath(texfile, buf.filePath()));
856 bool InsetBibtex::addDatabase(docstring const & db)
858 docstring bibfiles = getParam("bibfiles");
859 if (tokenPos(bibfiles, ',', db) != -1)
861 if (!bibfiles.empty())
863 setParam("bibfiles", bibfiles + db);
868 bool InsetBibtex::delDatabase(docstring const & db)
870 docstring bibfiles = getParam("bibfiles");
871 if (contains(bibfiles, db)) {
872 int const n = tokenPos(bibfiles, ',', db);
875 // this is not the first database
876 docstring tmp = ',' + bd;
877 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
879 // this is the first (or only) database
880 setParam("bibfiles", split(bibfiles, bd, ','));
888 void InsetBibtex::validate(LaTeXFeatures & features) const
890 BufferParams const & mparams = features.buffer().masterParams();
891 if (mparams.useBibtopic())
892 features.require("bibtopic");
893 else if (!mparams.useBiblatex() && mparams.multibib == "child")
894 features.require("chapterbib");
896 // It'd be better to be able to get this from an InsetLayout, but at present
897 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
898 if (features.runparams().flavor == OutputParams::HTML)
899 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
900 "span.bibtexlabel:before{ content: \"[\"; }\n"
901 "span.bibtexlabel:after{ content: \"] \"; }");
905 int InsetBibtex::plaintext(odocstringstream & os,
906 OutputParams const & op, size_t max_length) const
908 docstring const reflabel = buffer().B_("References");
910 // We could output more information here, e.g., what databases are included
911 // and information about options. But I don't necessarily see any reason to
912 // do this right now.
913 if (op.for_tooltip || op.for_toc || op.for_search) {
914 os << '[' << reflabel << ']' << '\n';
915 return PLAINTEXT_NEWLINE;
918 BiblioInfo bibinfo = buffer().masterBibInfo();
919 bibinfo.makeCitationLabels(buffer());
920 vector<docstring> const & cites = bibinfo.citedEntries();
922 size_t start_size = os.str().size();
924 refoutput += reflabel + "\n\n";
926 // Tell BiblioInfo our purpose
928 ci.context = CiteItem::Export;
930 // Now we loop over the entries
931 vector<docstring>::const_iterator vit = cites.begin();
932 vector<docstring>::const_iterator const ven = cites.end();
933 for (; vit != ven; ++vit) {
934 if (start_size + refoutput.size() >= max_length)
936 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
937 if (biit == bibinfo.end())
939 BibTeXInfo const & entry = biit->second;
940 refoutput += "[" + entry.label() + "] ";
941 // FIXME Right now, we are calling BibInfo::getInfo on the key,
942 // which will give us all the cross-referenced info. But for every
943 // entry, so there's a lot of repitition. This should be fixed.
944 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
947 return refoutput.size();
952 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
953 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
954 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
956 BiblioInfo const & bibinfo = buffer().masterBibInfo();
957 bool const all_entries = getParam("btprint") == "btPrintAll";
958 vector<docstring> const & cites =
959 all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
961 docstring const reflabel = buffer().B_("References");
963 // tell BiblioInfo our purpose
965 ci.context = CiteItem::Export;
967 ci.max_key_size = UINT_MAX;
969 xs << html::StartTag("h2", "class='bibtex'")
971 << html::EndTag("h2")
972 << html::StartTag("div", "class='bibtex'");
974 // Now we loop over the entries
975 vector<docstring>::const_iterator vit = cites.begin();
976 vector<docstring>::const_iterator const ven = cites.end();
977 for (; vit != ven; ++vit) {
978 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
979 if (biit == bibinfo.end())
982 BibTeXInfo const & entry = biit->second;
983 string const attr = "class='bibtexentry' id='LyXCite-"
984 + to_utf8(html::cleanAttr(entry.key())) + "'";
985 xs << html::StartTag("div", attr);
987 // don't print labels if we're outputting all entries
989 xs << html::StartTag("span", "class='bibtexlabel'")
991 << html::EndTag("span");
994 // FIXME Right now, we are calling BibInfo::getInfo on the key,
995 // which will give us all the cross-referenced info. But for every
996 // entry, so there's a lot of repitition. This should be fixed.
997 xs << html::StartTag("span", "class='bibtexinfo'")
998 << XHTMLStream::ESCAPE_AND
999 << bibinfo.getInfo(entry.key(), buffer(), ci)
1000 << html::EndTag("span")
1001 << html::EndTag("div")
1004 xs << html::EndTag("div");
1009 void InsetBibtex::write(ostream & os) const
1011 params().Write(os, &buffer());
1015 string InsetBibtex::contextMenuName() const
1017 return "context-bibtex";