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 * buf, InsetCommandParams const & p)
55 : InsetCommand(buf, p, "bibtex")
57 buffer_->invalidateBibinfoCache();
61 InsetBibtex::~InsetBibtex()
64 buffer_->invalidateBibinfoCache();
68 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
70 static ParamInfo param_info_;
71 if (param_info_.empty()) {
72 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
73 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
74 param_info_.add("options", ParamInfo::LYX_INTERNAL);
80 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
88 case LFUN_INSET_MODIFY: {
89 InsetCommandParams p(BIBTEX_CODE);
91 if (!InsetCommand::string2params("bibtex",
92 to_utf8(cmd.argument()), p)) {
96 } catch (ExceptionMessage const & message) {
97 if (message.type_ == WarningException) {
98 Alert::warning(message.title_, message.details_);
106 buffer().updateBibfilesCache();
111 InsetCommand::doDispatch(cur, cmd);
117 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
118 FuncStatus & flag) const
120 switch (cmd.action) {
121 case LFUN_INSET_EDIT:
122 flag.setEnabled(true);
126 return InsetCommand::getStatus(cur, cmd, flag);
131 void InsetBibtex::editDatabases() const
133 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
135 if (bibfilelist.empty())
138 int nr_databases = bibfilelist.size();
139 if (nr_databases > 1) {
140 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
141 "If you proceed, all of them will be opened."),
142 convert<docstring>(nr_databases));
143 int const ret = Alert::prompt(_("Open Databases?"),
144 message, 0, 1, _("&Cancel"), _("&Proceed"));
150 vector<docstring>::const_iterator it = bibfilelist.begin();
151 vector<docstring>::const_iterator en = bibfilelist.end();
152 for (; it != en; ++it) {
153 FileName bibfile = getBibTeXPath(*it, buffer());
154 formats.edit(buffer(), bibfile,
155 formats.getFormatFromFile(bibfile));
160 docstring InsetBibtex::screenLabel() const
162 return _("BibTeX Generated Bibliography");
166 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
168 docstring item = from_ascii("* ");
169 docstring tip = _("Databases:") + "\n";
170 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
172 if (bibfilelist.empty()) {
176 vector<docstring>::const_iterator it = bibfilelist.begin();
177 vector<docstring>::const_iterator en = bibfilelist.end();
178 for (; it != en; ++it) {
186 docstring style = getParam("options"); // maybe empty! and with bibtotoc
187 docstring bibtotoc = from_ascii("bibtotoc");
188 if (prefixIs(style, bibtotoc)) {
190 if (contains(style, char_type(',')))
191 style = split(style, bibtotoc, char_type(','));
194 tip += _("Style File:") +"\n";
201 tip += "\n" + _("Lists:") + " ";
202 docstring btprint = getParam("btprint");
203 if (btprint == "btPrintAll")
204 tip += _("all references");
205 else if (btprint == "btPrintNotCited")
206 tip += _("all uncited references");
208 tip += _("all cited references");
212 tip += _("included in TOC");
219 static string normalizeName(Buffer const & buffer,
220 OutputParams const & runparams, string const & name, string const & ext)
222 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
223 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
229 return to_utf8(makeRelPath(from_utf8(fname),
230 from_utf8(buffer.masterBuffer()->filePath())));
234 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
236 // the sequence of the commands:
237 // 1. \bibliographystyle{style}
238 // 2. \addcontentsline{...} - if option bibtotoc set
239 // 3. \bibliography{database}
240 // and with bibtopic:
241 // 1. \bibliographystyle{style}
242 // 2. \begin{btSect}{database}
243 // 3. \btPrint{Cited|NotCited|All}
247 // If we are processing the LaTeX file in a temp directory then
248 // copy the .bib databases to this temp directory, mangling their
249 // names in the process. Store this mangled name in the list of
251 // (We need to do all this because BibTeX *really*, *really*
252 // can't handle "files with spaces" and Windows users tend to
253 // use such filenames.)
254 // Otherwise, store the (maybe absolute) path to the original,
255 // unmangled database name.
256 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
257 vector<docstring>::const_iterator it = bibfilelist.begin();
258 vector<docstring>::const_iterator en = bibfilelist.end();
259 odocstringstream dbs;
262 for (; it != en; ++it) {
263 string utf8input = to_utf8(*it);
265 normalizeName(buffer(), runparams, utf8input, ".bib");
266 FileName const try_in_file =
267 makeAbsPath(database + ".bib", buffer().filePath());
268 bool const not_from_texmf = try_in_file.isReadableFile();
270 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
272 // mangledFilename() needs the extension
273 DocFileName const in_file = DocFileName(try_in_file);
274 database = removeExtension(in_file.mangledFilename());
275 FileName const out_file = makeAbsPath(database + ".bib",
276 buffer().masterBuffer()->temppath());
278 bool const success = in_file.copyTo(out_file);
280 lyxerr << "Failed to copy '" << in_file
281 << "' to '" << out_file << "'"
284 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
285 !isValidLaTeXFilename(database)) {
286 frontend::Alert::warning(_("Invalid filename"),
287 _("The following filename is likely to cause trouble "
288 "when running the exported file through LaTeX: ") +
289 from_utf8(database));
297 dbs << from_utf8(latex_path(database));
299 docstring const db_out = dbs.str();
301 // Post this warning only once.
302 static bool warned_about_spaces = false;
303 if (!warned_about_spaces &&
304 runparams.nice && db_out.find(' ') != docstring::npos) {
305 warned_about_spaces = true;
306 Alert::warning(_("Export Warning!"),
307 _("There are spaces in the paths to your BibTeX databases.\n"
308 "BibTeX will be unable to find them."));
311 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
313 if (prefixIs(style, "bibtotoc")) {
314 bibtotoc = "bibtotoc";
315 if (contains(style, ','))
316 style = split(style, bibtotoc, ',');
322 if (!style.empty()) {
323 string base = normalizeName(buffer(), runparams, style, ".bst");
324 FileName const try_in_file =
325 makeAbsPath(base + ".bst", buffer().filePath());
326 bool const not_from_texmf = try_in_file.isReadableFile();
327 // If this style does not come from texmf and we are not
328 // exporting to .tex copy it to the tmp directory.
329 // This prevents problems with spaces and 8bit charcaters
331 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
333 // use new style name
334 DocFileName const in_file = DocFileName(try_in_file);
335 base = removeExtension(in_file.mangledFilename());
336 FileName const out_file = makeAbsPath(base + ".bst",
337 buffer().masterBuffer()->temppath());
338 bool const success = in_file.copyTo(out_file);
340 lyxerr << "Failed to copy '" << in_file
341 << "' to '" << out_file << "'"
346 os << "\\bibliographystyle{"
347 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
352 // Post this warning only once.
353 static bool warned_about_bst_spaces = false;
354 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
355 warned_about_bst_spaces = true;
356 Alert::warning(_("Export Warning!"),
357 _("There are spaces in the path to your BibTeX style file.\n"
358 "BibTeX will be unable to find it."));
361 if (!db_out.empty() && buffer().params().use_bibtopic) {
362 os << "\\begin{btSect}{" << db_out << "}\n";
363 docstring btprint = getParam("btprint");
366 btprint = from_ascii("btPrintCited");
367 os << "\\" << btprint << "\n"
368 << "\\end{btSect}\n";
373 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
374 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
375 if (buffer().params().sides == OneSide) {
380 os << "\\cleardoublepage";
382 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
383 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
384 os << "\\addcontentsline{toc}{section}{\\refname}";
387 if (!db_out.empty() && !buffer().params().use_bibtopic) {
388 docstring btprint = getParam("btprint");
389 if (btprint == "btPrintAll") {
390 os << "\\nocite{*}\n";
393 os << "\\bibliography{" << db_out << "}\n";
401 support::FileNameList InsetBibtex::getBibFiles() const
403 FileName path(buffer().filePath());
404 support::PathChanger p(path);
406 support::FileNameList vec;
408 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
409 vector<docstring>::const_iterator it = bibfilelist.begin();
410 vector<docstring>::const_iterator en = bibfilelist.end();
411 for (; it != en; ++it) {
412 FileName const file = getBibTeXPath(*it, buffer());
417 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
426 // methods for parsing bibtex files
428 typedef map<docstring, docstring> VarMap;
430 /// remove whitespace characters, optionally a single comma,
431 /// and further whitespace characters from the stream.
432 /// @return true if a comma was found, false otherwise
434 bool removeWSAndComma(ifdocstream & ifs) {
443 } while (ifs && isSpace(ch));
456 } while (ifs && isSpace(ch));
471 /// remove whitespace characters, read characer sequence
472 /// not containing whitespace characters or characters in
473 /// delimChars, and remove further whitespace characters.
475 /// @return true if a string of length > 0 could be read.
477 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
478 docstring const & delimChars, docstring const &illegalChars,
491 } while (ifs && isSpace(ch));
497 bool legalChar = true;
498 while (ifs && !isSpace(ch) &&
499 delimChars.find(ch) == docstring::npos &&
500 (legalChar = (illegalChars.find(ch) == docstring::npos))
503 if (chCase == makeLowerCase)
504 val += lowercase(ch);
516 while (ifs && isSpace(ch)) {
524 return val.length() > 0;
527 /// read subsequent bibtex values that are delimited with a #-character.
528 /// Concatenate all parts and replace names with the associated string in
529 /// the variable strings.
530 /// @return true if reading was successfull (all single parts were delimited
532 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
545 } while (ifs && isSpace(ch));
550 // check for field type
553 // read integer value
557 } while (ifs && isDigit(ch));
562 } else if (ch == '"' || ch == '{') {
564 char_type delim = ch == '"' ? '"': '}';
569 } while (ifs && isSpace(ch));
574 // We now have the first non-whitespace character
575 // We'll collapse adjacent whitespace.
576 bool lastWasWhiteSpace = false;
578 // inside this delimited text braces must match.
579 // Thus we can have a closing delimiter only
580 // when nestLevel == 0
583 while (ifs && (nestLevel > 0 || ch != delim)) {
585 lastWasWhiteSpace = true;
589 // We output the space only after we stop getting
590 // whitespace so as not to output any whitespace
591 // at the end of the value.
592 if (lastWasWhiteSpace) {
593 lastWasWhiteSpace = false;
599 // update nesting level
606 if (nestLevel < 0) return false;
623 // reading a string name
626 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
627 strName += lowercase(ch);
634 // replace the string with its assigned value or
635 // discard it if it's not assigned
636 if (strName.length()) {
637 VarMap::const_iterator pos = strings.find(strName);
638 if (pos != strings.end()) {
645 while (ifs && isSpace(ch)) {
652 // continue reading next value on concatenate with '#'
662 // This method returns a comma separated list of Bibtex entries
663 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
664 InsetIterator const & /*di*/) const
666 // This bibtex parser is a first step to parse bibtex files
669 // - it reads the whole bibtex entry and does a syntax check
670 // (matching delimiters, missing commas,...
671 // - it recovers from errors starting with the next @-character
672 // - it reads @string definitions and replaces them in the
674 // - it accepts more characters in keys or value names than
677 // Officially bibtex does only support ASCII, but in practice
678 // you can use the encoding of the main document as long as
679 // some elements like keys and names are pure ASCII. Therefore
680 // we convert the file from the buffer encoding.
681 // We don't restrict keys to ASCII in LyX, since our own
682 // InsetBibitem can generate non-ASCII keys, and nonstandard
683 // 8bit clean bibtex forks exist.
684 support::FileNameList const files = getBibFiles();
685 support::FileNameList::const_iterator it = files.begin();
686 support::FileNameList::const_iterator en = files.end();
687 for (; it != en; ++ it) {
688 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
689 ios_base::in, buffer().params().encoding().iconvName());
705 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
706 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
711 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
715 if (entryType == from_ascii("comment")) {
716 ifs.ignore(numeric_limits<int>::max(), '\n');
722 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
726 if ((ch != '(') && (ch != '{')) {
727 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
733 if (entryType == from_ascii("string")) {
735 // read string and add it to the strings map
736 // (or replace it's old value)
740 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
741 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
746 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
750 // next char must be an equal sign
752 if (!ifs || ch != '=') {
753 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
754 name << "." << std::endl;
758 if (!readValue(value, ifs, strings)) {
759 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
760 name << "." << std::endl;
764 strings[name] = value;
766 } else if (entryType == from_ascii("preamble")) {
768 // preamble definitions are discarded.
769 // can they be of any use in lyx?
772 if (!readValue(value, ifs, strings)) {
773 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
779 // Citation entry. Try to read the key.
782 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
783 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
784 entryType << "." << std::endl;
789 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
793 /////////////////////////////////////////////
794 // now we have a key, so we will add an entry
795 // (even if it's empty, as bibtex does)
797 // we now read the field = value pairs.
798 // all items must be separated by a comma. If
799 // it is missing the scanning of this entry is
800 // stopped and the next is searched.
804 docstring commaNewline;
806 BibTeXInfo keyvalmap(key, entryType);
808 bool readNext = removeWSAndComma(ifs);
810 while (ifs && readNext) {
813 if (!readTypeOrKey(name, ifs, from_ascii("="),
814 from_ascii("{}(),"), makeLowerCase) || !ifs)
817 // next char must be an equal sign
820 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
824 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
825 name << ", for key: " << key << "." << std::endl;
831 if (!readValue(value, ifs, strings)) {
832 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
833 name << ", for key: " << key << "." << std::endl;
837 keyvalmap[name] = value;
838 data += "\n\n" + value;
839 keylist.addFieldName(name);
840 readNext = removeWSAndComma(ifs);
844 keylist.addEntryType(entryType);
845 keyvalmap.setAllData(data);
846 keylist[key] = keyvalmap;
847 } //< else (citation entry)
849 } //< for loop over files
853 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
855 string texfile = changeExtension(to_utf8(filename), "bib");
856 // note that, if the filename can be found directly from the path,
857 // findtexfile will just return a FileName object for that path.
858 FileName file(findtexfile(texfile, "bib"));
860 file = FileName(makeAbsPath(texfile, buf.filePath()));
865 bool InsetBibtex::addDatabase(docstring const & db)
867 docstring bibfiles = getParam("bibfiles");
868 if (tokenPos(bibfiles, ',', db) != -1)
870 if (!bibfiles.empty())
872 setParam("bibfiles", bibfiles + db);
877 bool InsetBibtex::delDatabase(docstring const & db)
879 docstring bibfiles = getParam("bibfiles");
880 if (contains(bibfiles, db)) {
881 int const n = tokenPos(bibfiles, ',', db);
884 // this is not the first database
885 docstring tmp = ',' + bd;
886 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
888 // this is the first (or only) database
889 setParam("bibfiles", split(bibfiles, bd, ','));
897 void InsetBibtex::validate(LaTeXFeatures & features) const
899 if (features.bufferParams().use_bibtopic)
900 features.require("bibtopic");
902 // It'd be better to be able to get this from an InsetLayout, but at present
903 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
904 if (features.runparams().flavor == OutputParams::HTML)
905 features.addPreambleSnippet("<style type=\"text/css\">\n"
906 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
907 "span.bibtexlabel:before{ content: \"[\"; }\n"
908 "span.bibtexlabel:after{ content: \"] \"; }\n"
914 // used in xhtml to sort a list of BibTeXInfo objects
915 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
917 return lhs->getAbbreviatedAuthor() < rhs->getAbbreviatedAuthor();
922 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
924 // We are going to collect all the citation keys used in the document,
925 // getting them from the TOC.
926 Toc const & toc = buffer().tocBackend().toc("citation");
927 Toc::const_iterator it = toc.begin();
928 Toc::const_iterator const en = toc.end();
929 vector<docstring> citekeys;
930 for (; it != en; ++it) {
931 if (it->str().empty())
933 vector<docstring> const keys = getVectorFromString(it->str());
934 citekeys.insert(citekeys.end(), keys.begin(), keys.end());
936 if (citekeys.empty())
938 sort(citekeys.begin(), citekeys.end());
939 vector<docstring>::iterator uit =
940 unique(citekeys.begin(), citekeys.end());
941 citekeys.erase(uit, citekeys.end());
942 // We now have a sorted, unique list of the keys used in this document.
943 // We will now convert it to a list of the BibTeXInfo objects used in
945 vector<BibTeXInfo const *> binfo;
946 vector<docstring>::const_iterator cit = citekeys.begin();
947 vector<docstring>::const_iterator const cen = citekeys.end();
948 BiblioInfo const & bi = buffer().masterBibInfo();
949 for (; cit != cen; ++cit) {
950 BiblioInfo::const_iterator const bt = bi.find(*cit);
951 if (bt == bi.end() || !bt->second.isBibTeX())
953 binfo.push_back(&(bt->second));
956 sort(binfo.begin(), binfo.end(), lSorter);
957 // Finally, then, we are ready for output.
958 xs << StartTag("h2", "class='bibtex'")
961 << StartTag("div", "class='bibtex'");
963 // Now we loop over the entries
964 vector<BibTeXInfo const *>::const_iterator vit = binfo.begin();
965 vector<BibTeXInfo const *>::const_iterator const ven = binfo.end();
966 for (; vit != ven; ++vit) {
967 BibTeXInfo const * bip = *vit;
968 xs << StartTag("div", "class='bibtexentry'");
970 // The same name/id problem we have elsewhere.
971 string const attr = "id='" + to_utf8(bip->key()) + "'";
972 xs << CompTag("a", attr);
973 docstring label = bip->label();
976 xs << StartTag("span", "class='bibtexlabel'")
979 // FIXME Right now, we are calling BibInfo::getInfo on the key,
980 // which will give us all the cross-referenced info. But for every
981 // entry, so there's a lot of repitition. This should be fixed.
982 xs << StartTag("span", "class='bibtexinfo'")
983 << bi.getInfo(bip->key())
992 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
994 return from_ascii("context-bibtex");