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 bool legalChar = true;
463 while (ifs && !isSpace(ch) &&
464 delimChars.find(ch) == docstring::npos &&
465 (legalChar = (illegalChars.find(ch) == docstring::npos))
468 if (chCase == makeLowerCase)
469 val += lowercase(ch);
481 while (ifs && isSpace(ch)) {
489 return val.length() > 0;
492 /// read subsequent bibtex values that are delimited with a #-character.
493 /// Concatenate all parts and replace names with the associated string in
494 /// the variable strings.
495 /// @return true if reading was successfull (all single parts were delimited
497 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
510 } while (ifs && isSpace(ch));
515 // check for field type
516 if (isDigitASCII(ch)) {
518 // read integer value
522 } while (ifs && isDigitASCII(ch));
527 } else if (ch == '"' || ch == '{') {
529 char_type delim = ch == '"' ? '"': '}';
534 } while (ifs && isSpace(ch));
539 // We now have the first non-whitespace character
540 // We'll collapse adjacent whitespace.
541 bool lastWasWhiteSpace = false;
543 // inside this delimited text braces must match.
544 // Thus we can have a closing delimiter only
545 // when nestLevel == 0
548 while (ifs && (nestLevel > 0 || ch != delim)) {
550 lastWasWhiteSpace = true;
554 // We output the space only after we stop getting
555 // whitespace so as not to output any whitespace
556 // at the end of the value.
557 if (lastWasWhiteSpace) {
558 lastWasWhiteSpace = false;
564 // update nesting level
583 // FIXME Why is this here?
591 // reading a string name
594 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
595 strName += lowercase(ch);
602 // replace the string with its assigned value or
603 // discard it if it's not assigned
604 if (strName.length()) {
605 VarMap::const_iterator pos = strings.find(strName);
606 if (pos != strings.end()) {
613 while (ifs && isSpace(ch)) {
620 // continue reading next value on concatenate with '#'
630 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
632 parseBibTeXFiles(checkedFiles);
636 void InsetBibtex::parseBibTeXFiles(FileNameList & checkedFiles) const
638 // This bibtex parser is a first step to parse bibtex files
641 // - it reads the whole bibtex entry and does a syntax check
642 // (matching delimiters, missing commas,...
643 // - it recovers from errors starting with the next @-character
644 // - it reads @string definitions and replaces them in the
646 // - it accepts more characters in keys or value names than
649 // Officially bibtex does only support ASCII, but in practice
650 // you can use the encoding of the main document as long as
651 // some elements like keys and names are pure ASCII. Therefore
652 // we convert the file from the buffer encoding.
653 // We don't restrict keys to ASCII in LyX, since our own
654 // InsetBibitem can generate non-ASCII keys, and nonstandard
655 // 8bit clean bibtex forks exist.
659 FileNamePairList const files = getBibFiles();
660 FileNamePairList::const_iterator it = files.begin();
661 FileNamePairList::const_iterator en = files.end();
662 for (; it != en; ++ it) {
663 FileName const bibfile = it->second;
664 if (find(checkedFiles.begin(), checkedFiles.end(), bibfile) != checkedFiles.end())
665 // already checked this one. Skip.
668 // record that we check this.
669 checkedFiles.push_back(bibfile);
670 ifdocstream ifs(bibfile.toFilesystemEncoding().c_str(),
671 ios_base::in, buffer().masterParams().encoding().iconvName());
687 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
688 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
693 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
697 if (entryType == from_ascii("comment")) {
698 ifs.ignore(numeric_limits<int>::max(), '\n');
704 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
708 if ((ch != '(') && (ch != '{')) {
709 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
715 if (entryType == from_ascii("string")) {
717 // read string and add it to the strings map
718 // (or replace it's old value)
722 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
723 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
728 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
732 // next char must be an equal sign
734 if (!ifs || ch != '=') {
735 lyxerr << "BibTeX Parser: No `=' after string name: " <<
736 name << "." << std::endl;
740 if (!readValue(value, ifs, strings)) {
741 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
742 name << "." << std::endl;
746 strings[name] = value;
748 } else if (entryType == from_ascii("preamble")) {
750 // preamble definitions are discarded.
751 // can they be of any use in lyx?
754 if (!readValue(value, ifs, strings)) {
755 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
761 // Citation entry. Try to read the key.
764 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
765 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
766 entryType << "." << std::endl;
771 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
775 /////////////////////////////////////////////
776 // now we have a key, so we will add an entry
777 // (even if it's empty, as bibtex does)
779 // we now read the field = value pairs.
780 // all items must be separated by a comma. If
781 // it is missing the scanning of this entry is
782 // stopped and the next is searched.
786 BibTeXInfo keyvalmap(key, entryType);
788 bool readNext = removeWSAndComma(ifs);
790 while (ifs && readNext) {
793 if (!readTypeOrKey(name, ifs, from_ascii("="),
794 from_ascii("{}(),"), makeLowerCase) || !ifs)
797 // next char must be an equal sign
798 // FIXME Whitespace??
801 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
805 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
806 name << ", for key: " << key << "." << std::endl;
812 if (!readValue(value, ifs, strings)) {
813 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
814 name << ", for key: " << key << "." << std::endl;
818 keyvalmap[name] = value;
819 data += "\n\n" + value;
820 keylist.addFieldName(name);
821 readNext = removeWSAndComma(ifs);
825 keylist.addEntryType(entryType);
826 keyvalmap.setAllData(data);
827 keylist[key] = keyvalmap;
828 } //< else (citation entry)
830 } //< for loop over files
832 buffer().addBiblioInfo(keylist);
836 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
838 string texfile = changeExtension(to_utf8(filename), "bib");
839 // note that, if the filename can be found directly from the path,
840 // findtexfile will just return a FileName object for that path.
841 FileName file(findtexfile(texfile, "bib"));
843 file = FileName(makeAbsPath(texfile, buf.filePath()));
848 bool InsetBibtex::addDatabase(docstring const & db)
850 docstring bibfiles = getParam("bibfiles");
851 if (tokenPos(bibfiles, ',', db) != -1)
853 if (!bibfiles.empty())
855 setParam("bibfiles", bibfiles + db);
860 bool InsetBibtex::delDatabase(docstring const & db)
862 docstring bibfiles = getParam("bibfiles");
863 if (contains(bibfiles, db)) {
864 int const n = tokenPos(bibfiles, ',', db);
867 // this is not the first database
868 docstring tmp = ',' + bd;
869 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
871 // this is the first (or only) database
872 setParam("bibfiles", split(bibfiles, bd, ','));
880 void InsetBibtex::validate(LaTeXFeatures & features) const
882 BufferParams const & mparams = features.buffer().masterParams();
883 if (mparams.useBibtopic())
884 features.require("bibtopic");
885 else if (!mparams.useBiblatex() && mparams.multibib == "child")
886 features.require("chapterbib");
888 // It'd be better to be able to get this from an InsetLayout, but at present
889 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
890 if (features.runparams().flavor == OutputParams::HTML)
891 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
892 "span.bibtexlabel:before{ content: \"[\"; }\n"
893 "span.bibtexlabel:after{ content: \"] \"; }");
897 void InsetBibtex::updateBuffer(ParIterator const &, UpdateType) {
898 buffer().registerBibfiles(getBibFiles());
902 int InsetBibtex::plaintext(odocstringstream & os,
903 OutputParams const & op, size_t max_length) const
905 docstring const reflabel = buffer().B_("References");
907 // We could output more information here, e.g., what databases are included
908 // and information about options. But I don't necessarily see any reason to
909 // do this right now.
910 if (op.for_tooltip || op.for_toc || op.for_search) {
911 os << '[' << reflabel << ']' << '\n';
912 return PLAINTEXT_NEWLINE;
915 BiblioInfo bibinfo = buffer().masterBibInfo();
916 bibinfo.makeCitationLabels(buffer());
917 vector<docstring> const & cites = bibinfo.citedEntries();
919 size_t start_size = os.str().size();
921 refoutput += reflabel + "\n\n";
923 // Tell BiblioInfo our purpose
925 ci.context = CiteItem::Export;
927 // Now we loop over the entries
928 vector<docstring>::const_iterator vit = cites.begin();
929 vector<docstring>::const_iterator const ven = cites.end();
930 for (; vit != ven; ++vit) {
931 if (start_size + refoutput.size() >= max_length)
933 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
934 if (biit == bibinfo.end())
936 BibTeXInfo const & entry = biit->second;
937 refoutput += "[" + entry.label() + "] ";
938 // FIXME Right now, we are calling BibInfo::getInfo on the key,
939 // which will give us all the cross-referenced info. But for every
940 // entry, so there's a lot of repitition. This should be fixed.
941 refoutput += bibinfo.getInfo(entry.key(), buffer(), ci) + "\n\n";
944 return refoutput.size();
949 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
950 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
951 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
953 BiblioInfo const & bibinfo = buffer().masterBibInfo();
954 bool const all_entries = getParam("btprint") == "btPrintAll";
955 vector<docstring> const & cites =
956 all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
958 docstring const reflabel = buffer().B_("References");
960 // tell BiblioInfo our purpose
962 ci.context = CiteItem::Export;
964 ci.max_key_size = UINT_MAX;
966 xs << html::StartTag("h2", "class='bibtex'")
968 << html::EndTag("h2")
969 << html::StartTag("div", "class='bibtex'");
971 // Now we loop over the entries
972 vector<docstring>::const_iterator vit = cites.begin();
973 vector<docstring>::const_iterator const ven = cites.end();
974 for (; vit != ven; ++vit) {
975 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
976 if (biit == bibinfo.end())
979 BibTeXInfo const & entry = biit->second;
980 string const attr = "class='bibtexentry' id='LyXCite-"
981 + to_utf8(html::cleanAttr(entry.key())) + "'";
982 xs << html::StartTag("div", attr);
984 // don't print labels if we're outputting all entries
986 xs << html::StartTag("span", "class='bibtexlabel'")
988 << html::EndTag("span");
991 // FIXME Right now, we are calling BibInfo::getInfo on the key,
992 // which will give us all the cross-referenced info. But for every
993 // entry, so there's a lot of repitition. This should be fixed.
994 xs << html::StartTag("span", "class='bibtexinfo'")
995 << XHTMLStream::ESCAPE_AND
996 << bibinfo.getInfo(entry.key(), buffer(), ci)
997 << html::EndTag("span")
998 << html::EndTag("div")
1001 xs << html::EndTag("div");
1006 void InsetBibtex::write(ostream & os) const
1008 params().Write(os, &buffer());
1012 string InsetBibtex::contextMenuName() const
1014 return "context-bibtex";