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)
9 * Full author contact details are available in file CREDITS.
14 #include "InsetBibtex.h"
16 #include "BiblioInfo.h"
18 #include "BufferParams.h"
20 #include "DispatchResult.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "output_xhtml.h"
28 #include "OutputParams.h"
29 #include "PDFOptions.h"
30 #include "TextClass.h"
32 #include "frontends/alert.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/ExceptionMessage.h"
38 #include "support/FileNameList.h"
39 #include "support/filetools.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/os.h"
43 #include "support/PathChanger.h"
44 #include "support/textutils.h"
49 using namespace lyx::support;
53 namespace Alert = frontend::Alert;
54 namespace os = support::os;
57 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
58 : InsetCommand(buf, p)
60 buffer().invalidateBibfileCache();
61 buffer().removeBiblioTempFiles();
65 InsetBibtex::~InsetBibtex()
67 if (isBufferLoaded()) {
68 buffer().invalidateBibfileCache();
69 buffer().removeBiblioTempFiles();
74 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
76 static ParamInfo param_info_;
77 if (param_info_.empty()) {
78 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
79 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
80 param_info_.add("options", ParamInfo::LYX_INTERNAL);
86 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
88 switch (cmd.action()) {
94 case LFUN_INSET_MODIFY: {
95 InsetCommandParams p(BIBTEX_CODE);
97 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
101 } catch (ExceptionMessage const & message) {
102 if (message.type_ == WarningException) {
103 Alert::warning(message.title_, message.details_);
104 cur.noScreenUpdate();
112 buffer().invalidateBibfileCache();
113 buffer().removeBiblioTempFiles();
114 cur.forceBufferUpdate();
119 InsetCommand::doDispatch(cur, cmd);
125 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
126 FuncStatus & flag) const
128 switch (cmd.action()) {
129 case LFUN_INSET_EDIT:
130 flag.setEnabled(true);
134 return InsetCommand::getStatus(cur, cmd, flag);
139 void InsetBibtex::editDatabases() const
141 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
143 if (bibfilelist.empty())
146 int nr_databases = bibfilelist.size();
147 if (nr_databases > 1) {
148 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
149 "If you proceed, all of them will be opened."),
150 convert<docstring>(nr_databases));
151 int const ret = Alert::prompt(_("Open Databases?"),
152 message, 0, 1, _("&Cancel"), _("&Proceed"));
158 vector<docstring>::const_iterator it = bibfilelist.begin();
159 vector<docstring>::const_iterator en = bibfilelist.end();
160 for (; it != en; ++it) {
161 FileName const bibfile = getBibTeXPath(*it, buffer());
162 formats.edit(buffer(), bibfile,
163 formats.getFormatFromFile(bibfile));
168 docstring InsetBibtex::screenLabel() const
170 return _("BibTeX Generated Bibliography");
174 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
176 docstring tip = _("Databases:");
177 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
180 if (bibfilelist.empty())
181 tip += "<li>" + _("none") + "</li>";
183 for (docstring const & bibfile : bibfilelist)
184 tip += "<li>" + bibfile + "</li>";
189 docstring style = getParam("options"); // maybe empty! and with bibtotoc
190 docstring bibtotoc = from_ascii("bibtotoc");
191 if (prefixIs(style, bibtotoc)) {
193 if (contains(style, char_type(',')))
194 style = split(style, bibtotoc, char_type(','));
197 tip += _("Style File:");
198 tip += "<ul><li>" + (style.empty() ? _("none") : style) + "</li></ul>";
200 tip += _("Lists:") + " ";
201 docstring btprint = getParam("btprint");
202 if (btprint == "btPrintAll")
203 tip += _("all references");
204 else if (btprint == "btPrintNotCited")
205 tip += _("all uncited references");
207 tip += _("all cited references");
211 tip += _("included in TOC");
218 static string normalizeName(Buffer const & buffer,
219 OutputParams const & runparams, string const & name, string const & ext)
221 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
222 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
228 return to_utf8(makeRelPath(from_utf8(fname),
229 from_utf8(buffer.masterBuffer()->filePath())));
233 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
235 // the sequence of the commands:
236 // 1. \bibliographystyle{style}
237 // 2. \addcontentsline{...} - if option bibtotoc set
238 // 3. \bibliography{database}
239 // and with bibtopic:
240 // 1. \bibliographystyle{style}
241 // 2. \begin{btSect}{database}
242 // 3. \btPrint{Cited|NotCited|All}
246 // If we are processing the LaTeX file in a temp directory then
247 // copy the .bib databases to this temp directory, mangling their
248 // names in the process. Store this mangled name in the list of
250 // (We need to do all this because BibTeX *really*, *really*
251 // can't handle "files with spaces" and Windows users tend to
252 // use such filenames.)
253 // Otherwise, store the (maybe absolute) path to the original,
254 // unmangled database name.
255 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
256 vector<docstring>::const_iterator it = bibfilelist.begin();
257 vector<docstring>::const_iterator en = bibfilelist.end();
258 odocstringstream dbs;
261 // determine the export format
262 string const tex_format = flavor2format(runparams.flavor);
264 for (; it != en; ++it) {
265 string utf8input = to_utf8(*it);
267 normalizeName(buffer(), runparams, utf8input, ".bib");
268 FileName const try_in_file =
269 makeAbsPath(database + ".bib", buffer().filePath());
270 bool const not_from_texmf = try_in_file.isReadableFile();
272 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
274 // mangledFileName() needs the extension
275 DocFileName const in_file = DocFileName(try_in_file);
276 database = removeExtension(in_file.mangledFileName());
277 FileName const out_file = makeAbsPath(database + ".bib",
278 buffer().masterBuffer()->temppath());
279 bool const success = in_file.copyTo(out_file);
281 lyxerr << "Failed to copy '" << in_file
282 << "' to '" << out_file << "'"
285 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
286 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
287 if (!isValidLaTeXFileName(database)) {
288 frontend::Alert::warning(_("Invalid filename"),
289 _("The following filename will cause troubles "
290 "when running the exported file through LaTeX: ") +
291 from_utf8(database));
293 if (!isValidDVIFileName(database)) {
294 frontend::Alert::warning(_("Problematic filename for DVI"),
295 _("The following filename can cause troubles "
296 "when running the exported file through LaTeX "
297 "and opening the resulting DVI: ") +
298 from_utf8(database), true);
307 dbs << from_utf8(latex_path(database));
309 docstring const db_out = dbs.str();
311 // Post this warning only once.
312 static bool warned_about_spaces = false;
313 if (!warned_about_spaces &&
314 runparams.nice && db_out.find(' ') != docstring::npos) {
315 warned_about_spaces = true;
316 Alert::warning(_("Export Warning!"),
317 _("There are spaces in the paths to your BibTeX databases.\n"
318 "BibTeX will be unable to find them."));
321 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
323 if (prefixIs(style, "bibtotoc")) {
324 bibtotoc = "bibtotoc";
325 if (contains(style, ','))
326 style = split(style, bibtotoc, ',');
329 if (style == "default")
330 style = buffer().params().biblio_style;
332 if (!style.empty() && !buffer().params().use_bibtopic) {
333 string base = normalizeName(buffer(), runparams, style, ".bst");
334 FileName const try_in_file =
335 makeAbsPath(base + ".bst", buffer().filePath());
336 bool const not_from_texmf = try_in_file.isReadableFile();
337 // If this style does not come from texmf and we are not
338 // exporting to .tex copy it to the tmp directory.
339 // This prevents problems with spaces and 8bit charcaters
341 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
343 // use new style name
344 DocFileName const in_file = DocFileName(try_in_file);
345 base = removeExtension(in_file.mangledFileName());
346 FileName const out_file = makeAbsPath(base + ".bst",
347 buffer().masterBuffer()->temppath());
348 bool const success = in_file.copyTo(out_file);
350 lyxerr << "Failed to copy '" << in_file
351 << "' to '" << out_file << "'"
356 os << "\\bibliographystyle{"
357 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
361 // Post this warning only once.
362 static bool warned_about_bst_spaces = false;
363 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
364 warned_about_bst_spaces = true;
365 Alert::warning(_("Export Warning!"),
366 _("There are spaces in the path to your BibTeX style file.\n"
367 "BibTeX will be unable to find it."));
370 if (!db_out.empty() && buffer().params().use_bibtopic) {
371 os << "\\begin{btSect}";
373 os << "[" << style << "]";
374 os << "{" << db_out << "}\n";
375 docstring btprint = getParam("btprint");
378 btprint = from_ascii("btPrintCited");
379 os << "\\" << btprint << "\n"
380 << "\\end{btSect}\n";
384 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
385 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
386 if (buffer().params().pdfoptions().use_hyperref)
387 os << "\\phantomsection";
388 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
389 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
390 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
391 os << "\\addcontentsline{toc}{section}{\\refname}";
394 if (!db_out.empty() && !buffer().params().use_bibtopic) {
395 docstring btprint = getParam("btprint");
396 if (btprint == "btPrintAll") {
397 os << "\\nocite{*}\n";
399 os << "\\bibliography{" << db_out << "}\n";
404 support::FileNameList InsetBibtex::getBibFiles() const
406 FileName path(buffer().filePath());
407 support::PathChanger p(path);
409 support::FileNameList vec;
411 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
412 vector<docstring>::const_iterator it = bibfilelist.begin();
413 vector<docstring>::const_iterator en = bibfilelist.end();
414 for (; it != en; ++it) {
415 FileName const file = getBibTeXPath(*it, buffer());
420 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
429 // methods for parsing bibtex files
431 typedef map<docstring, docstring> VarMap;
433 /// remove whitespace characters, optionally a single comma,
434 /// and further whitespace characters from the stream.
435 /// @return true if a comma was found, false otherwise
437 bool removeWSAndComma(ifdocstream & ifs) {
446 } while (ifs && isSpace(ch));
459 } while (ifs && isSpace(ch));
474 /// remove whitespace characters, read characer sequence
475 /// not containing whitespace characters or characters in
476 /// delimChars, and remove further whitespace characters.
478 /// @return true if a string of length > 0 could be read.
480 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
481 docstring const & delimChars, docstring const & illegalChars,
494 } while (ifs && isSpace(ch));
500 bool legalChar = true;
501 while (ifs && !isSpace(ch) &&
502 delimChars.find(ch) == docstring::npos &&
503 (legalChar = (illegalChars.find(ch) == docstring::npos))
506 if (chCase == makeLowerCase)
507 val += lowercase(ch);
519 while (ifs && isSpace(ch)) {
527 return val.length() > 0;
530 /// read subsequent bibtex values that are delimited with a #-character.
531 /// Concatenate all parts and replace names with the associated string in
532 /// the variable strings.
533 /// @return true if reading was successfull (all single parts were delimited
535 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
548 } while (ifs && isSpace(ch));
553 // check for field type
554 if (isDigitASCII(ch)) {
556 // read integer value
560 } while (ifs && isDigitASCII(ch));
565 } else if (ch == '"' || ch == '{') {
567 char_type delim = ch == '"' ? '"': '}';
572 } while (ifs && isSpace(ch));
577 // We now have the first non-whitespace character
578 // We'll collapse adjacent whitespace.
579 bool lastWasWhiteSpace = false;
581 // inside this delimited text braces must match.
582 // Thus we can have a closing delimiter only
583 // when nestLevel == 0
586 while (ifs && (nestLevel > 0 || ch != delim)) {
588 lastWasWhiteSpace = true;
592 // We output the space only after we stop getting
593 // whitespace so as not to output any whitespace
594 // at the end of the value.
595 if (lastWasWhiteSpace) {
596 lastWasWhiteSpace = false;
602 // update nesting level
621 // FIXME Why is this here?
629 // reading a string name
632 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
633 strName += lowercase(ch);
640 // replace the string with its assigned value or
641 // discard it if it's not assigned
642 if (strName.length()) {
643 VarMap::const_iterator pos = strings.find(strName);
644 if (pos != strings.end()) {
651 while (ifs && isSpace(ch)) {
658 // continue reading next value on concatenate with '#'
668 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
674 void InsetBibtex::parseBibTeXFiles() const
676 // This bibtex parser is a first step to parse bibtex files
679 // - it reads the whole bibtex entry and does a syntax check
680 // (matching delimiters, missing commas,...
681 // - it recovers from errors starting with the next @-character
682 // - it reads @string definitions and replaces them in the
684 // - it accepts more characters in keys or value names than
687 // Officially bibtex does only support ASCII, but in practice
688 // you can use the encoding of the main document as long as
689 // some elements like keys and names are pure ASCII. Therefore
690 // we convert the file from the buffer encoding.
691 // We don't restrict keys to ASCII in LyX, since our own
692 // InsetBibitem can generate non-ASCII keys, and nonstandard
693 // 8bit clean bibtex forks exist.
697 support::FileNameList const files = getBibFiles();
698 support::FileNameList::const_iterator it = files.begin();
699 support::FileNameList::const_iterator en = files.end();
700 for (; it != en; ++ it) {
701 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
702 ios_base::in, buffer().params().encoding().iconvName());
718 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
719 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
724 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
728 if (entryType == from_ascii("comment")) {
729 ifs.ignore(numeric_limits<int>::max(), '\n');
735 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
739 if ((ch != '(') && (ch != '{')) {
740 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
746 if (entryType == from_ascii("string")) {
748 // read string and add it to the strings map
749 // (or replace it's old value)
753 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
754 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
759 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
763 // next char must be an equal sign
765 if (!ifs || ch != '=') {
766 lyxerr << "BibTeX Parser: No `=' after string name: " <<
767 name << "." << std::endl;
771 if (!readValue(value, ifs, strings)) {
772 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
773 name << "." << std::endl;
777 strings[name] = value;
779 } else if (entryType == from_ascii("preamble")) {
781 // preamble definitions are discarded.
782 // can they be of any use in lyx?
785 if (!readValue(value, ifs, strings)) {
786 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
792 // Citation entry. Try to read the key.
795 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
796 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
797 entryType << "." << std::endl;
802 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
806 /////////////////////////////////////////////
807 // now we have a key, so we will add an entry
808 // (even if it's empty, as bibtex does)
810 // we now read the field = value pairs.
811 // all items must be separated by a comma. If
812 // it is missing the scanning of this entry is
813 // stopped and the next is searched.
817 BibTeXInfo keyvalmap(key, entryType);
819 bool readNext = removeWSAndComma(ifs);
821 while (ifs && readNext) {
824 if (!readTypeOrKey(name, ifs, from_ascii("="),
825 from_ascii("{}(),"), makeLowerCase) || !ifs)
828 // next char must be an equal sign
829 // FIXME Whitespace??
832 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
836 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
837 name << ", for key: " << key << "." << std::endl;
843 if (!readValue(value, ifs, strings)) {
844 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
845 name << ", for key: " << key << "." << std::endl;
849 keyvalmap[name] = value;
850 data += "\n\n" + value;
851 keylist.addFieldName(name);
852 readNext = removeWSAndComma(ifs);
856 keylist.addEntryType(entryType);
857 keyvalmap.setAllData(data);
858 keylist[key] = keyvalmap;
859 } //< else (citation entry)
861 } //< for loop over files
863 buffer().addBiblioInfo(keylist);
867 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
869 string texfile = changeExtension(to_utf8(filename), "bib");
870 // note that, if the filename can be found directly from the path,
871 // findtexfile will just return a FileName object for that path.
872 FileName file(findtexfile(texfile, "bib"));
874 file = FileName(makeAbsPath(texfile, buf.filePath()));
879 bool InsetBibtex::addDatabase(docstring const & db)
881 docstring bibfiles = getParam("bibfiles");
882 if (tokenPos(bibfiles, ',', db) != -1)
884 if (!bibfiles.empty())
886 setParam("bibfiles", bibfiles + db);
891 bool InsetBibtex::delDatabase(docstring const & db)
893 docstring bibfiles = getParam("bibfiles");
894 if (contains(bibfiles, db)) {
895 int const n = tokenPos(bibfiles, ',', db);
898 // this is not the first database
899 docstring tmp = ',' + bd;
900 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
902 // this is the first (or only) database
903 setParam("bibfiles", split(bibfiles, bd, ','));
911 void InsetBibtex::validate(LaTeXFeatures & features) const
913 if (features.bufferParams().use_bibtopic)
914 features.require("bibtopic");
916 // It'd be better to be able to get this from an InsetLayout, but at present
917 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
918 if (features.runparams().flavor == OutputParams::HTML)
919 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
920 "span.bibtexlabel:before{ content: \"[\"; }\n"
921 "span.bibtexlabel:after{ content: \"] \"; }");
925 int InsetBibtex::plaintext(odocstringstream & os,
926 OutputParams const & op, size_t max_length) const
928 docstring const reflabel = buffer().B_("References");
930 // We could output more information here, e.g., what databases are included
931 // and information about options. But I don't necessarily see any reason to
932 // do this right now.
933 if (op.for_tooltip || op.for_toc || op.for_search) {
934 os << '[' << reflabel << ']' << '\n';
935 return PLAINTEXT_NEWLINE;
938 BiblioInfo bibinfo = buffer().masterBibInfo();
939 bibinfo.makeCitationLabels(buffer());
940 vector<docstring> const & cites = bibinfo.citedEntries();
942 size_t start_size = os.str().size();
944 refoutput += reflabel + "\n\n";
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 if (start_size + refoutput.size() >= max_length)
952 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
953 if (biit == bibinfo.end())
955 BibTeXInfo const & entry = biit->second;
956 refoutput += "[" + entry.label() + "] ";
957 // FIXME Right now, we are calling BibInfo::getInfo on the key,
958 // which will give us all the cross-referenced info. But for every
959 // entry, so there's a lot of repitition. This should be fixed.
960 refoutput += bibinfo.getInfo(entry.key(), buffer(), false) + "\n\n";
963 return refoutput.size();
968 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
969 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
970 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
972 BiblioInfo const & bibinfo = buffer().masterBibInfo();
973 bool const all_entries = getParam("btprint") == "btPrintAll";
974 vector<docstring> const & cites =
975 all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
977 docstring const reflabel = buffer().B_("References");
979 xs << html::StartTag("h2", "class='bibtex'")
981 << html::EndTag("h2")
982 << html::StartTag("div", "class='bibtex'");
984 // Now we loop over the entries
985 vector<docstring>::const_iterator vit = cites.begin();
986 vector<docstring>::const_iterator const ven = cites.end();
987 for (; vit != ven; ++vit) {
988 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
989 if (biit == bibinfo.end())
992 BibTeXInfo const & entry = biit->second;
993 string const attr = "class='bibtexentry' id='LyXCite-"
994 + to_utf8(html::cleanAttr(entry.key())) + "'";
995 xs << html::StartTag("div", attr);
997 // don't print labels if we're outputting all entries
999 xs << html::StartTag("span", "class='bibtexlabel'")
1001 << html::EndTag("span");
1004 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1005 // which will give us all the cross-referenced info. But for every
1006 // entry, so there's a lot of repitition. This should be fixed.
1007 xs << html::StartTag("span", "class='bibtexinfo'")
1008 << XHTMLStream::ESCAPE_AND
1009 << bibinfo.getInfo(entry.key(), buffer(), true)
1010 << html::EndTag("span")
1011 << html::EndTag("div")
1014 xs << html::EndTag("div");
1019 void InsetBibtex::write(ostream & os) const
1021 params().Write(os, &buffer());
1025 string InsetBibtex::contextMenuName() const
1027 return "context-bibtex";