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"
17 #include "BufferParams.h"
18 #include "DispatchResult.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "LaTeXFeatures.h"
24 #include "MetricsInfo.h"
25 #include "output_xhtml.h"
26 #include "OutputParams.h"
27 #include "TextClass.h"
28 #include "TocBackend.h"
30 #include "frontends/alert.h"
32 #include "support/convert.h"
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/ExceptionMessage.h"
36 #include "support/filetools.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
39 #include "support/os.h"
40 #include "support/Path.h"
41 #include "support/textutils.h"
46 using namespace lyx::support;
50 namespace Alert = frontend::Alert;
51 namespace os = support::os;
54 InsetBibtex::InsetBibtex(Buffer const & buf, InsetCommandParams const & p)
55 : InsetCommand(p, "bibtex")
57 Inset::setBuffer(const_cast<Buffer &>(buf));
58 buffer_->invalidateBibinfoCache();
62 InsetBibtex::~InsetBibtex()
65 buffer_->invalidateBibinfoCache();
69 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
71 static ParamInfo param_info_;
72 if (param_info_.empty()) {
73 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
74 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
75 param_info_.add("options", ParamInfo::LYX_INTERNAL);
81 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
89 case LFUN_INSET_MODIFY: {
90 InsetCommandParams p(BIBTEX_CODE);
92 if (!InsetCommand::string2params("bibtex",
93 to_utf8(cmd.argument()), p)) {
97 } catch (ExceptionMessage const & message) {
98 if (message.type_ == WarningException) {
99 Alert::warning(message.title_, message.details_);
107 buffer().updateBibfilesCache();
112 InsetCommand::doDispatch(cur, cmd);
118 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
119 FuncStatus & flag) const
121 switch (cmd.action) {
122 case LFUN_INSET_EDIT:
123 flag.setEnabled(true);
127 return InsetCommand::getStatus(cur, cmd, flag);
132 void InsetBibtex::editDatabases() const
134 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
136 if (bibfilelist.empty())
139 int nr_databases = bibfilelist.size();
140 if (nr_databases > 1) {
141 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
142 "If you proceed, all of them will be opened."),
143 convert<docstring>(nr_databases));
144 int const ret = Alert::prompt(_("Open Databases?"),
145 message, 0, 1, _("&Cancel"), _("&Proceed"));
151 vector<docstring>::const_iterator it = bibfilelist.begin();
152 vector<docstring>::const_iterator en = bibfilelist.end();
153 for (; it != en; ++it) {
154 FileName bibfile = getBibTeXPath(*it, buffer());
155 formats.edit(buffer(), bibfile,
156 formats.getFormatFromFile(bibfile));
161 docstring InsetBibtex::screenLabel() const
163 return _("BibTeX Generated Bibliography");
167 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
169 docstring item = from_ascii("* ");
170 docstring tip = _("Databases:") + "\n";
171 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
173 if (bibfilelist.empty()) {
177 vector<docstring>::const_iterator it = bibfilelist.begin();
178 vector<docstring>::const_iterator en = bibfilelist.end();
179 for (; it != en; ++it) {
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 tip += _("Style File:") +"\n";
202 tip += "\n" + _("Lists:") + " ";
203 docstring btprint = getParam("btprint");
204 if (btprint == "btPrintAll")
205 tip += _("all references");
206 else if (btprint == "btPrintNotCited")
207 tip += _("all uncited references");
209 tip += _("all cited references");
213 tip += _("included in TOC");
220 static string normalizeName(Buffer const & buffer,
221 OutputParams const & runparams, string const & name, string const & ext)
223 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
224 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
230 return to_utf8(makeRelPath(from_utf8(fname),
231 from_utf8(buffer.masterBuffer()->filePath())));
235 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
237 // the sequence of the commands:
238 // 1. \bibliographystyle{style}
239 // 2. \addcontentsline{...} - if option bibtotoc set
240 // 3. \bibliography{database}
241 // and with bibtopic:
242 // 1. \bibliographystyle{style}
243 // 2. \begin{btSect}{database}
244 // 3. \btPrint{Cited|NotCited|All}
248 // If we are processing the LaTeX file in a temp directory then
249 // copy the .bib databases to this temp directory, mangling their
250 // names in the process. Store this mangled name in the list of
252 // (We need to do all this because BibTeX *really*, *really*
253 // can't handle "files with spaces" and Windows users tend to
254 // use such filenames.)
255 // Otherwise, store the (maybe absolute) path to the original,
256 // unmangled database name.
257 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
258 vector<docstring>::const_iterator it = bibfilelist.begin();
259 vector<docstring>::const_iterator en = bibfilelist.end();
260 odocstringstream dbs;
263 for (; it != en; ++it) {
264 string utf8input = to_utf8(*it);
266 normalizeName(buffer(), runparams, utf8input, ".bib");
267 FileName const try_in_file =
268 makeAbsPath(database + ".bib", buffer().filePath());
269 bool const not_from_texmf = try_in_file.isReadableFile();
271 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
273 // mangledFilename() needs the extension
274 DocFileName const in_file = DocFileName(try_in_file);
275 database = removeExtension(in_file.mangledFilename());
276 FileName const out_file = makeAbsPath(database + ".bib",
277 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 !isValidLaTeXFilename(database)) {
287 frontend::Alert::warning(_("Invalid filename"),
288 _("The following filename is likely to cause trouble "
289 "when running the exported file through LaTeX: ") +
290 from_utf8(database));
298 dbs << from_utf8(latex_path(database));
300 docstring const db_out = dbs.str();
302 // Post this warning only once.
303 static bool warned_about_spaces = false;
304 if (!warned_about_spaces &&
305 runparams.nice && db_out.find(' ') != docstring::npos) {
306 warned_about_spaces = true;
307 Alert::warning(_("Export Warning!"),
308 _("There are spaces in the paths to your BibTeX databases.\n"
309 "BibTeX will be unable to find them."));
312 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
314 if (prefixIs(style, "bibtotoc")) {
315 bibtotoc = "bibtotoc";
316 if (contains(style, ','))
317 style = split(style, bibtotoc, ',');
323 if (!style.empty()) {
324 string base = normalizeName(buffer(), runparams, style, ".bst");
325 FileName const try_in_file =
326 makeAbsPath(base + ".bst", buffer().filePath());
327 bool const not_from_texmf = try_in_file.isReadableFile();
328 // If this style does not come from texmf and we are not
329 // exporting to .tex copy it to the tmp directory.
330 // This prevents problems with spaces and 8bit charcaters
332 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
334 // use new style name
335 DocFileName const in_file = DocFileName(try_in_file);
336 base = removeExtension(in_file.mangledFilename());
337 FileName const out_file = makeAbsPath(base + ".bst",
338 buffer().masterBuffer()->temppath());
339 bool const success = in_file.copyTo(out_file);
341 lyxerr << "Failed to copy '" << in_file
342 << "' to '" << out_file << "'"
347 os << "\\bibliographystyle{"
348 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
353 // Post this warning only once.
354 static bool warned_about_bst_spaces = false;
355 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
356 warned_about_bst_spaces = true;
357 Alert::warning(_("Export Warning!"),
358 _("There are spaces in the path to your BibTeX style file.\n"
359 "BibTeX will be unable to find it."));
362 if (!db_out.empty() && buffer().params().use_bibtopic) {
363 os << "\\begin{btSect}{" << db_out << "}\n";
364 docstring btprint = getParam("btprint");
367 btprint = from_ascii("btPrintCited");
368 os << "\\" << btprint << "\n"
369 << "\\end{btSect}\n";
374 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
375 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
376 if (buffer().params().sides == OneSide) {
381 os << "\\cleardoublepage";
383 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
384 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
385 os << "\\addcontentsline{toc}{section}{\\refname}";
388 if (!db_out.empty() && !buffer().params().use_bibtopic) {
389 docstring btprint = getParam("btprint");
390 if (btprint == "btPrintAll") {
391 os << "\\nocite{*}\n";
394 os << "\\bibliography{" << db_out << "}\n";
402 support::FileNameList InsetBibtex::getBibFiles() const
404 FileName path(buffer().filePath());
405 support::PathChanger p(path);
407 support::FileNameList vec;
409 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
410 vector<docstring>::const_iterator it = bibfilelist.begin();
411 vector<docstring>::const_iterator en = bibfilelist.end();
412 for (; it != en; ++it) {
413 FileName const file = getBibTeXPath(*it, buffer());
418 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
427 // methods for parsing bibtex files
429 typedef map<docstring, docstring> VarMap;
431 /// remove whitespace characters, optionally a single comma,
432 /// and further whitespace characters from the stream.
433 /// @return true if a comma was found, false otherwise
435 bool removeWSAndComma(ifdocstream & ifs) {
444 } while (ifs && isSpace(ch));
457 } while (ifs && isSpace(ch));
472 /// remove whitespace characters, read characer sequence
473 /// not containing whitespace characters or characters in
474 /// delimChars, and remove further whitespace characters.
476 /// @return true if a string of length > 0 could be read.
478 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
479 docstring const & delimChars, docstring const &illegalChars,
492 } while (ifs && isSpace(ch));
498 bool legalChar = true;
499 while (ifs && !isSpace(ch) &&
500 delimChars.find(ch) == docstring::npos &&
501 (legalChar = (illegalChars.find(ch) == docstring::npos))
504 if (chCase == makeLowerCase)
505 val += lowercase(ch);
517 while (ifs && isSpace(ch)) {
525 return val.length() > 0;
528 /// read subsequent bibtex values that are delimited with a #-character.
529 /// Concatenate all parts and replace names with the associated string in
530 /// the variable strings.
531 /// @return true if reading was successfull (all single parts were delimited
533 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
546 } while (ifs && isSpace(ch));
551 // check for field type
554 // read integer value
558 } while (ifs && isDigit(ch));
563 } else if (ch == '"' || ch == '{') {
565 char_type delim = ch == '"' ? '"': '}';
570 } while (ifs && isSpace(ch));
575 // We now have the first non-whitespace character
576 // We'll collapse adjacent whitespace.
577 bool lastWasWhiteSpace = false;
579 // inside this delimited text braces must match.
580 // Thus we can have a closing delimiter only
581 // when nestLevel == 0
584 while (ifs && (nestLevel > 0 || ch != delim)) {
586 lastWasWhiteSpace = true;
590 // We output the space only after we stop getting
591 // whitespace so as not to output any whitespace
592 // at the end of the value.
593 if (lastWasWhiteSpace) {
594 lastWasWhiteSpace = false;
600 // update nesting level
607 if (nestLevel < 0) return false;
624 // reading a string name
627 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
628 strName += lowercase(ch);
635 // replace the string with its assigned value or
636 // discard it if it's not assigned
637 if (strName.length()) {
638 VarMap::const_iterator pos = strings.find(strName);
639 if (pos != strings.end()) {
646 while (ifs && isSpace(ch)) {
653 // continue reading next value on concatenate with '#'
663 // This method returns a comma separated list of Bibtex entries
664 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
665 InsetIterator const & /*di*/) const
667 // This bibtex parser is a first step to parse bibtex files
670 // - it reads the whole bibtex entry and does a syntax check
671 // (matching delimiters, missing commas,...
672 // - it recovers from errors starting with the next @-character
673 // - it reads @string definitions and replaces them in the
675 // - it accepts more characters in keys or value names than
678 // Officially bibtex does only support ASCII, but in practice
679 // you can use the encoding of the main document as long as
680 // some elements like keys and names are pure ASCII. Therefore
681 // we convert the file from the buffer encoding.
682 // We don't restrict keys to ASCII in LyX, since our own
683 // InsetBibitem can generate non-ASCII keys, and nonstandard
684 // 8bit clean bibtex forks exist.
685 support::FileNameList const files = getBibFiles();
686 support::FileNameList::const_iterator it = files.begin();
687 support::FileNameList::const_iterator en = files.end();
688 for (; it != en; ++ it) {
689 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
690 ios_base::in, buffer().params().encoding().iconvName());
706 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
707 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
712 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
716 if (entryType == from_ascii("comment")) {
717 ifs.ignore(numeric_limits<int>::max(), '\n');
723 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
727 if ((ch != '(') && (ch != '{')) {
728 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
734 if (entryType == from_ascii("string")) {
736 // read string and add it to the strings map
737 // (or replace it's old value)
741 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
742 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
747 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
751 // next char must be an equal sign
753 if (!ifs || ch != '=') {
754 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
755 name << "." << std::endl;
759 if (!readValue(value, ifs, strings)) {
760 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
761 name << "." << std::endl;
765 strings[name] = value;
767 } else if (entryType == from_ascii("preamble")) {
769 // preamble definitions are discarded.
770 // can they be of any use in lyx?
773 if (!readValue(value, ifs, strings)) {
774 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
780 // Citation entry. Try to read the key.
783 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
784 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
785 entryType << "." << std::endl;
790 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
794 /////////////////////////////////////////////
795 // now we have a key, so we will add an entry
796 // (even if it's empty, as bibtex does)
798 // we now read the field = value pairs.
799 // all items must be separated by a comma. If
800 // it is missing the scanning of this entry is
801 // stopped and the next is searched.
805 docstring commaNewline;
807 BibTeXInfo keyvalmap(key, entryType);
809 bool readNext = removeWSAndComma(ifs);
811 while (ifs && readNext) {
814 if (!readTypeOrKey(name, ifs, from_ascii("="),
815 from_ascii("{}(),"), makeLowerCase) || !ifs)
818 // next char must be an equal sign
821 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
825 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
826 name << ", for key: " << key << "." << std::endl;
832 if (!readValue(value, ifs, strings)) {
833 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
834 name << ", for key: " << key << "." << std::endl;
838 keyvalmap[name] = value;
839 data += "\n\n" + value;
840 keylist.addFieldName(name);
841 readNext = removeWSAndComma(ifs);
845 keylist.addEntryType(entryType);
846 keyvalmap.setAllData(data);
847 keylist[key] = keyvalmap;
848 } //< else (citation entry)
850 } //< for loop over files
854 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
856 string texfile = changeExtension(to_utf8(filename), "bib");
857 // note that, if the filename can be found directly from the path,
858 // findtexfile will just return a FileName object for that path.
859 FileName file(findtexfile(texfile, "bib"));
861 file = FileName(makeAbsPath(texfile, buf.filePath()));
866 bool InsetBibtex::addDatabase(docstring const & db)
868 docstring bibfiles = getParam("bibfiles");
869 if (tokenPos(bibfiles, ',', db) != -1)
871 if (!bibfiles.empty())
873 setParam("bibfiles", bibfiles + db);
878 bool InsetBibtex::delDatabase(docstring const & db)
880 docstring bibfiles = getParam("bibfiles");
881 if (contains(bibfiles, db)) {
882 int const n = tokenPos(bibfiles, ',', db);
885 // this is not the first database
886 docstring tmp = ',' + bd;
887 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
889 // this is the first (or only) database
890 setParam("bibfiles", split(bibfiles, bd, ','));
898 void InsetBibtex::validate(LaTeXFeatures & features) const
900 if (features.bufferParams().use_bibtopic)
901 features.require("bibtopic");
906 // used in xhtml to sort a list of BibTeXInfo objects
907 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
909 return lhs->getAbbreviatedAuthor() < rhs->getAbbreviatedAuthor();
914 docstring InsetBibtex::xhtml(odocstream & os, OutputParams const &) const
916 // We are going to collect all the citation keys used in the document,
917 // getting them from the TOC.
918 Toc const & toc = buffer().tocBackend().toc("citation");
919 Toc::const_iterator it = toc.begin();
920 Toc::const_iterator en = toc.end();
921 vector<docstring> citekeys;
922 for (; it != en; ++it) {
923 if (it->str().empty())
925 vector<docstring> keys = getVectorFromString(it->str());
926 vector<docstring>::const_iterator dit = keys.begin();
927 vector<docstring>::const_iterator den = keys.end();
928 for (; dit != den; ++dit)
929 citekeys.push_back(*dit);
931 if (citekeys.empty())
933 sort(citekeys.begin(), citekeys.end());
934 unique(citekeys.begin(), citekeys.end());
935 // We now have a sorted, unique list of the keys used in this document.
936 // We will now convert it to a list of the BibTeXInfo objects used in
938 // FIXME We need to do something here about cross-references, if we
939 // want to be able to display them AS cross-references. Probably the
940 // easiest thing to do is to loop over the list again and add whatever
941 // cross-references we find, then sort and unique it, planning just to
942 // add the cross-references to the bibliography.
943 vector<BibTeXInfo const *> binfo;
944 vector<docstring>::const_iterator cit = citekeys.begin();
945 vector<docstring>::const_iterator cen = citekeys.end();
946 BiblioInfo const & bi = buffer().masterBibInfo();
947 for (; cit != cen; ++cit) {
948 BiblioInfo::const_iterator bt = bi.find(*cit);
951 binfo.push_back(&(bt->second));
954 sort(binfo.begin(), binfo.end(), lSorter);
955 // Finally, then, we are ready for output.
956 os << "<h2 class='bibliography'>" << _("References") << "</h2>\n";
957 os << "<div class='bibliography'>\n";
958 vector<BibTeXInfo const *>::const_iterator vit = binfo.begin();
959 vector<BibTeXInfo const *>::const_iterator ven = binfo.end();
960 // Now we loop over the entries
961 for (; vit != ven; ++vit) {
962 BibTeXInfo const * bip = *vit;
963 os << "<p class='bibliography'>";
964 os << "<a name='" << html::htmlize(bip->key()) << "'></a>";
965 docstring label = bip->label();
968 os << "<span class='biblabel'>[" << label << "]</span> ";
969 // FIXME Right now, we are calling BibInfo::getInfo on the key,
970 // which will give us all the cross-referenced info. But for every
972 os << "<span class='bibinfo'>" << bi.getInfo(bip->key()) << "</span>";
981 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
983 return from_ascii("context-bibtex");