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 "PDFOptions.h"
28 #include "TextClass.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().invalidateBibfileCache();
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)
82 switch (cmd.action()) {
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().invalidateBibfileCache();
107 cur.forceBufferUpdate();
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 if (!isValidLaTeXFileName(database)) {
287 frontend::Alert::warning(_("Invalid filename"),
288 _("The following filename will cause troubles "
289 "when running the exported file through LaTeX: ") +
290 from_utf8(database));
292 if (!isValidDVIFileName(database)) {
293 frontend::Alert::warning(_("Problematic filename for DVI"),
294 _("The following filename can cause troubles "
295 "when running the exported file through LaTeX "
296 "and opening the resulting DVI: ") +
297 from_utf8(database), true);
306 dbs << from_utf8(latex_path(database));
308 docstring const db_out = dbs.str();
310 // Post this warning only once.
311 static bool warned_about_spaces = false;
312 if (!warned_about_spaces &&
313 runparams.nice && db_out.find(' ') != docstring::npos) {
314 warned_about_spaces = true;
315 Alert::warning(_("Export Warning!"),
316 _("There are spaces in the paths to your BibTeX databases.\n"
317 "BibTeX will be unable to find them."));
320 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
322 if (prefixIs(style, "bibtotoc")) {
323 bibtotoc = "bibtotoc";
324 if (contains(style, ','))
325 style = split(style, bibtotoc, ',');
331 if (!style.empty()) {
332 string base = normalizeName(buffer(), runparams, style, ".bst");
333 FileName const try_in_file =
334 makeAbsPath(base + ".bst", buffer().filePath());
335 bool const not_from_texmf = try_in_file.isReadableFile();
336 // If this style does not come from texmf and we are not
337 // exporting to .tex copy it to the tmp directory.
338 // This prevents problems with spaces and 8bit charcaters
340 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
342 // use new style name
343 DocFileName const in_file = DocFileName(try_in_file);
344 base = removeExtension(in_file.mangledFileName());
345 FileName const out_file = makeAbsPath(base + ".bst",
346 buffer().masterBuffer()->temppath());
347 bool const success = in_file.copyTo(out_file);
349 lyxerr << "Failed to copy '" << in_file
350 << "' to '" << out_file << "'"
355 os << "\\bibliographystyle{"
356 << 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}{" << db_out << "}\n";
372 docstring btprint = getParam("btprint");
375 btprint = from_ascii("btPrintCited");
376 os << "\\" << btprint << "\n"
377 << "\\end{btSect}\n";
382 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
383 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
384 if (buffer().params().pdfoptions().use_hyperref)
385 os << "\\phantomsection";
386 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
387 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
388 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
389 os << "\\addcontentsline{toc}{section}{\\refname}";
392 if (!db_out.empty() && !buffer().params().use_bibtopic) {
393 docstring btprint = getParam("btprint");
394 if (btprint == "btPrintAll") {
395 os << "\\nocite{*}\n";
398 os << "\\bibliography{" << db_out << "}\n";
406 support::FileNameList InsetBibtex::getBibFiles() const
408 FileName path(buffer().filePath());
409 support::PathChanger p(path);
411 support::FileNameList vec;
413 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
414 vector<docstring>::const_iterator it = bibfilelist.begin();
415 vector<docstring>::const_iterator en = bibfilelist.end();
416 for (; it != en; ++it) {
417 FileName const file = getBibTeXPath(*it, buffer());
422 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
431 // methods for parsing bibtex files
433 typedef map<docstring, docstring> VarMap;
435 /// remove whitespace characters, optionally a single comma,
436 /// and further whitespace characters from the stream.
437 /// @return true if a comma was found, false otherwise
439 bool removeWSAndComma(ifdocstream & ifs) {
448 } while (ifs && isSpace(ch));
461 } while (ifs && isSpace(ch));
476 /// remove whitespace characters, read characer sequence
477 /// not containing whitespace characters or characters in
478 /// delimChars, and remove further whitespace characters.
480 /// @return true if a string of length > 0 could be read.
482 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
483 docstring const & delimChars, docstring const & illegalChars,
496 } while (ifs && isSpace(ch));
502 bool legalChar = true;
503 while (ifs && !isSpace(ch) &&
504 delimChars.find(ch) == docstring::npos &&
505 (legalChar = (illegalChars.find(ch) == docstring::npos))
508 if (chCase == makeLowerCase)
509 val += lowercase(ch);
521 while (ifs && isSpace(ch)) {
529 return val.length() > 0;
532 /// read subsequent bibtex values that are delimited with a #-character.
533 /// Concatenate all parts and replace names with the associated string in
534 /// the variable strings.
535 /// @return true if reading was successfull (all single parts were delimited
537 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
550 } while (ifs && isSpace(ch));
555 // check for field type
558 // read integer value
562 } while (ifs && isDigit(ch));
567 } else if (ch == '"' || ch == '{') {
569 char_type delim = ch == '"' ? '"': '}';
574 } while (ifs && isSpace(ch));
579 // We now have the first non-whitespace character
580 // We'll collapse adjacent whitespace.
581 bool lastWasWhiteSpace = false;
583 // inside this delimited text braces must match.
584 // Thus we can have a closing delimiter only
585 // when nestLevel == 0
588 while (ifs && (nestLevel > 0 || ch != delim)) {
590 lastWasWhiteSpace = true;
594 // We output the space only after we stop getting
595 // whitespace so as not to output any whitespace
596 // at the end of the value.
597 if (lastWasWhiteSpace) {
598 lastWasWhiteSpace = false;
604 // update nesting level
623 // FIXME Why is this here?
631 // reading a string name
634 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
635 strName += lowercase(ch);
642 // replace the string with its assigned value or
643 // discard it if it's not assigned
644 if (strName.length()) {
645 VarMap::const_iterator pos = strings.find(strName);
646 if (pos != strings.end()) {
653 while (ifs && isSpace(ch)) {
660 // continue reading next value on concatenate with '#'
670 // This method returns a comma separated list of Bibtex entries
671 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
672 InsetIterator const & /*di*/) const
674 // This bibtex parser is a first step to parse bibtex files
677 // - it reads the whole bibtex entry and does a syntax check
678 // (matching delimiters, missing commas,...
679 // - it recovers from errors starting with the next @-character
680 // - it reads @string definitions and replaces them in the
682 // - it accepts more characters in keys or value names than
685 // Officially bibtex does only support ASCII, but in practice
686 // you can use the encoding of the main document as long as
687 // some elements like keys and names are pure ASCII. Therefore
688 // we convert the file from the buffer encoding.
689 // We don't restrict keys to ASCII in LyX, since our own
690 // InsetBibitem can generate non-ASCII keys, and nonstandard
691 // 8bit clean bibtex forks exist.
692 support::FileNameList const files = getBibFiles();
693 support::FileNameList::const_iterator it = files.begin();
694 support::FileNameList::const_iterator en = files.end();
695 for (; it != en; ++ it) {
696 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
697 ios_base::in, buffer().params().encoding().iconvName());
713 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
714 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
719 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
723 if (entryType == from_ascii("comment")) {
724 ifs.ignore(numeric_limits<int>::max(), '\n');
730 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
734 if ((ch != '(') && (ch != '{')) {
735 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
741 if (entryType == from_ascii("string")) {
743 // read string and add it to the strings map
744 // (or replace it's old value)
748 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
749 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
754 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
758 // next char must be an equal sign
760 if (!ifs || ch != '=') {
761 lyxerr << "BibTeX Parser: No `=' after string name: " <<
762 name << "." << std::endl;
766 if (!readValue(value, ifs, strings)) {
767 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
768 name << "." << std::endl;
772 strings[name] = value;
774 } else if (entryType == from_ascii("preamble")) {
776 // preamble definitions are discarded.
777 // can they be of any use in lyx?
780 if (!readValue(value, ifs, strings)) {
781 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
787 // Citation entry. Try to read the key.
790 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
791 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
792 entryType << "." << std::endl;
797 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
801 /////////////////////////////////////////////
802 // now we have a key, so we will add an entry
803 // (even if it's empty, as bibtex does)
805 // we now read the field = value pairs.
806 // all items must be separated by a comma. If
807 // it is missing the scanning of this entry is
808 // stopped and the next is searched.
812 BibTeXInfo keyvalmap(key, entryType);
814 bool readNext = removeWSAndComma(ifs);
816 while (ifs && readNext) {
819 if (!readTypeOrKey(name, ifs, from_ascii("="),
820 from_ascii("{}(),"), makeLowerCase) || !ifs)
823 // next char must be an equal sign
824 // FIXME Whitespace??
827 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
831 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
832 name << ", for key: " << key << "." << std::endl;
838 if (!readValue(value, ifs, strings)) {
839 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
840 name << ", for key: " << key << "." << std::endl;
844 keyvalmap[name] = value;
845 data += "\n\n" + value;
846 keylist.addFieldName(name);
847 readNext = removeWSAndComma(ifs);
851 keylist.addEntryType(entryType);
852 keyvalmap.setAllData(data);
853 keylist[key] = keyvalmap;
854 } //< else (citation entry)
856 } //< for loop over files
860 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
862 string texfile = changeExtension(to_utf8(filename), "bib");
863 // note that, if the filename can be found directly from the path,
864 // findtexfile will just return a FileName object for that path.
865 FileName file(findtexfile(texfile, "bib"));
867 file = FileName(makeAbsPath(texfile, buf.filePath()));
872 bool InsetBibtex::addDatabase(docstring const & db)
874 docstring bibfiles = getParam("bibfiles");
875 if (tokenPos(bibfiles, ',', db) != -1)
877 if (!bibfiles.empty())
879 setParam("bibfiles", bibfiles + db);
884 bool InsetBibtex::delDatabase(docstring const & db)
886 docstring bibfiles = getParam("bibfiles");
887 if (contains(bibfiles, db)) {
888 int const n = tokenPos(bibfiles, ',', db);
891 // this is not the first database
892 docstring tmp = ',' + bd;
893 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
895 // this is the first (or only) database
896 setParam("bibfiles", split(bibfiles, bd, ','));
904 void InsetBibtex::validate(LaTeXFeatures & features) const
906 if (features.bufferParams().use_bibtopic)
907 features.require("bibtopic");
909 // It'd be better to be able to get this from an InsetLayout, but at present
910 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
911 if (features.runparams().flavor == OutputParams::HTML)
912 features.addPreambleSnippet("<style type=\"text/css\">\n"
913 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
914 "span.bibtexlabel:before{ content: \"[\"; }\n"
915 "span.bibtexlabel:after{ content: \"] \"; }\n"
921 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
922 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
923 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
925 BiblioInfo const & bibinfo = buffer().masterBibInfo();
926 vector<docstring> const & cites = bibinfo.citedEntries();
927 CiteEngine const engine = buffer().params().citeEngine();
929 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
931 docstring reflabel = from_ascii("References");
932 Language const * l = buffer().params().language;
934 reflabel = translateIfPossible(reflabel, l->code());
936 xs << html::StartTag("h2", "class='bibtex'")
938 << html::EndTag("h2")
939 << html::StartTag("div", "class='bibtex'");
941 // Now we loop over the entries
942 vector<docstring>::const_iterator vit = cites.begin();
943 vector<docstring>::const_iterator const ven = cites.end();
944 for (; vit != ven; ++vit) {
945 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
946 if (biit == bibinfo.end())
948 BibTeXInfo const & entry = biit->second;
949 xs << html::StartTag("div", "class='bibtexentry'");
951 // The same name/id problem we have elsewhere.
952 string const attr = "id='" + to_utf8(entry.key()) + "'";
953 xs << html::CompTag("a", attr);
956 citekey = entry.citeNumber();
958 docstring const auth = entry.getAbbreviatedAuthor();
959 // we do it this way so as to access the xref, if necessary
960 // note that this also gives us the modifier
961 docstring const year = bibinfo.getYear(*vit, true);
962 if (!auth.empty() && !year.empty())
963 citekey = auth + ' ' + year;
965 if (citekey.empty()) {
966 citekey = entry.label();
968 citekey = entry.key();
970 xs << html::StartTag("span", "class='bibtexlabel'")
972 << html::EndTag("span");
973 // FIXME Right now, we are calling BibInfo::getInfo on the key,
974 // which will give us all the cross-referenced info. But for every
975 // entry, so there's a lot of repitition. This should be fixed.
976 xs << html::StartTag("span", "class='bibtexinfo'")
977 << XHTMLStream::NextRaw()
978 << bibinfo.getInfo(entry.key(), buffer(), true)
979 << html::EndTag("span")
980 << html::EndTag("div");
983 xs << html::EndTag("div");
988 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
990 return from_ascii("context-bibtex");