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)
65 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
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);
78 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
80 switch (cmd.action()) {
86 case LFUN_INSET_MODIFY: {
87 InsetCommandParams p(BIBTEX_CODE);
89 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
93 } catch (ExceptionMessage const & message) {
94 if (message.type_ == WarningException) {
95 Alert::warning(message.title_, message.details_);
104 cur.forceBufferUpdate();
109 InsetCommand::doDispatch(cur, cmd);
115 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
116 FuncStatus & flag) const
118 switch (cmd.action()) {
119 case LFUN_INSET_EDIT:
120 flag.setEnabled(true);
124 return InsetCommand::getStatus(cur, cmd, flag);
129 void InsetBibtex::editDatabases() const
131 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
133 if (bibfilelist.empty())
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"));
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));
159 bool InsetBibtex::usingBiblatex() const
161 return buffer().masterParams().useBiblatex();
165 docstring InsetBibtex::screenLabel() const
167 return usingBiblatex() ? _("Biblatex Generated Bibliography")
168 : _("BibTeX Generated Bibliography");
172 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
174 docstring tip = _("Databases:");
175 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
178 if (bibfilelist.empty())
179 tip += "<li>" + _("none") + "</li>";
181 for (docstring const & bibfile : bibfilelist)
182 tip += "<li>" + bibfile + "</li>";
187 docstring style = getParam("options"); // maybe empty! and with bibtotoc
188 docstring bibtotoc = from_ascii("bibtotoc");
189 if (prefixIs(style, bibtotoc)) {
191 if (contains(style, char_type(',')))
192 style = split(style, bibtotoc, char_type(','));
195 docstring const btprint = getParam("btprint");
196 if (!usingBiblatex()) {
197 tip += _("Style File:");
198 tip += "<ul><li>" + (style.empty() ? _("none") : style) + "</li></ul>";
200 tip += _("Lists:") + " ";
201 if (btprint == "btPrintAll")
202 tip += _("all references");
203 else if (btprint == "btPrintNotCited")
204 tip += _("all uncited references");
206 tip += _("all cited references");
209 tip += _("included in TOC");
211 if (!buffer().parent()
212 && buffer().params().multibib == "child") {
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'");
218 tip += _("Lists:") + " ";
219 if (btprint == "bibbysection")
220 tip += _("all reference units");
221 else if (btprint == "btPrintAll")
222 tip += _("all references");
224 tip += _("all cited references");
227 tip += _("included in TOC");
229 if (!getParam("biblatexopts").empty()) {
232 tip += _("Options: ") + getParam("biblatexopts");
240 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
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}
248 // 1. \bibliographystyle{style}
249 // 2. \begin{btSect}{database}
250 // 3. \btPrint{Cited|NotCited|All}
253 // \printbibliography[biblatexopts]
255 // \bibbysection[biblatexopts] - if btprint is "bibbysection"
257 // chapterbib does not allow bibliographies in the master
258 if (!usingBiblatex() && !runparams.is_child
259 && buffer().params().multibib == "child")
262 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
264 if (prefixIs(style, "bibtotoc")) {
265 bibtotoc = "bibtotoc";
266 if (contains(style, ','))
267 style = split(style, bibtotoc, ',');
270 if (usingBiblatex()) {
272 string opts = to_utf8(getParam("biblatexopts"));
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";
283 os << "\\printbibliography";
285 os << "[" << opts << "]";
287 } else {// using BibTeX
289 vector<docstring> const db_out =
290 buffer().prepareBibFilePaths(runparams, getBibFiles(), false);
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
303 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
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);
312 LYXERR0("Failed to copy '" << in_file
313 << "' to '" << out_file << "'");
317 os << "\\bibliographystyle{"
318 << from_utf8(latex_path(buffer().prepareFileNameForLaTeX(base, ".bst", runparams.nice)))
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."));
329 // Handle the bibtopic case
330 if (!db_out.empty() && buffer().masterParams().useBibtopic()) {
331 os << "\\begin{btSect}";
333 os << "[" << style << "]";
334 os << "{" << getStringFromVector(db_out) << "}\n";
335 docstring btprint = getParam("btprint");
338 btprint = from_ascii("btPrintCited");
339 os << "\\" << btprint << "\n"
340 << "\\end{btSect}\n";
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}";
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";
358 os << "\\bibliography{" << getStringFromVector(db_out) << "}\n";
364 FileNamePairList InsetBibtex::getBibFiles() const
366 FileName path(buffer().filePath());
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;
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());
381 vec.push_back(make_pair(*it, file));
383 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
391 // methods for parsing bibtex files
393 typedef map<docstring, docstring> VarMap;
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
399 bool removeWSAndComma(ifdocstream & ifs) {
408 } while (ifs && isSpace(ch));
421 } while (ifs && isSpace(ch));
436 /// remove whitespace characters, read characer sequence
437 /// not containing whitespace characters or characters in
438 /// delimChars, and remove further whitespace characters.
440 /// @return true if a string of length > 0 could be read.
442 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
443 docstring const & delimChars, docstring const & illegalChars,
456 } while (ifs && isSpace(ch));
462 while (ifs && !isSpace(ch) &&
463 delimChars.find(ch) == docstring::npos &&
464 illegalChars.find(ch) == docstring::npos)
466 if (chCase == makeLowerCase)
467 val += lowercase(ch);
473 if (illegalChars.find(ch) != docstring::npos) {
479 while (ifs && isSpace(ch)) {
487 return val.length() > 0;
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
495 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
508 } while (ifs && isSpace(ch));
513 // check for field type
514 if (isDigitASCII(ch)) {
516 // read integer value
520 } while (ifs && isDigitASCII(ch));
525 } else if (ch == '"' || ch == '{') {
527 char_type delim = ch == '"' ? '"': '}';
532 } while (ifs && isSpace(ch));
537 // We now have the first non-whitespace character
538 // We'll collapse adjacent whitespace.
539 bool lastWasWhiteSpace = false;
541 // inside this delimited text braces must match.
542 // Thus we can have a closing delimiter only
543 // when nestLevel == 0
546 while (ifs && (nestLevel > 0 || ch != delim)) {
548 lastWasWhiteSpace = true;
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;
562 // update nesting level
581 // FIXME Why is this here?
589 // reading a string name
592 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
593 strName += lowercase(ch);
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()) {
611 while (ifs && isSpace(ch)) {
618 // continue reading next value on concatenate with '#'
628 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
630 parseBibTeXFiles(checkedFiles);
634 void InsetBibtex::parseBibTeXFiles(FileNameList & checkedFiles) const
636 // This bibtex parser is a first step to parse bibtex files
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
644 // - it accepts more characters in keys or value names than
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.
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.
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());
685 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
686 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
691 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
695 if (entryType == from_ascii("comment")) {
696 ifs.ignore(numeric_limits<int>::max(), '\n');
702 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
706 if ((ch != '(') && (ch != '{')) {
707 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
713 if (entryType == from_ascii("string")) {
715 // read string and add it to the strings map
716 // (or replace it's old value)
720 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
721 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
726 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
730 // next char must be an equal sign
732 if (!ifs || ch != '=') {
733 lyxerr << "BibTeX Parser: No `=' after string name: " <<
734 name << "." << std::endl;
738 if (!readValue(value, ifs, strings)) {
739 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
740 name << "." << std::endl;
744 strings[name] = value;
746 } else if (entryType == from_ascii("preamble")) {
748 // preamble definitions are discarded.
749 // can they be of any use in lyx?
752 if (!readValue(value, ifs, strings)) {
753 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
759 // Citation entry. Try to read the key.
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;
769 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
773 /////////////////////////////////////////////
774 // now we have a key, so we will add an entry
775 // (even if it's empty, as bibtex does)
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.
784 BibTeXInfo keyvalmap(key, entryType);
786 bool readNext = removeWSAndComma(ifs);
788 while (ifs && readNext) {
791 if (!readTypeOrKey(name, ifs, from_ascii("="),
792 from_ascii("{}(),"), makeLowerCase) || !ifs)
795 // next char must be an equal sign
796 // FIXME Whitespace??
799 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
803 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
804 name << ", for key: " << key << "." << std::endl;
810 if (!readValue(value, ifs, strings)) {
811 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
812 name << ", for key: " << key << "." << std::endl;
816 keyvalmap[name] = value;
817 data += "\n\n" + value;
818 keylist.addFieldName(name);
819 readNext = removeWSAndComma(ifs);
823 keylist.addEntryType(entryType);
824 keyvalmap.setAllData(data);
825 keylist[key] = keyvalmap;
826 } //< else (citation entry)
828 } //< for loop over files
830 buffer().addBiblioInfo(keylist);
834 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
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"));
841 file = FileName(makeAbsPath(texfile, buf.filePath()));
846 bool InsetBibtex::addDatabase(docstring const & db)
848 docstring bibfiles = getParam("bibfiles");
849 if (tokenPos(bibfiles, ',', db) != -1)
851 if (!bibfiles.empty())
853 setParam("bibfiles", bibfiles + db);
858 bool InsetBibtex::delDatabase(docstring const & db)
860 docstring bibfiles = getParam("bibfiles");
861 if (contains(bibfiles, db)) {
862 int const n = tokenPos(bibfiles, ',', db);
865 // this is not the first database
866 docstring tmp = ',' + bd;
867 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
869 // this is the first (or only) database
870 setParam("bibfiles", split(bibfiles, bd, ','));
878 void InsetBibtex::validate(LaTeXFeatures & features) const
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");
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: \"] \"; }");
895 void InsetBibtex::updateBuffer(ParIterator const &, UpdateType) {
896 buffer().registerBibfiles(getBibFiles());
900 int InsetBibtex::plaintext(odocstringstream & os,
901 OutputParams const & op, size_t max_length) const
903 docstring const reflabel = buffer().B_("References");
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;
913 BiblioInfo bibinfo = buffer().masterBibInfo();
914 bibinfo.makeCitationLabels(buffer());
915 vector<docstring> const & cites = bibinfo.citedEntries();
917 size_t start_size = os.str().size();
919 refoutput += reflabel + "\n\n";
921 // Tell BiblioInfo our purpose
923 ci.context = CiteItem::Export;
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)
931 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
932 if (biit == bibinfo.end())
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";
942 return refoutput.size();
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
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();
956 docstring const reflabel = buffer().B_("References");
958 // tell BiblioInfo our purpose
960 ci.context = CiteItem::Export;
962 ci.max_key_size = UINT_MAX;
964 xs << html::StartTag("h2", "class='bibtex'")
966 << html::EndTag("h2")
967 << html::StartTag("div", "class='bibtex'");
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())
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);
982 // don't print labels if we're outputting all entries
984 xs << html::StartTag("span", "class='bibtexlabel'")
986 << html::EndTag("span");
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")
999 xs << html::EndTag("div");
1004 void InsetBibtex::write(ostream & os) const
1006 params().Write(os, &buffer());
1010 string InsetBibtex::contextMenuName() const
1012 return "context-bibtex";