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"
27 #include "LaTeXFeatures.h"
28 #include "output_xhtml.h"
29 #include "OutputParams.h"
30 #include "PDFOptions.h"
31 #include "TextClass.h"
33 #include "frontends/alert.h"
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/FileNameList.h"
40 #include "support/filetools.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/os.h"
44 #include "support/Path.h"
45 #include "support/textutils.h"
50 using namespace lyx::support;
54 namespace Alert = frontend::Alert;
55 namespace os = support::os;
58 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
59 : InsetCommand(buf, p)
61 buffer().invalidateBibinfoCache();
62 buffer().removeBiblioTempFiles();
66 InsetBibtex::~InsetBibtex()
68 if (isBufferLoaded()) {
69 buffer().invalidateBibfileCache();
70 buffer().removeBiblioTempFiles();
75 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
77 static ParamInfo param_info_;
78 if (param_info_.empty()) {
79 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
80 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
81 param_info_.add("options", ParamInfo::LYX_INTERNAL);
87 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
89 switch (cmd.action()) {
95 case LFUN_INSET_MODIFY: {
96 InsetCommandParams p(BIBTEX_CODE);
98 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
102 } catch (ExceptionMessage const & message) {
103 if (message.type_ == WarningException) {
104 Alert::warning(message.title_, message.details_);
105 cur.noScreenUpdate();
113 buffer().invalidateBibfileCache();
114 buffer().removeBiblioTempFiles();
115 cur.forceBufferUpdate();
120 InsetCommand::doDispatch(cur, cmd);
126 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
127 FuncStatus & flag) const
129 switch (cmd.action()) {
130 case LFUN_INSET_EDIT:
131 flag.setEnabled(true);
135 return InsetCommand::getStatus(cur, cmd, flag);
140 void InsetBibtex::editDatabases() const
142 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
144 if (bibfilelist.empty())
147 int nr_databases = bibfilelist.size();
148 if (nr_databases > 1) {
149 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
150 "If you proceed, all of them will be opened."),
151 convert<docstring>(nr_databases));
152 int const ret = Alert::prompt(_("Open Databases?"),
153 message, 0, 1, _("&Cancel"), _("&Proceed"));
159 vector<docstring>::const_iterator it = bibfilelist.begin();
160 vector<docstring>::const_iterator en = bibfilelist.end();
161 for (; it != en; ++it) {
162 FileName const bibfile = getBibTeXPath(*it, buffer());
163 formats.edit(buffer(), bibfile,
164 formats.getFormatFromFile(bibfile));
169 docstring InsetBibtex::screenLabel() const
171 return _("BibTeX Generated Bibliography");
175 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
177 docstring item = from_ascii("* ");
178 docstring tip = _("Databases:") + "\n";
179 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
181 if (bibfilelist.empty()) {
185 vector<docstring>::const_iterator it = bibfilelist.begin();
186 vector<docstring>::const_iterator en = bibfilelist.end();
187 for (; it != en; ++it) {
195 docstring style = getParam("options"); // maybe empty! and with bibtotoc
196 docstring bibtotoc = from_ascii("bibtotoc");
197 if (prefixIs(style, bibtotoc)) {
199 if (contains(style, char_type(',')))
200 style = split(style, bibtotoc, char_type(','));
203 tip += _("Style File:") +"\n";
210 tip += "\n" + _("Lists:") + " ";
211 docstring btprint = getParam("btprint");
212 if (btprint == "btPrintAll")
213 tip += _("all references");
214 else if (btprint == "btPrintNotCited")
215 tip += _("all uncited references");
217 tip += _("all cited references");
221 tip += _("included in TOC");
228 static string normalizeName(Buffer const & buffer,
229 OutputParams const & runparams, string const & name, string const & ext)
231 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
232 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
238 return to_utf8(makeRelPath(from_utf8(fname),
239 from_utf8(buffer.masterBuffer()->filePath())));
243 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
245 // the sequence of the commands:
246 // 1. \bibliographystyle{style}
247 // 2. \addcontentsline{...} - if option bibtotoc set
248 // 3. \bibliography{database}
249 // and with bibtopic:
250 // 1. \bibliographystyle{style}
251 // 2. \begin{btSect}{database}
252 // 3. \btPrint{Cited|NotCited|All}
256 // If we are processing the LaTeX file in a temp directory then
257 // copy the .bib databases to this temp directory, mangling their
258 // names in the process. Store this mangled name in the list of
260 // (We need to do all this because BibTeX *really*, *really*
261 // can't handle "files with spaces" and Windows users tend to
262 // use such filenames.)
263 // Otherwise, store the (maybe absolute) path to the original,
264 // unmangled database name.
265 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
266 vector<docstring>::const_iterator it = bibfilelist.begin();
267 vector<docstring>::const_iterator en = bibfilelist.end();
268 odocstringstream dbs;
271 // determine the export format
272 string const tex_format = flavor2format(runparams.flavor);
274 for (; it != en; ++it) {
275 string utf8input = to_utf8(*it);
277 normalizeName(buffer(), runparams, utf8input, ".bib");
278 FileName const try_in_file =
279 makeAbsPath(database + ".bib", buffer().filePath());
280 bool const not_from_texmf = try_in_file.isReadableFile();
282 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
284 // mangledFileName() needs the extension
285 DocFileName const in_file = DocFileName(try_in_file);
286 database = removeExtension(in_file.mangledFileName());
287 FileName const out_file = makeAbsPath(database + ".bib",
288 buffer().masterBuffer()->temppath());
289 bool const success = in_file.copyTo(out_file);
291 lyxerr << "Failed to copy '" << in_file
292 << "' to '" << out_file << "'"
295 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
296 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
297 if (!isValidLaTeXFileName(database)) {
298 frontend::Alert::warning(_("Invalid filename"),
299 _("The following filename will cause troubles "
300 "when running the exported file through LaTeX: ") +
301 from_utf8(database));
303 if (!isValidDVIFileName(database)) {
304 frontend::Alert::warning(_("Problematic filename for DVI"),
305 _("The following filename can cause troubles "
306 "when running the exported file through LaTeX "
307 "and opening the resulting DVI: ") +
308 from_utf8(database), true);
317 dbs << from_utf8(latex_path(database));
319 docstring const db_out = dbs.str();
321 // Post this warning only once.
322 static bool warned_about_spaces = false;
323 if (!warned_about_spaces &&
324 runparams.nice && db_out.find(' ') != docstring::npos) {
325 warned_about_spaces = true;
326 Alert::warning(_("Export Warning!"),
327 _("There are spaces in the paths to your BibTeX databases.\n"
328 "BibTeX will be unable to find them."));
331 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
333 if (prefixIs(style, "bibtotoc")) {
334 bibtotoc = "bibtotoc";
335 if (contains(style, ','))
336 style = split(style, bibtotoc, ',');
339 if (!style.empty()) {
340 string base = normalizeName(buffer(), runparams, style, ".bst");
341 FileName const try_in_file =
342 makeAbsPath(base + ".bst", buffer().filePath());
343 bool const not_from_texmf = try_in_file.isReadableFile();
344 // If this style does not come from texmf and we are not
345 // exporting to .tex copy it to the tmp directory.
346 // This prevents problems with spaces and 8bit charcaters
348 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
350 // use new style name
351 DocFileName const in_file = DocFileName(try_in_file);
352 base = removeExtension(in_file.mangledFileName());
353 FileName const out_file = makeAbsPath(base + ".bst",
354 buffer().masterBuffer()->temppath());
355 bool const success = in_file.copyTo(out_file);
357 lyxerr << "Failed to copy '" << in_file
358 << "' to '" << out_file << "'"
363 os << "\\bibliographystyle{"
364 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
368 // Post this warning only once.
369 static bool warned_about_bst_spaces = false;
370 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
371 warned_about_bst_spaces = true;
372 Alert::warning(_("Export Warning!"),
373 _("There are spaces in the path to your BibTeX style file.\n"
374 "BibTeX will be unable to find it."));
377 if (!db_out.empty() && buffer().params().use_bibtopic) {
378 os << "\\begin{btSect}{" << db_out << "}\n";
379 docstring btprint = getParam("btprint");
382 btprint = from_ascii("btPrintCited");
383 os << "\\" << btprint << "\n"
384 << "\\end{btSect}\n";
388 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
389 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
390 if (buffer().params().pdfoptions().use_hyperref)
391 os << "\\phantomsection";
392 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
393 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
394 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
395 os << "\\addcontentsline{toc}{section}{\\refname}";
398 if (!db_out.empty() && !buffer().params().use_bibtopic) {
399 docstring btprint = getParam("btprint");
400 if (btprint == "btPrintAll") {
401 os << "\\nocite{*}\n";
403 os << "\\bibliography{" << db_out << "}\n";
408 support::FileNameList InsetBibtex::getBibFiles() const
410 FileName path(buffer().filePath());
411 support::PathChanger p(path);
413 support::FileNameList vec;
415 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
416 vector<docstring>::const_iterator it = bibfilelist.begin();
417 vector<docstring>::const_iterator en = bibfilelist.end();
418 for (; it != en; ++it) {
419 FileName const file = getBibTeXPath(*it, buffer());
424 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
433 // methods for parsing bibtex files
435 typedef map<docstring, docstring> VarMap;
437 /// remove whitespace characters, optionally a single comma,
438 /// and further whitespace characters from the stream.
439 /// @return true if a comma was found, false otherwise
441 bool removeWSAndComma(ifdocstream & ifs) {
450 } while (ifs && isSpace(ch));
463 } while (ifs && isSpace(ch));
478 /// remove whitespace characters, read characer sequence
479 /// not containing whitespace characters or characters in
480 /// delimChars, and remove further whitespace characters.
482 /// @return true if a string of length > 0 could be read.
484 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
485 docstring const & delimChars, docstring const & illegalChars,
498 } while (ifs && isSpace(ch));
504 bool legalChar = true;
505 while (ifs && !isSpace(ch) &&
506 delimChars.find(ch) == docstring::npos &&
507 (legalChar = (illegalChars.find(ch) == docstring::npos))
510 if (chCase == makeLowerCase)
511 val += lowercase(ch);
523 while (ifs && isSpace(ch)) {
531 return val.length() > 0;
534 /// read subsequent bibtex values that are delimited with a #-character.
535 /// Concatenate all parts and replace names with the associated string in
536 /// the variable strings.
537 /// @return true if reading was successfull (all single parts were delimited
539 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
552 } while (ifs && isSpace(ch));
557 // check for field type
558 if (isDigitASCII(ch)) {
560 // read integer value
564 } while (ifs && isDigitASCII(ch));
569 } else if (ch == '"' || ch == '{') {
571 char_type delim = ch == '"' ? '"': '}';
576 } while (ifs && isSpace(ch));
581 // We now have the first non-whitespace character
582 // We'll collapse adjacent whitespace.
583 bool lastWasWhiteSpace = false;
585 // inside this delimited text braces must match.
586 // Thus we can have a closing delimiter only
587 // when nestLevel == 0
590 while (ifs && (nestLevel > 0 || ch != delim)) {
592 lastWasWhiteSpace = true;
596 // We output the space only after we stop getting
597 // whitespace so as not to output any whitespace
598 // at the end of the value.
599 if (lastWasWhiteSpace) {
600 lastWasWhiteSpace = false;
606 // update nesting level
625 // FIXME Why is this here?
633 // reading a string name
636 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
637 strName += lowercase(ch);
644 // replace the string with its assigned value or
645 // discard it if it's not assigned
646 if (strName.length()) {
647 VarMap::const_iterator pos = strings.find(strName);
648 if (pos != strings.end()) {
655 while (ifs && isSpace(ch)) {
662 // continue reading next value on concatenate with '#'
672 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
678 void InsetBibtex::parseBibTeXFiles() const
680 // This bibtex parser is a first step to parse bibtex files
683 // - it reads the whole bibtex entry and does a syntax check
684 // (matching delimiters, missing commas,...
685 // - it recovers from errors starting with the next @-character
686 // - it reads @string definitions and replaces them in the
688 // - it accepts more characters in keys or value names than
691 // Officially bibtex does only support ASCII, but in practice
692 // you can use the encoding of the main document as long as
693 // some elements like keys and names are pure ASCII. Therefore
694 // we convert the file from the buffer encoding.
695 // We don't restrict keys to ASCII in LyX, since our own
696 // InsetBibitem can generate non-ASCII keys, and nonstandard
697 // 8bit clean bibtex forks exist.
701 support::FileNameList const files = getBibFiles();
702 support::FileNameList::const_iterator it = files.begin();
703 support::FileNameList::const_iterator en = files.end();
704 for (; it != en; ++ it) {
705 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
706 ios_base::in, buffer().params().encoding().iconvName());
722 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
723 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
728 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
732 if (entryType == from_ascii("comment")) {
733 ifs.ignore(numeric_limits<int>::max(), '\n');
739 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
743 if ((ch != '(') && (ch != '{')) {
744 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
750 if (entryType == from_ascii("string")) {
752 // read string and add it to the strings map
753 // (or replace it's old value)
757 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
758 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
763 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
767 // next char must be an equal sign
769 if (!ifs || ch != '=') {
770 lyxerr << "BibTeX Parser: No `=' after string name: " <<
771 name << "." << std::endl;
775 if (!readValue(value, ifs, strings)) {
776 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
777 name << "." << std::endl;
781 strings[name] = value;
783 } else if (entryType == from_ascii("preamble")) {
785 // preamble definitions are discarded.
786 // can they be of any use in lyx?
789 if (!readValue(value, ifs, strings)) {
790 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
796 // Citation entry. Try to read the key.
799 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
800 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
801 entryType << "." << std::endl;
806 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
810 /////////////////////////////////////////////
811 // now we have a key, so we will add an entry
812 // (even if it's empty, as bibtex does)
814 // we now read the field = value pairs.
815 // all items must be separated by a comma. If
816 // it is missing the scanning of this entry is
817 // stopped and the next is searched.
821 BibTeXInfo keyvalmap(key, entryType);
823 bool readNext = removeWSAndComma(ifs);
825 while (ifs && readNext) {
828 if (!readTypeOrKey(name, ifs, from_ascii("="),
829 from_ascii("{}(),"), makeLowerCase) || !ifs)
832 // next char must be an equal sign
833 // FIXME Whitespace??
836 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
840 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
841 name << ", for key: " << key << "." << std::endl;
847 if (!readValue(value, ifs, strings)) {
848 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
849 name << ", for key: " << key << "." << std::endl;
853 keyvalmap[name] = value;
854 data += "\n\n" + value;
855 keylist.addFieldName(name);
856 readNext = removeWSAndComma(ifs);
860 keylist.addEntryType(entryType);
861 keyvalmap.setAllData(data);
862 keylist[key] = keyvalmap;
863 } //< else (citation entry)
865 } //< for loop over files
867 buffer().addBiblioInfo(keylist);
871 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
873 string texfile = changeExtension(to_utf8(filename), "bib");
874 // note that, if the filename can be found directly from the path,
875 // findtexfile will just return a FileName object for that path.
876 FileName file(findtexfile(texfile, "bib"));
878 file = FileName(makeAbsPath(texfile, buf.filePath()));
883 bool InsetBibtex::addDatabase(docstring const & db)
885 docstring bibfiles = getParam("bibfiles");
886 if (tokenPos(bibfiles, ',', db) != -1)
888 if (!bibfiles.empty())
890 setParam("bibfiles", bibfiles + db);
895 bool InsetBibtex::delDatabase(docstring const & db)
897 docstring bibfiles = getParam("bibfiles");
898 if (contains(bibfiles, db)) {
899 int const n = tokenPos(bibfiles, ',', db);
902 // this is not the first database
903 docstring tmp = ',' + bd;
904 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
906 // this is the first (or only) database
907 setParam("bibfiles", split(bibfiles, bd, ','));
915 void InsetBibtex::validate(LaTeXFeatures & features) const
917 if (features.bufferParams().use_bibtopic)
918 features.require("bibtopic");
920 // It'd be better to be able to get this from an InsetLayout, but at present
921 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
922 if (features.runparams().flavor == OutputParams::HTML)
923 features.addPreambleSnippet("<style type=\"text/css\">\n"
924 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
925 "span.bibtexlabel:before{ content: \"[\"; }\n"
926 "span.bibtexlabel:after{ content: \"] \"; }\n"
932 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
933 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
934 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
936 BiblioInfo const & bibinfo = buffer().masterBibInfo();
937 vector<docstring> const & cites = bibinfo.citedEntries();
938 CiteEngine const engine = buffer().params().citeEngine();
940 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
942 docstring reflabel = from_ascii("References");
943 Language const * l = buffer().params().language;
945 reflabel = translateIfPossible(reflabel, l->code());
947 xs << html::StartTag("h2", "class='bibtex'")
949 << html::EndTag("h2")
950 << html::StartTag("div", "class='bibtex'");
952 // Now we loop over the entries
953 vector<docstring>::const_iterator vit = cites.begin();
954 vector<docstring>::const_iterator const ven = cites.end();
955 for (; vit != ven; ++vit) {
956 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
957 if (biit == bibinfo.end())
959 BibTeXInfo const & entry = biit->second;
960 xs << html::StartTag("div", "class='bibtexentry'");
962 // The same name/id problem we have elsewhere.
963 string const attr = "id='" + to_utf8(entry.key()) + "'";
964 xs << html::CompTag("a", attr);
967 citekey = entry.citeNumber();
969 docstring const auth = entry.getAbbreviatedAuthor();
970 // we do it this way so as to access the xref, if necessary
971 // note that this also gives us the modifier
972 docstring const year = bibinfo.getYear(*vit, true);
973 if (!auth.empty() && !year.empty())
974 citekey = auth + ' ' + year;
976 if (citekey.empty()) {
977 citekey = entry.label();
979 citekey = entry.key();
981 xs << html::StartTag("span", "class='bibtexlabel'")
983 << html::EndTag("span");
984 // FIXME Right now, we are calling BibInfo::getInfo on the key,
985 // which will give us all the cross-referenced info. But for every
986 // entry, so there's a lot of repitition. This should be fixed.
987 xs << html::StartTag("span", "class='bibtexinfo'")
988 << XHTMLStream::ESCAPE_AND
989 << bibinfo.getInfo(entry.key(), buffer(), true)
990 << html::EndTag("span")
991 << html::EndTag("div")
994 xs << html::EndTag("div");
999 string InsetBibtex::contextMenuName() const
1001 return "context-bibtex";