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"
24 #include "LaTeXFeatures.h"
25 #include "output_xhtml.h"
26 #include "OutputParams.h"
27 #include "TextClass.h"
29 #include "frontends/alert.h"
31 #include "support/convert.h"
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/ExceptionMessage.h"
35 #include "support/filetools.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38 #include "support/os.h"
39 #include "support/Path.h"
40 #include "support/textutils.h"
45 using namespace lyx::support;
49 namespace Alert = frontend::Alert;
50 namespace os = support::os;
53 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
54 : InsetCommand(buf, p, "bibtex")
56 buffer().invalidateBibinfoCache();
60 InsetBibtex::~InsetBibtex()
63 buffer().invalidateBibfileCache();
67 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
69 static ParamInfo param_info_;
70 if (param_info_.empty()) {
71 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
72 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
73 param_info_.add("options", ParamInfo::LYX_INTERNAL);
79 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
81 switch (cmd.action()) {
87 case LFUN_INSET_MODIFY: {
88 InsetCommandParams p(BIBTEX_CODE);
90 if (!InsetCommand::string2params("bibtex",
91 to_utf8(cmd.argument()), p)) {
95 } catch (ExceptionMessage const & message) {
96 if (message.type_ == WarningException) {
97 Alert::warning(message.title_, message.details_);
105 buffer().invalidateBibfileCache();
106 cur.forceBufferUpdate();
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 if (!isValidLaTeXFileName(database)) {
286 frontend::Alert::warning(_("Invalid filename"),
287 _("The following filename will cause troubles "
288 "when running the exported file through LaTeX: ") +
289 from_utf8(database));
291 if (!isValidDVIFileName(database)) {
292 frontend::Alert::warning(_("Problematic filename for DVI"),
293 _("The following filename can cause troubles "
294 "when running the exported file through LaTeX "
295 "and opening the resulting DVI: ") +
296 from_utf8(database), true);
305 dbs << from_utf8(latex_path(database));
307 docstring const db_out = dbs.str();
309 // Post this warning only once.
310 static bool warned_about_spaces = false;
311 if (!warned_about_spaces &&
312 runparams.nice && db_out.find(' ') != docstring::npos) {
313 warned_about_spaces = true;
314 Alert::warning(_("Export Warning!"),
315 _("There are spaces in the paths to your BibTeX databases.\n"
316 "BibTeX will be unable to find them."));
319 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
321 if (prefixIs(style, "bibtotoc")) {
322 bibtotoc = "bibtotoc";
323 if (contains(style, ','))
324 style = split(style, bibtotoc, ',');
330 if (!style.empty()) {
331 string base = normalizeName(buffer(), runparams, style, ".bst");
332 FileName const try_in_file =
333 makeAbsPath(base + ".bst", buffer().filePath());
334 bool const not_from_texmf = try_in_file.isReadableFile();
335 // If this style does not come from texmf and we are not
336 // exporting to .tex copy it to the tmp directory.
337 // This prevents problems with spaces and 8bit charcaters
339 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
341 // use new style name
342 DocFileName const in_file = DocFileName(try_in_file);
343 base = removeExtension(in_file.mangledFileName());
344 FileName const out_file = makeAbsPath(base + ".bst",
345 buffer().masterBuffer()->temppath());
346 bool const success = in_file.copyTo(out_file);
348 lyxerr << "Failed to copy '" << in_file
349 << "' to '" << out_file << "'"
354 os << "\\bibliographystyle{"
355 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
360 // Post this warning only once.
361 static bool warned_about_bst_spaces = false;
362 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
363 warned_about_bst_spaces = true;
364 Alert::warning(_("Export Warning!"),
365 _("There are spaces in the path to your BibTeX style file.\n"
366 "BibTeX will be unable to find it."));
369 if (!db_out.empty() && buffer().params().use_bibtopic) {
370 os << "\\begin{btSect}{" << db_out << "}\n";
371 docstring btprint = getParam("btprint");
374 btprint = from_ascii("btPrintCited");
375 os << "\\" << btprint << "\n"
376 << "\\end{btSect}\n";
381 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
382 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
383 if (buffer().params().sides == OneSide) {
388 os << "\\cleardoublepage";
390 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
391 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
392 os << "\\addcontentsline{toc}{section}{\\refname}";
395 if (!db_out.empty() && !buffer().params().use_bibtopic) {
396 docstring btprint = getParam("btprint");
397 if (btprint == "btPrintAll") {
398 os << "\\nocite{*}\n";
401 os << "\\bibliography{" << db_out << "}\n";
409 support::FileNameList InsetBibtex::getBibFiles() const
411 FileName path(buffer().filePath());
412 support::PathChanger p(path);
414 support::FileNameList vec;
416 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
417 vector<docstring>::const_iterator it = bibfilelist.begin();
418 vector<docstring>::const_iterator en = bibfilelist.end();
419 for (; it != en; ++it) {
420 FileName const file = getBibTeXPath(*it, buffer());
425 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
434 // methods for parsing bibtex files
436 typedef map<docstring, docstring> VarMap;
438 /// remove whitespace characters, optionally a single comma,
439 /// and further whitespace characters from the stream.
440 /// @return true if a comma was found, false otherwise
442 bool removeWSAndComma(ifdocstream & ifs) {
451 } while (ifs && isSpace(ch));
464 } while (ifs && isSpace(ch));
479 /// remove whitespace characters, read characer sequence
480 /// not containing whitespace characters or characters in
481 /// delimChars, and remove further whitespace characters.
483 /// @return true if a string of length > 0 could be read.
485 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
486 docstring const & delimChars, docstring const & illegalChars,
499 } while (ifs && isSpace(ch));
505 bool legalChar = true;
506 while (ifs && !isSpace(ch) &&
507 delimChars.find(ch) == docstring::npos &&
508 (legalChar = (illegalChars.find(ch) == docstring::npos))
511 if (chCase == makeLowerCase)
512 val += lowercase(ch);
524 while (ifs && isSpace(ch)) {
532 return val.length() > 0;
535 /// read subsequent bibtex values that are delimited with a #-character.
536 /// Concatenate all parts and replace names with the associated string in
537 /// the variable strings.
538 /// @return true if reading was successfull (all single parts were delimited
540 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
553 } while (ifs && isSpace(ch));
558 // check for field type
561 // read integer value
565 } while (ifs && isDigit(ch));
570 } else if (ch == '"' || ch == '{') {
572 char_type delim = ch == '"' ? '"': '}';
577 } while (ifs && isSpace(ch));
582 // We now have the first non-whitespace character
583 // We'll collapse adjacent whitespace.
584 bool lastWasWhiteSpace = false;
586 // inside this delimited text braces must match.
587 // Thus we can have a closing delimiter only
588 // when nestLevel == 0
591 while (ifs && (nestLevel > 0 || ch != delim)) {
593 lastWasWhiteSpace = true;
597 // We output the space only after we stop getting
598 // whitespace so as not to output any whitespace
599 // at the end of the value.
600 if (lastWasWhiteSpace) {
601 lastWasWhiteSpace = false;
607 // update nesting level
626 // FIXME Why is this here?
634 // reading a string name
637 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
638 strName += lowercase(ch);
645 // replace the string with its assigned value or
646 // discard it if it's not assigned
647 if (strName.length()) {
648 VarMap::const_iterator pos = strings.find(strName);
649 if (pos != strings.end()) {
656 while (ifs && isSpace(ch)) {
663 // continue reading next value on concatenate with '#'
673 // This method returns a comma separated list of Bibtex entries
674 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
675 InsetIterator const & /*di*/) const
677 // This bibtex parser is a first step to parse bibtex files
680 // - it reads the whole bibtex entry and does a syntax check
681 // (matching delimiters, missing commas,...
682 // - it recovers from errors starting with the next @-character
683 // - it reads @string definitions and replaces them in the
685 // - it accepts more characters in keys or value names than
688 // Officially bibtex does only support ASCII, but in practice
689 // you can use the encoding of the main document as long as
690 // some elements like keys and names are pure ASCII. Therefore
691 // we convert the file from the buffer encoding.
692 // We don't restrict keys to ASCII in LyX, since our own
693 // InsetBibitem can generate non-ASCII keys, and nonstandard
694 // 8bit clean bibtex forks exist.
695 support::FileNameList const files = getBibFiles();
696 support::FileNameList::const_iterator it = files.begin();
697 support::FileNameList::const_iterator en = files.end();
698 for (; it != en; ++ it) {
699 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
700 ios_base::in, buffer().params().encoding().iconvName());
716 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
717 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
722 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
726 if (entryType == from_ascii("comment")) {
727 ifs.ignore(numeric_limits<int>::max(), '\n');
733 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
737 if ((ch != '(') && (ch != '{')) {
738 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
744 if (entryType == from_ascii("string")) {
746 // read string and add it to the strings map
747 // (or replace it's old value)
751 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
752 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
757 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
761 // next char must be an equal sign
763 if (!ifs || ch != '=') {
764 lyxerr << "BibTeX Parser: No `=' after string name: " <<
765 name << "." << std::endl;
769 if (!readValue(value, ifs, strings)) {
770 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
771 name << "." << std::endl;
775 strings[name] = value;
777 } else if (entryType == from_ascii("preamble")) {
779 // preamble definitions are discarded.
780 // can they be of any use in lyx?
783 if (!readValue(value, ifs, strings)) {
784 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
790 // Citation entry. Try to read the key.
793 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
794 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
795 entryType << "." << std::endl;
800 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
804 /////////////////////////////////////////////
805 // now we have a key, so we will add an entry
806 // (even if it's empty, as bibtex does)
808 // we now read the field = value pairs.
809 // all items must be separated by a comma. If
810 // it is missing the scanning of this entry is
811 // stopped and the next is searched.
815 BibTeXInfo keyvalmap(key, entryType);
817 bool readNext = removeWSAndComma(ifs);
819 while (ifs && readNext) {
822 if (!readTypeOrKey(name, ifs, from_ascii("="),
823 from_ascii("{}(),"), makeLowerCase) || !ifs)
826 // next char must be an equal sign
827 // FIXME Whitespace??
830 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
834 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
835 name << ", for key: " << key << "." << std::endl;
841 if (!readValue(value, ifs, strings)) {
842 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
843 name << ", for key: " << key << "." << std::endl;
847 keyvalmap[name] = value;
848 data += "\n\n" + value;
849 keylist.addFieldName(name);
850 readNext = removeWSAndComma(ifs);
854 keylist.addEntryType(entryType);
855 keyvalmap.setAllData(data);
856 keylist[key] = keyvalmap;
857 } //< else (citation entry)
859 } //< for loop over files
863 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
865 string texfile = changeExtension(to_utf8(filename), "bib");
866 // note that, if the filename can be found directly from the path,
867 // findtexfile will just return a FileName object for that path.
868 FileName file(findtexfile(texfile, "bib"));
870 file = FileName(makeAbsPath(texfile, buf.filePath()));
875 bool InsetBibtex::addDatabase(docstring const & db)
877 docstring bibfiles = getParam("bibfiles");
878 if (tokenPos(bibfiles, ',', db) != -1)
880 if (!bibfiles.empty())
882 setParam("bibfiles", bibfiles + db);
887 bool InsetBibtex::delDatabase(docstring const & db)
889 docstring bibfiles = getParam("bibfiles");
890 if (contains(bibfiles, db)) {
891 int const n = tokenPos(bibfiles, ',', db);
894 // this is not the first database
895 docstring tmp = ',' + bd;
896 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
898 // this is the first (or only) database
899 setParam("bibfiles", split(bibfiles, bd, ','));
907 void InsetBibtex::validate(LaTeXFeatures & features) const
909 if (features.bufferParams().use_bibtopic)
910 features.require("bibtopic");
912 // It'd be better to be able to get this from an InsetLayout, but at present
913 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
914 if (features.runparams().flavor == OutputParams::HTML)
915 features.addPreambleSnippet("<style type=\"text/css\">\n"
916 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
917 "span.bibtexlabel:before{ content: \"[\"; }\n"
918 "span.bibtexlabel:after{ content: \"] \"; }\n"
924 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
925 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
926 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
928 BiblioInfo const & bibinfo = buffer().masterBibInfo();
929 vector<docstring> const & cites = bibinfo.citedEntries();
930 CiteEngine const engine = buffer().params().citeEngine();
932 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
934 docstring reflabel = from_ascii("References");
935 Language const * l = buffer().params().language;
937 reflabel = translateIfPossible(reflabel, l->code());
939 xs << html::StartTag("h2", "class='bibtex'")
941 << html::EndTag("h2")
942 << html::StartTag("div", "class='bibtex'");
944 // Now we loop over the entries
945 vector<docstring>::const_iterator vit = cites.begin();
946 vector<docstring>::const_iterator const ven = cites.end();
947 for (; vit != ven; ++vit) {
948 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
949 if (biit == bibinfo.end())
951 BibTeXInfo const & entry = biit->second;
952 xs << html::StartTag("div", "class='bibtexentry'");
954 // The same name/id problem we have elsewhere.
955 string const attr = "id='" + to_utf8(entry.key()) + "'";
956 xs << html::CompTag("a", attr);
959 citekey = entry.citeNumber();
961 docstring const auth = entry.getAbbreviatedAuthor();
962 // we do it this way so as to access the xref, if necessary
963 // note that this also gives us the modifier
964 docstring const year = bibinfo.getYear(*vit, true);
965 if (!auth.empty() && !year.empty())
966 citekey = auth + ' ' + year;
968 if (citekey.empty()) {
969 citekey = entry.label();
971 citekey = entry.key();
973 xs << html::StartTag("span", "class='bibtexlabel'")
975 << html::EndTag("span");
976 // FIXME Right now, we are calling BibInfo::getInfo on the key,
977 // which will give us all the cross-referenced info. But for every
978 // entry, so there's a lot of repitition. This should be fixed.
979 xs << html::StartTag("span", "class='bibtexinfo'")
980 << XHTMLStream::NextRaw()
981 << bibinfo.getInfo(entry.key(), buffer(), true)
982 << html::EndTag("span")
983 << html::EndTag("div");
986 xs << html::EndTag("div");
991 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
993 return from_ascii("context-bibtex");