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");
226 tip += _("Lists:") + " ";
227 if (btprint == "bibbysection")
228 tip += _("all reference units");
229 else if (btprint == "btPrintAll")
230 tip += _("all references");
232 tip += _("all cited references");
235 tip += _("included in TOC");
237 if (!getParam("biblatexopts").empty()) {
240 tip += _("Options: ") + getParam("biblatexopts");
248 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
250 // The sequence of the commands:
251 // With normal BibTeX:
252 // 1. \bibliographystyle{style}
253 // 2. \addcontentsline{...} - if option bibtotoc set
254 // 3. \bibliography{database}
256 // 1. \bibliographystyle{style}
257 // 2. \begin{btSect}{database}
258 // 3. \btPrint{Cited|NotCited|All}
261 // \printbibliography[biblatexopts]
263 // \bibbysection[biblatexopts] - if btprint is "bibbysection"
265 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
267 if (prefixIs(style, "bibtotoc")) {
268 bibtotoc = "bibtotoc";
269 if (contains(style, ','))
270 style = split(style, bibtotoc, ',');
273 if (usingBiblatex()) {
275 string opts = to_utf8(getParam("biblatexopts"));
277 if (!bibtotoc.empty())
278 opts = opts.empty() ? "heading=bibintoc" : "heading=bibintoc," + opts;
279 // The bibliography command
280 docstring btprint = getParam("btprint");
281 if (btprint == "btPrintAll")
282 os << "\\nocite{*}\n";
283 if (btprint == "bibbysection" && !buffer().masterParams().multibib.empty())
284 os << "\\bibbysection";
286 os << "\\printbibliography";
288 os << "[" << opts << "]";
290 } else {// using BibTeX
292 vector<docstring> const db_out =
293 buffer().prepareBibFilePaths(runparams, getBibFiles(), false);
295 if (style == "default")
296 style = buffer().masterParams().defaultBiblioStyle();
297 if (!style.empty() && !buffer().masterParams().useBibtopic()) {
298 string base = buffer().masterBuffer()->prepareFileNameForLaTeX(style, ".bst", runparams.nice);
299 FileName const try_in_file =
300 makeAbsPath(base + ".bst", buffer().filePath());
301 bool const not_from_texmf = try_in_file.isReadableFile();
302 // If this style does not come from texmf and we are not
303 // exporting to .tex copy it to the tmp directory.
304 // This prevents problems with spaces and 8bit characters
306 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
308 // use new style name
309 DocFileName const in_file = DocFileName(try_in_file);
310 base = removeExtension(in_file.mangledFileName());
311 FileName const out_file = makeAbsPath(base + ".bst",
312 buffer().masterBuffer()->temppath());
313 bool const success = in_file.copyTo(out_file);
315 LYXERR0("Failed to copy '" << in_file
316 << "' to '" << out_file << "'");
320 os << "\\bibliographystyle{"
321 << from_utf8(latex_path(buffer().prepareFileNameForLaTeX(base, ".bst", runparams.nice)))
324 // Warn about spaces in bst path. Warn only once.
325 static bool warned_about_bst_spaces = false;
326 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
327 warned_about_bst_spaces = true;
328 Alert::warning(_("Export Warning!"),
329 _("There are spaces in the path to your BibTeX style file.\n"
330 "BibTeX will be unable to find it."));
332 // Handle the bibtopic case
333 if (!db_out.empty() && buffer().masterParams().useBibtopic()) {
334 os << "\\begin{btSect}";
336 os << "[" << style << "]";
337 os << "{" << getStringFromVector(db_out) << "}\n";
338 docstring btprint = getParam("btprint");
341 btprint = from_ascii("btPrintCited");
342 os << "\\" << btprint << "\n"
343 << "\\end{btSect}\n";
346 if (!bibtotoc.empty() && !buffer().masterParams().useBibtopic()) {
347 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
348 if (buffer().masterParams().pdfoptions().use_hyperref)
349 os << "\\phantomsection";
350 if (buffer().masterParams().documentClass().hasLaTeXLayout("chapter"))
351 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
352 else if (buffer().masterParams().documentClass().hasLaTeXLayout("section"))
353 os << "\\addcontentsline{toc}{section}{\\refname}";
355 // The bibliography command
356 if (!db_out.empty() && !buffer().masterParams().useBibtopic()) {
357 docstring btprint = getParam("btprint");
358 if (btprint == "btPrintAll") {
359 os << "\\nocite{*}\n";
361 os << "\\bibliography{" << getStringFromVector(db_out) << "}\n";
367 support::FileNamePairList InsetBibtex::getBibFiles() const
369 FileName path(buffer().filePath());
370 support::PathChanger p(path);
372 // We need to store both the real FileName and the way it is entered
373 // (with full path, rel path or as a single file name).
374 // The latter is needed for biblatex's central bibfile macro.
375 support::FileNamePairList vec;
377 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
378 vector<docstring>::const_iterator it = bibfilelist.begin();
379 vector<docstring>::const_iterator en = bibfilelist.end();
380 for (; it != en; ++it) {
381 FileName const file = getBibTeXPath(*it, buffer());
384 vec.push_back(make_pair(*it, file));
386 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
395 // methods for parsing bibtex files
397 typedef map<docstring, docstring> VarMap;
399 /// remove whitespace characters, optionally a single comma,
400 /// and further whitespace characters from the stream.
401 /// @return true if a comma was found, false otherwise
403 bool removeWSAndComma(ifdocstream & ifs) {
412 } while (ifs && isSpace(ch));
425 } while (ifs && isSpace(ch));
440 /// remove whitespace characters, read characer sequence
441 /// not containing whitespace characters or characters in
442 /// delimChars, and remove further whitespace characters.
444 /// @return true if a string of length > 0 could be read.
446 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
447 docstring const & delimChars, docstring const & illegalChars,
460 } while (ifs && isSpace(ch));
466 bool legalChar = true;
467 while (ifs && !isSpace(ch) &&
468 delimChars.find(ch) == docstring::npos &&
469 (legalChar = (illegalChars.find(ch) == docstring::npos))
472 if (chCase == makeLowerCase)
473 val += lowercase(ch);
485 while (ifs && isSpace(ch)) {
493 return val.length() > 0;
496 /// read subsequent bibtex values that are delimited with a #-character.
497 /// Concatenate all parts and replace names with the associated string in
498 /// the variable strings.
499 /// @return true if reading was successfull (all single parts were delimited
501 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
514 } while (ifs && isSpace(ch));
519 // check for field type
520 if (isDigitASCII(ch)) {
522 // read integer value
526 } while (ifs && isDigitASCII(ch));
531 } else if (ch == '"' || ch == '{') {
533 char_type delim = ch == '"' ? '"': '}';
538 } while (ifs && isSpace(ch));
543 // We now have the first non-whitespace character
544 // We'll collapse adjacent whitespace.
545 bool lastWasWhiteSpace = false;
547 // inside this delimited text braces must match.
548 // Thus we can have a closing delimiter only
549 // when nestLevel == 0
552 while (ifs && (nestLevel > 0 || ch != delim)) {
554 lastWasWhiteSpace = true;
558 // We output the space only after we stop getting
559 // whitespace so as not to output any whitespace
560 // at the end of the value.
561 if (lastWasWhiteSpace) {
562 lastWasWhiteSpace = false;
568 // update nesting level
587 // FIXME Why is this here?
595 // reading a string name
598 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
599 strName += lowercase(ch);
606 // replace the string with its assigned value or
607 // discard it if it's not assigned
608 if (strName.length()) {
609 VarMap::const_iterator pos = strings.find(strName);
610 if (pos != strings.end()) {
617 while (ifs && isSpace(ch)) {
624 // continue reading next value on concatenate with '#'
634 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
640 void InsetBibtex::parseBibTeXFiles() const
642 // This bibtex parser is a first step to parse bibtex files
645 // - it reads the whole bibtex entry and does a syntax check
646 // (matching delimiters, missing commas,...
647 // - it recovers from errors starting with the next @-character
648 // - it reads @string definitions and replaces them in the
650 // - it accepts more characters in keys or value names than
653 // Officially bibtex does only support ASCII, but in practice
654 // you can use the encoding of the main document as long as
655 // some elements like keys and names are pure ASCII. Therefore
656 // we convert the file from the buffer encoding.
657 // We don't restrict keys to ASCII in LyX, since our own
658 // InsetBibitem can generate non-ASCII keys, and nonstandard
659 // 8bit clean bibtex forks exist.
663 support::FileNamePairList const files = getBibFiles();
664 support::FileNamePairList::const_iterator it = files.begin();
665 support::FileNamePairList::const_iterator en = files.end();
666 for (; it != en; ++ it) {
667 ifdocstream ifs(it->second.toFilesystemEncoding().c_str(),
668 ios_base::in, buffer().masterParams().encoding().iconvName());
684 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
685 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
690 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
694 if (entryType == from_ascii("comment")) {
695 ifs.ignore(numeric_limits<int>::max(), '\n');
701 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
705 if ((ch != '(') && (ch != '{')) {
706 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
712 if (entryType == from_ascii("string")) {
714 // read string and add it to the strings map
715 // (or replace it's old value)
719 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
720 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
725 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
729 // next char must be an equal sign
731 if (!ifs || ch != '=') {
732 lyxerr << "BibTeX Parser: No `=' after string name: " <<
733 name << "." << std::endl;
737 if (!readValue(value, ifs, strings)) {
738 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
739 name << "." << std::endl;
743 strings[name] = value;
745 } else if (entryType == from_ascii("preamble")) {
747 // preamble definitions are discarded.
748 // can they be of any use in lyx?
751 if (!readValue(value, ifs, strings)) {
752 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
758 // Citation entry. Try to read the key.
761 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
762 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
763 entryType << "." << std::endl;
768 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
772 /////////////////////////////////////////////
773 // now we have a key, so we will add an entry
774 // (even if it's empty, as bibtex does)
776 // we now read the field = value pairs.
777 // all items must be separated by a comma. If
778 // it is missing the scanning of this entry is
779 // stopped and the next is searched.
783 BibTeXInfo keyvalmap(key, entryType);
785 bool readNext = removeWSAndComma(ifs);
787 while (ifs && readNext) {
790 if (!readTypeOrKey(name, ifs, from_ascii("="),
791 from_ascii("{}(),"), makeLowerCase) || !ifs)
794 // next char must be an equal sign
795 // FIXME Whitespace??
798 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
802 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
803 name << ", for key: " << key << "." << std::endl;
809 if (!readValue(value, ifs, strings)) {
810 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
811 name << ", for key: " << key << "." << std::endl;
815 keyvalmap[name] = value;
816 data += "\n\n" + value;
817 keylist.addFieldName(name);
818 readNext = removeWSAndComma(ifs);
822 keylist.addEntryType(entryType);
823 keyvalmap.setAllData(data);
824 keylist[key] = keyvalmap;
825 } //< else (citation entry)
827 } //< for loop over files
829 buffer().addBiblioInfo(keylist);
833 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
835 string texfile = changeExtension(to_utf8(filename), "bib");
836 // note that, if the filename can be found directly from the path,
837 // findtexfile will just return a FileName object for that path.
838 FileName file(findtexfile(texfile, "bib"));
840 file = FileName(makeAbsPath(texfile, buf.filePath()));
845 bool InsetBibtex::addDatabase(docstring const & db)
847 docstring bibfiles = getParam("bibfiles");
848 if (tokenPos(bibfiles, ',', db) != -1)
850 if (!bibfiles.empty())
852 setParam("bibfiles", bibfiles + db);
857 bool InsetBibtex::delDatabase(docstring const & db)
859 docstring bibfiles = getParam("bibfiles");
860 if (contains(bibfiles, db)) {
861 int const n = tokenPos(bibfiles, ',', db);
864 // this is not the first database
865 docstring tmp = ',' + bd;
866 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
868 // this is the first (or only) database
869 setParam("bibfiles", split(bibfiles, bd, ','));
877 void InsetBibtex::validate(LaTeXFeatures & features) const
879 if (features.buffer().masterParams().useBibtopic())
880 features.require("bibtopic");
882 // It'd be better to be able to get this from an InsetLayout, but at present
883 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
884 if (features.runparams().flavor == OutputParams::HTML)
885 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
886 "span.bibtexlabel:before{ content: \"[\"; }\n"
887 "span.bibtexlabel:after{ content: \"] \"; }");
891 int InsetBibtex::plaintext(odocstringstream & os,
892 OutputParams const & op, size_t max_length) const
894 docstring const reflabel = buffer().B_("References");
896 // We could output more information here, e.g., what databases are included
897 // and information about options. But I don't necessarily see any reason to
898 // do this right now.
899 if (op.for_tooltip || op.for_toc || op.for_search) {
900 os << '[' << reflabel << ']' << '\n';
901 return PLAINTEXT_NEWLINE;
904 BiblioInfo bibinfo = buffer().masterBibInfo();
905 bibinfo.makeCitationLabels(buffer());
906 vector<docstring> const & cites = bibinfo.citedEntries();
908 size_t start_size = os.str().size();
910 refoutput += reflabel + "\n\n";
912 // Tell BiblioInfo our purpose
914 ci.context = CiteItem::Export;
916 // Now we loop over the entries
917 vector<docstring>::const_iterator vit = cites.begin();
918 vector<docstring>::const_iterator const ven = cites.end();
919 for (; vit != ven; ++vit) {
920 if (start_size + refoutput.size() >= max_length)
922 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
923 if (biit == bibinfo.end())
925 BibTeXInfo const & entry = biit->second;
926 refoutput += "[" + entry.label() + "] ";
927 // FIXME Right now, we are calling BibInfo::getInfo on the key,
928 // which will give us all the cross-referenced info. But for every
929 // entry, so there's a lot of repitition. This should be fixed.
930 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
933 return refoutput.size();
938 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
939 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
940 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
942 BiblioInfo const & bibinfo = buffer().masterBibInfo();
943 bool const all_entries = getParam("btprint") == "btPrintAll";
944 vector<docstring> const & cites =
945 all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
947 docstring const reflabel = buffer().B_("References");
949 // tell BiblioInfo our purpose
951 ci.context = CiteItem::Export;
953 ci.max_key_size = UINT_MAX;
955 xs << html::StartTag("h2", "class='bibtex'")
957 << html::EndTag("h2")
958 << html::StartTag("div", "class='bibtex'");
960 // Now we loop over the entries
961 vector<docstring>::const_iterator vit = cites.begin();
962 vector<docstring>::const_iterator const ven = cites.end();
963 for (; vit != ven; ++vit) {
964 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
965 if (biit == bibinfo.end())
968 BibTeXInfo const & entry = biit->second;
969 string const attr = "class='bibtexentry' id='LyXCite-"
970 + to_utf8(html::cleanAttr(entry.key())) + "'";
971 xs << html::StartTag("div", attr);
973 // don't print labels if we're outputting all entries
975 xs << html::StartTag("span", "class='bibtexlabel'")
977 << html::EndTag("span");
980 // FIXME Right now, we are calling BibInfo::getInfo on the key,
981 // which will give us all the cross-referenced info. But for every
982 // entry, so there's a lot of repitition. This should be fixed.
983 xs << html::StartTag("span", "class='bibtexinfo'")
984 << XHTMLStream::ESCAPE_AND
985 << bibinfo.getInfo(entry.key(), buffer(), ci)
986 << html::EndTag("span")
987 << html::EndTag("div")
990 xs << html::EndTag("div");
995 void InsetBibtex::write(ostream & os) const
997 params().Write(os, &buffer());
1001 string InsetBibtex::contextMenuName() const
1003 return "context-bibtex";