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().masterBuffer()->params().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 if (!usingBiblatex()) {
210 tip += _("Style File:");
211 tip += "<ul><li>" + (style.empty() ? _("none") : style) + "</li></ul>";
213 tip += _("Lists:") + " ";
214 docstring btprint = getParam("btprint");
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");
227 tip += _("Included in TOC");
228 if (!getParam("biblatexopts").empty()) {
231 tip += _("Options: ") + getParam("biblatexopts");
239 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
241 // The sequence of the commands:
242 // With normal BibTeX:
243 // 1. \bibliographystyle{style}
244 // 2. \addcontentsline{...} - if option bibtotoc set
245 // 3. \bibliography{database}
247 // 1. \bibliographystyle{style}
248 // 2. \begin{btSect}{database}
249 // 3. \btPrint{Cited|NotCited|All}
252 // \printbibliography[biblatexopts]
254 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
256 if (prefixIs(style, "bibtotoc")) {
257 bibtotoc = "bibtotoc";
258 if (contains(style, ','))
259 style = split(style, bibtotoc, ',');
262 if (usingBiblatex()) {
264 string opts = to_utf8(getParam("biblatexopts"));
266 if (!bibtotoc.empty())
267 opts = opts.empty() ? "heading=bibintoc" : "heading=bibintoc," + opts;
268 // The bibliography command
269 docstring btprint = getParam("btprint");
270 if (btprint == "btPrintAll")
271 os << "\\nocite{*}\n";
272 os << "\\printbibliography";
274 os << "[" << opts << "]";
276 } else {// using BibTeX
278 vector<docstring> const db_out =
279 buffer().prepareBibFilePaths(runparams, getBibFiles(), false);
281 if (style == "default")
282 style = buffer().params().defaultBiblioStyle();
283 if (!style.empty() && !buffer().params().use_bibtopic) {
284 string base = buffer().prepareFileNameForLaTeX(style, ".bst", runparams.nice);
285 FileName const try_in_file =
286 makeAbsPath(base + ".bst", buffer().filePath());
287 bool const not_from_texmf = try_in_file.isReadableFile();
288 // If this style does not come from texmf and we are not
289 // exporting to .tex copy it to the tmp directory.
290 // This prevents problems with spaces and 8bit characters
292 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
294 // use new style name
295 DocFileName const in_file = DocFileName(try_in_file);
296 base = removeExtension(in_file.mangledFileName());
297 FileName const out_file = makeAbsPath(base + ".bst",
298 buffer().masterBuffer()->temppath());
299 bool const success = in_file.copyTo(out_file);
301 LYXERR0("Failed to copy '" << in_file
302 << "' to '" << out_file << "'");
306 os << "\\bibliographystyle{"
307 << from_utf8(latex_path(buffer().prepareFileNameForLaTeX(base, ".bst", runparams.nice)))
310 // Warn about spaces in bst path. Warn only once.
311 static bool warned_about_bst_spaces = false;
312 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
313 warned_about_bst_spaces = true;
314 Alert::warning(_("Export Warning!"),
315 _("There are spaces in the path to your BibTeX style file.\n"
316 "BibTeX will be unable to find it."));
318 // Handle the bibtopic case
319 if (!db_out.empty() && buffer().params().use_bibtopic) {
320 os << "\\begin{btSect}";
322 os << "[" << style << "]";
323 os << "{" << getStringFromVector(db_out) << "}\n";
324 docstring btprint = getParam("btprint");
327 btprint = from_ascii("btPrintCited");
328 os << "\\" << btprint << "\n"
329 << "\\end{btSect}\n";
332 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
333 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
334 if (buffer().params().pdfoptions().use_hyperref)
335 os << "\\phantomsection";
336 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
337 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
338 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
339 os << "\\addcontentsline{toc}{section}{\\refname}";
341 // The bibliography command
342 if (!db_out.empty() && !buffer().params().use_bibtopic) {
343 docstring btprint = getParam("btprint");
344 if (btprint == "btPrintAll") {
345 os << "\\nocite{*}\n";
347 os << "\\bibliography{" << getStringFromVector(db_out) << "}\n";
353 support::FileNamePairList InsetBibtex::getBibFiles() const
355 FileName path(buffer().filePath());
356 support::PathChanger p(path);
358 // We need to store both the real FileName and the way it is entered
359 // (with full path, rel path or as a single file name).
360 // The latter is needed for biblatex's central bibfile macro.
361 support::FileNamePairList vec;
363 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
364 vector<docstring>::const_iterator it = bibfilelist.begin();
365 vector<docstring>::const_iterator en = bibfilelist.end();
366 for (; it != en; ++it) {
367 FileName const file = getBibTeXPath(*it, buffer());
370 vec.push_back(make_pair(*it, file));
372 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
381 // methods for parsing bibtex files
383 typedef map<docstring, docstring> VarMap;
385 /// remove whitespace characters, optionally a single comma,
386 /// and further whitespace characters from the stream.
387 /// @return true if a comma was found, false otherwise
389 bool removeWSAndComma(ifdocstream & ifs) {
398 } while (ifs && isSpace(ch));
411 } while (ifs && isSpace(ch));
426 /// remove whitespace characters, read characer sequence
427 /// not containing whitespace characters or characters in
428 /// delimChars, and remove further whitespace characters.
430 /// @return true if a string of length > 0 could be read.
432 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
433 docstring const & delimChars, docstring const & illegalChars,
446 } while (ifs && isSpace(ch));
452 bool legalChar = true;
453 while (ifs && !isSpace(ch) &&
454 delimChars.find(ch) == docstring::npos &&
455 (legalChar = (illegalChars.find(ch) == docstring::npos))
458 if (chCase == makeLowerCase)
459 val += lowercase(ch);
471 while (ifs && isSpace(ch)) {
479 return val.length() > 0;
482 /// read subsequent bibtex values that are delimited with a #-character.
483 /// Concatenate all parts and replace names with the associated string in
484 /// the variable strings.
485 /// @return true if reading was successfull (all single parts were delimited
487 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
500 } while (ifs && isSpace(ch));
505 // check for field type
506 if (isDigitASCII(ch)) {
508 // read integer value
512 } while (ifs && isDigitASCII(ch));
517 } else if (ch == '"' || ch == '{') {
519 char_type delim = ch == '"' ? '"': '}';
524 } while (ifs && isSpace(ch));
529 // We now have the first non-whitespace character
530 // We'll collapse adjacent whitespace.
531 bool lastWasWhiteSpace = false;
533 // inside this delimited text braces must match.
534 // Thus we can have a closing delimiter only
535 // when nestLevel == 0
538 while (ifs && (nestLevel > 0 || ch != delim)) {
540 lastWasWhiteSpace = true;
544 // We output the space only after we stop getting
545 // whitespace so as not to output any whitespace
546 // at the end of the value.
547 if (lastWasWhiteSpace) {
548 lastWasWhiteSpace = false;
554 // update nesting level
573 // FIXME Why is this here?
581 // reading a string name
584 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
585 strName += lowercase(ch);
592 // replace the string with its assigned value or
593 // discard it if it's not assigned
594 if (strName.length()) {
595 VarMap::const_iterator pos = strings.find(strName);
596 if (pos != strings.end()) {
603 while (ifs && isSpace(ch)) {
610 // continue reading next value on concatenate with '#'
620 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
626 void InsetBibtex::parseBibTeXFiles() const
628 // This bibtex parser is a first step to parse bibtex files
631 // - it reads the whole bibtex entry and does a syntax check
632 // (matching delimiters, missing commas,...
633 // - it recovers from errors starting with the next @-character
634 // - it reads @string definitions and replaces them in the
636 // - it accepts more characters in keys or value names than
639 // Officially bibtex does only support ASCII, but in practice
640 // you can use the encoding of the main document as long as
641 // some elements like keys and names are pure ASCII. Therefore
642 // we convert the file from the buffer encoding.
643 // We don't restrict keys to ASCII in LyX, since our own
644 // InsetBibitem can generate non-ASCII keys, and nonstandard
645 // 8bit clean bibtex forks exist.
649 support::FileNamePairList const files = getBibFiles();
650 support::FileNamePairList::const_iterator it = files.begin();
651 support::FileNamePairList::const_iterator en = files.end();
652 for (; it != en; ++ it) {
653 ifdocstream ifs(it->second.toFilesystemEncoding().c_str(),
654 ios_base::in, buffer().params().encoding().iconvName());
670 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
671 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
676 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
680 if (entryType == from_ascii("comment")) {
681 ifs.ignore(numeric_limits<int>::max(), '\n');
687 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
691 if ((ch != '(') && (ch != '{')) {
692 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
698 if (entryType == from_ascii("string")) {
700 // read string and add it to the strings map
701 // (or replace it's old value)
705 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
706 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
711 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
715 // next char must be an equal sign
717 if (!ifs || ch != '=') {
718 lyxerr << "BibTeX Parser: No `=' after string name: " <<
719 name << "." << std::endl;
723 if (!readValue(value, ifs, strings)) {
724 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
725 name << "." << std::endl;
729 strings[name] = value;
731 } else if (entryType == from_ascii("preamble")) {
733 // preamble definitions are discarded.
734 // can they be of any use in lyx?
737 if (!readValue(value, ifs, strings)) {
738 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
744 // Citation entry. Try to read the key.
747 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
748 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
749 entryType << "." << std::endl;
754 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
758 /////////////////////////////////////////////
759 // now we have a key, so we will add an entry
760 // (even if it's empty, as bibtex does)
762 // we now read the field = value pairs.
763 // all items must be separated by a comma. If
764 // it is missing the scanning of this entry is
765 // stopped and the next is searched.
769 BibTeXInfo keyvalmap(key, entryType);
771 bool readNext = removeWSAndComma(ifs);
773 while (ifs && readNext) {
776 if (!readTypeOrKey(name, ifs, from_ascii("="),
777 from_ascii("{}(),"), makeLowerCase) || !ifs)
780 // next char must be an equal sign
781 // FIXME Whitespace??
784 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
788 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
789 name << ", for key: " << key << "." << std::endl;
795 if (!readValue(value, ifs, strings)) {
796 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
797 name << ", for key: " << key << "." << std::endl;
801 keyvalmap[name] = value;
802 data += "\n\n" + value;
803 keylist.addFieldName(name);
804 readNext = removeWSAndComma(ifs);
808 keylist.addEntryType(entryType);
809 keyvalmap.setAllData(data);
810 keylist[key] = keyvalmap;
811 } //< else (citation entry)
813 } //< for loop over files
815 buffer().addBiblioInfo(keylist);
819 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
821 string texfile = changeExtension(to_utf8(filename), "bib");
822 // note that, if the filename can be found directly from the path,
823 // findtexfile will just return a FileName object for that path.
824 FileName file(findtexfile(texfile, "bib"));
826 file = FileName(makeAbsPath(texfile, buf.filePath()));
831 bool InsetBibtex::addDatabase(docstring const & db)
833 docstring bibfiles = getParam("bibfiles");
834 if (tokenPos(bibfiles, ',', db) != -1)
836 if (!bibfiles.empty())
838 setParam("bibfiles", bibfiles + db);
843 bool InsetBibtex::delDatabase(docstring const & db)
845 docstring bibfiles = getParam("bibfiles");
846 if (contains(bibfiles, db)) {
847 int const n = tokenPos(bibfiles, ',', db);
850 // this is not the first database
851 docstring tmp = ',' + bd;
852 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
854 // this is the first (or only) database
855 setParam("bibfiles", split(bibfiles, bd, ','));
863 void InsetBibtex::validate(LaTeXFeatures & features) const
865 if (features.bufferParams().use_bibtopic)
866 features.require("bibtopic");
868 // It'd be better to be able to get this from an InsetLayout, but at present
869 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
870 if (features.runparams().flavor == OutputParams::HTML)
871 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
872 "span.bibtexlabel:before{ content: \"[\"; }\n"
873 "span.bibtexlabel:after{ content: \"] \"; }");
877 int InsetBibtex::plaintext(odocstringstream & os,
878 OutputParams const & op, size_t max_length) const
880 docstring const reflabel = buffer().B_("References");
882 // We could output more information here, e.g., what databases are included
883 // and information about options. But I don't necessarily see any reason to
884 // do this right now.
885 if (op.for_tooltip || op.for_toc || op.for_search) {
886 os << '[' << reflabel << ']' << '\n';
887 return PLAINTEXT_NEWLINE;
890 BiblioInfo bibinfo = buffer().masterBibInfo();
891 bibinfo.makeCitationLabels(buffer());
892 vector<docstring> const & cites = bibinfo.citedEntries();
894 size_t start_size = os.str().size();
896 refoutput += reflabel + "\n\n";
898 // Tell BiblioInfo our purpose
900 ci.context = CiteItem::Export;
902 // Now we loop over the entries
903 vector<docstring>::const_iterator vit = cites.begin();
904 vector<docstring>::const_iterator const ven = cites.end();
905 for (; vit != ven; ++vit) {
906 if (start_size + refoutput.size() >= max_length)
908 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
909 if (biit == bibinfo.end())
911 BibTeXInfo const & entry = biit->second;
912 refoutput += "[" + entry.label() + "] ";
913 // FIXME Right now, we are calling BibInfo::getInfo on the key,
914 // which will give us all the cross-referenced info. But for every
915 // entry, so there's a lot of repitition. This should be fixed.
916 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
919 return refoutput.size();
924 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
925 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
926 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
928 BiblioInfo const & bibinfo = buffer().masterBibInfo();
929 bool const all_entries = getParam("btprint") == "btPrintAll";
930 vector<docstring> const & cites =
931 all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
933 docstring const reflabel = buffer().B_("References");
935 // tell BiblioInfo our purpose
937 ci.context = CiteItem::Export;
939 ci.max_key_size = UINT_MAX;
941 xs << html::StartTag("h2", "class='bibtex'")
943 << html::EndTag("h2")
944 << html::StartTag("div", "class='bibtex'");
946 // Now we loop over the entries
947 vector<docstring>::const_iterator vit = cites.begin();
948 vector<docstring>::const_iterator const ven = cites.end();
949 for (; vit != ven; ++vit) {
950 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
951 if (biit == bibinfo.end())
954 BibTeXInfo const & entry = biit->second;
955 string const attr = "class='bibtexentry' id='LyXCite-"
956 + to_utf8(html::cleanAttr(entry.key())) + "'";
957 xs << html::StartTag("div", attr);
959 // don't print labels if we're outputting all entries
961 xs << html::StartTag("span", "class='bibtexlabel'")
963 << html::EndTag("span");
966 // FIXME Right now, we are calling BibInfo::getInfo on the key,
967 // which will give us all the cross-referenced info. But for every
968 // entry, so there's a lot of repitition. This should be fixed.
969 xs << html::StartTag("span", "class='bibtexinfo'")
970 << XHTMLStream::ESCAPE_AND
971 << bibinfo.getInfo(entry.key(), buffer(), ci)
972 << html::EndTag("span")
973 << html::EndTag("div")
976 xs << html::EndTag("div");
981 void InsetBibtex::write(ostream & os) const
983 params().Write(os, &buffer());
987 string InsetBibtex::contextMenuName() const
989 return "context-bibtex";