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"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "output_xhtml.h"
28 #include "OutputParams.h"
29 #include "PDFOptions.h"
30 #include "TextClass.h"
32 #include "frontends/alert.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/ExceptionMessage.h"
38 #include "support/FileNameList.h"
39 #include "support/filetools.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/os.h"
43 #include "support/Path.h"
44 #include "support/textutils.h"
49 using namespace lyx::support;
53 namespace Alert = frontend::Alert;
54 namespace os = support::os;
57 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
58 : InsetCommand(buf, p)
60 buffer().invalidateBibinfoCache();
64 InsetBibtex::~InsetBibtex()
67 buffer().invalidateBibfileCache();
71 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
73 static ParamInfo param_info_;
74 if (param_info_.empty()) {
75 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
76 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
77 param_info_.add("options", ParamInfo::LYX_INTERNAL);
83 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
85 switch (cmd.action()) {
91 case LFUN_INSET_MODIFY: {
92 InsetCommandParams p(BIBTEX_CODE);
94 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
98 } catch (ExceptionMessage const & message) {
99 if (message.type_ == WarningException) {
100 Alert::warning(message.title_, message.details_);
101 cur.noScreenUpdate();
108 buffer().invalidateBibfileCache();
109 cur.forceBufferUpdate();
114 InsetCommand::doDispatch(cur, cmd);
120 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
121 FuncStatus & flag) const
123 switch (cmd.action()) {
124 case LFUN_INSET_EDIT:
125 flag.setEnabled(true);
129 return InsetCommand::getStatus(cur, cmd, flag);
134 void InsetBibtex::editDatabases() const
136 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
138 if (bibfilelist.empty())
141 int nr_databases = bibfilelist.size();
142 if (nr_databases > 1) {
143 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
144 "If you proceed, all of them will be opened."),
145 convert<docstring>(nr_databases));
146 int const ret = Alert::prompt(_("Open Databases?"),
147 message, 0, 1, _("&Cancel"), _("&Proceed"));
153 vector<docstring>::const_iterator it = bibfilelist.begin();
154 vector<docstring>::const_iterator en = bibfilelist.end();
155 for (; it != en; ++it) {
156 FileName const bibfile = getBibTeXPath(*it, buffer());
157 formats.edit(buffer(), bibfile,
158 formats.getFormatFromFile(bibfile));
163 docstring InsetBibtex::screenLabel() const
165 return _("BibTeX Generated Bibliography");
169 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
171 docstring item = from_ascii("* ");
172 docstring tip = _("Databases:") + "\n";
173 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
175 if (bibfilelist.empty()) {
179 vector<docstring>::const_iterator it = bibfilelist.begin();
180 vector<docstring>::const_iterator en = bibfilelist.end();
181 for (; it != en; ++it) {
189 docstring style = getParam("options"); // maybe empty! and with bibtotoc
190 docstring bibtotoc = from_ascii("bibtotoc");
191 if (prefixIs(style, bibtotoc)) {
193 if (contains(style, char_type(',')))
194 style = split(style, bibtotoc, char_type(','));
197 tip += _("Style File:") +"\n";
204 tip += "\n" + _("Lists:") + " ";
205 docstring btprint = getParam("btprint");
206 if (btprint == "btPrintAll")
207 tip += _("all references");
208 else if (btprint == "btPrintNotCited")
209 tip += _("all uncited references");
211 tip += _("all cited references");
215 tip += _("included in TOC");
222 static string normalizeName(Buffer const & buffer,
223 OutputParams const & runparams, string const & name, string const & ext)
225 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
226 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
232 return to_utf8(makeRelPath(from_utf8(fname),
233 from_utf8(buffer.masterBuffer()->filePath())));
237 void InsetBibtex::updateBuffer(ParIterator const &, UpdateType)
239 if (buffer().isBibInfoCacheValid())
245 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
247 // the sequence of the commands:
248 // 1. \bibliographystyle{style}
249 // 2. \addcontentsline{...} - if option bibtotoc set
250 // 3. \bibliography{database}
251 // and with bibtopic:
252 // 1. \bibliographystyle{style}
253 // 2. \begin{btSect}{database}
254 // 3. \btPrint{Cited|NotCited|All}
258 // If we are processing the LaTeX file in a temp directory then
259 // copy the .bib databases to this temp directory, mangling their
260 // names in the process. Store this mangled name in the list of
262 // (We need to do all this because BibTeX *really*, *really*
263 // can't handle "files with spaces" and Windows users tend to
264 // use such filenames.)
265 // Otherwise, store the (maybe absolute) path to the original,
266 // unmangled database name.
267 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
268 vector<docstring>::const_iterator it = bibfilelist.begin();
269 vector<docstring>::const_iterator en = bibfilelist.end();
270 odocstringstream dbs;
273 for (; it != en; ++it) {
274 string utf8input = to_utf8(*it);
276 normalizeName(buffer(), runparams, utf8input, ".bib");
277 FileName const try_in_file =
278 makeAbsPath(database + ".bib", buffer().filePath());
279 bool const not_from_texmf = try_in_file.isReadableFile();
281 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
283 // mangledFileName() needs the extension
284 DocFileName const in_file = DocFileName(try_in_file);
285 database = removeExtension(in_file.mangledFileName());
286 FileName const out_file = makeAbsPath(database + ".bib",
287 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 if (!isValidLaTeXFileName(database)) {
297 frontend::Alert::warning(_("Invalid filename"),
298 _("The following filename will cause troubles "
299 "when running the exported file through LaTeX: ") +
300 from_utf8(database));
302 if (!isValidDVIFileName(database)) {
303 frontend::Alert::warning(_("Problematic filename for DVI"),
304 _("The following filename can cause troubles "
305 "when running the exported file through LaTeX "
306 "and opening the resulting DVI: ") +
307 from_utf8(database), true);
316 dbs << from_utf8(latex_path(database));
318 docstring const db_out = dbs.str();
320 // Post this warning only once.
321 static bool warned_about_spaces = false;
322 if (!warned_about_spaces &&
323 runparams.nice && db_out.find(' ') != docstring::npos) {
324 warned_about_spaces = true;
325 Alert::warning(_("Export Warning!"),
326 _("There are spaces in the paths to your BibTeX databases.\n"
327 "BibTeX will be unable to find them."));
330 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
332 if (prefixIs(style, "bibtotoc")) {
333 bibtotoc = "bibtotoc";
334 if (contains(style, ','))
335 style = split(style, bibtotoc, ',');
341 if (!style.empty()) {
342 string base = normalizeName(buffer(), runparams, style, ".bst");
343 FileName const try_in_file =
344 makeAbsPath(base + ".bst", buffer().filePath());
345 bool const not_from_texmf = try_in_file.isReadableFile();
346 // If this style does not come from texmf and we are not
347 // exporting to .tex copy it to the tmp directory.
348 // This prevents problems with spaces and 8bit charcaters
350 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
352 // use new style name
353 DocFileName const in_file = DocFileName(try_in_file);
354 base = removeExtension(in_file.mangledFileName());
355 FileName const out_file = makeAbsPath(base + ".bst",
356 buffer().masterBuffer()->temppath());
357 bool const success = in_file.copyTo(out_file);
359 lyxerr << "Failed to copy '" << in_file
360 << "' to '" << out_file << "'"
365 os << "\\bibliographystyle{"
366 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
371 // Post this warning only once.
372 static bool warned_about_bst_spaces = false;
373 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
374 warned_about_bst_spaces = true;
375 Alert::warning(_("Export Warning!"),
376 _("There are spaces in the path to your BibTeX style file.\n"
377 "BibTeX will be unable to find it."));
380 if (!db_out.empty() && buffer().params().use_bibtopic) {
381 os << "\\begin{btSect}{" << db_out << "}\n";
382 docstring btprint = getParam("btprint");
385 btprint = from_ascii("btPrintCited");
386 os << "\\" << btprint << "\n"
387 << "\\end{btSect}\n";
392 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
393 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
394 if (buffer().params().pdfoptions().use_hyperref)
395 os << "\\phantomsection";
396 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
397 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
398 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
399 os << "\\addcontentsline{toc}{section}{\\refname}";
402 if (!db_out.empty() && !buffer().params().use_bibtopic) {
403 docstring btprint = getParam("btprint");
404 if (btprint == "btPrintAll") {
405 os << "\\nocite{*}\n";
408 os << "\\bibliography{" << db_out << "}\n";
416 support::FileNameList InsetBibtex::getBibFiles() const
418 FileName path(buffer().filePath());
419 support::PathChanger p(path);
421 support::FileNameList vec;
423 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
424 vector<docstring>::const_iterator it = bibfilelist.begin();
425 vector<docstring>::const_iterator en = bibfilelist.end();
426 for (; it != en; ++it) {
427 FileName const file = getBibTeXPath(*it, buffer());
432 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
441 // methods for parsing bibtex files
443 typedef map<docstring, docstring> VarMap;
445 /// remove whitespace characters, optionally a single comma,
446 /// and further whitespace characters from the stream.
447 /// @return true if a comma was found, false otherwise
449 bool removeWSAndComma(ifdocstream & ifs) {
458 } while (ifs && isSpace(ch));
471 } while (ifs && isSpace(ch));
486 /// remove whitespace characters, read characer sequence
487 /// not containing whitespace characters or characters in
488 /// delimChars, and remove further whitespace characters.
490 /// @return true if a string of length > 0 could be read.
492 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
493 docstring const & delimChars, docstring const & illegalChars,
506 } while (ifs && isSpace(ch));
512 bool legalChar = true;
513 while (ifs && !isSpace(ch) &&
514 delimChars.find(ch) == docstring::npos &&
515 (legalChar = (illegalChars.find(ch) == docstring::npos))
518 if (chCase == makeLowerCase)
519 val += lowercase(ch);
531 while (ifs && isSpace(ch)) {
539 return val.length() > 0;
542 /// read subsequent bibtex values that are delimited with a #-character.
543 /// Concatenate all parts and replace names with the associated string in
544 /// the variable strings.
545 /// @return true if reading was successfull (all single parts were delimited
547 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
560 } while (ifs && isSpace(ch));
565 // check for field type
568 // read integer value
572 } while (ifs && isDigit(ch));
577 } else if (ch == '"' || ch == '{') {
579 char_type delim = ch == '"' ? '"': '}';
584 } while (ifs && isSpace(ch));
589 // We now have the first non-whitespace character
590 // We'll collapse adjacent whitespace.
591 bool lastWasWhiteSpace = false;
593 // inside this delimited text braces must match.
594 // Thus we can have a closing delimiter only
595 // when nestLevel == 0
598 while (ifs && (nestLevel > 0 || ch != delim)) {
600 lastWasWhiteSpace = true;
604 // We output the space only after we stop getting
605 // whitespace so as not to output any whitespace
606 // at the end of the value.
607 if (lastWasWhiteSpace) {
608 lastWasWhiteSpace = false;
614 // update nesting level
633 // FIXME Why is this here?
641 // reading a string name
644 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
645 strName += lowercase(ch);
652 // replace the string with its assigned value or
653 // discard it if it's not assigned
654 if (strName.length()) {
655 VarMap::const_iterator pos = strings.find(strName);
656 if (pos != strings.end()) {
663 while (ifs && isSpace(ch)) {
670 // continue reading next value on concatenate with '#'
680 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
686 void InsetBibtex::parseBibTeXFiles() const
688 // This bibtex parser is a first step to parse bibtex files
691 // - it reads the whole bibtex entry and does a syntax check
692 // (matching delimiters, missing commas,...
693 // - it recovers from errors starting with the next @-character
694 // - it reads @string definitions and replaces them in the
696 // - it accepts more characters in keys or value names than
699 // Officially bibtex does only support ASCII, but in practice
700 // you can use the encoding of the main document as long as
701 // some elements like keys and names are pure ASCII. Therefore
702 // we convert the file from the buffer encoding.
703 // We don't restrict keys to ASCII in LyX, since our own
704 // InsetBibitem can generate non-ASCII keys, and nonstandard
705 // 8bit clean bibtex forks exist.
709 support::FileNameList const files = getBibFiles();
710 support::FileNameList::const_iterator it = files.begin();
711 support::FileNameList::const_iterator en = files.end();
712 for (; it != en; ++ it) {
713 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
714 ios_base::in, buffer().params().encoding().iconvName());
730 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
731 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
736 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
740 if (entryType == from_ascii("comment")) {
741 ifs.ignore(numeric_limits<int>::max(), '\n');
747 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
751 if ((ch != '(') && (ch != '{')) {
752 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
758 if (entryType == from_ascii("string")) {
760 // read string and add it to the strings map
761 // (or replace it's old value)
765 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
766 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
771 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
775 // next char must be an equal sign
777 if (!ifs || ch != '=') {
778 lyxerr << "BibTeX Parser: No `=' after string name: " <<
779 name << "." << std::endl;
783 if (!readValue(value, ifs, strings)) {
784 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
785 name << "." << std::endl;
789 strings[name] = value;
791 } else if (entryType == from_ascii("preamble")) {
793 // preamble definitions are discarded.
794 // can they be of any use in lyx?
797 if (!readValue(value, ifs, strings)) {
798 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
804 // Citation entry. Try to read the key.
807 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
808 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
809 entryType << "." << std::endl;
814 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
818 /////////////////////////////////////////////
819 // now we have a key, so we will add an entry
820 // (even if it's empty, as bibtex does)
822 // we now read the field = value pairs.
823 // all items must be separated by a comma. If
824 // it is missing the scanning of this entry is
825 // stopped and the next is searched.
829 BibTeXInfo keyvalmap(key, entryType);
831 bool readNext = removeWSAndComma(ifs);
833 while (ifs && readNext) {
836 if (!readTypeOrKey(name, ifs, from_ascii("="),
837 from_ascii("{}(),"), makeLowerCase) || !ifs)
840 // next char must be an equal sign
841 // FIXME Whitespace??
844 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
848 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
849 name << ", for key: " << key << "." << std::endl;
855 if (!readValue(value, ifs, strings)) {
856 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
857 name << ", for key: " << key << "." << std::endl;
861 keyvalmap[name] = value;
862 data += "\n\n" + value;
863 keylist.addFieldName(name);
864 readNext = removeWSAndComma(ifs);
868 keylist.addEntryType(entryType);
869 keyvalmap.setAllData(data);
870 keylist[key] = keyvalmap;
871 } //< else (citation entry)
873 } //< for loop over files
875 buffer().addBiblioInfo(keylist);
879 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
881 string texfile = changeExtension(to_utf8(filename), "bib");
882 // note that, if the filename can be found directly from the path,
883 // findtexfile will just return a FileName object for that path.
884 FileName file(findtexfile(texfile, "bib"));
886 file = FileName(makeAbsPath(texfile, buf.filePath()));
891 bool InsetBibtex::addDatabase(docstring const & db)
893 docstring bibfiles = getParam("bibfiles");
894 if (tokenPos(bibfiles, ',', db) != -1)
896 if (!bibfiles.empty())
898 setParam("bibfiles", bibfiles + db);
903 bool InsetBibtex::delDatabase(docstring const & db)
905 docstring bibfiles = getParam("bibfiles");
906 if (contains(bibfiles, db)) {
907 int const n = tokenPos(bibfiles, ',', db);
910 // this is not the first database
911 docstring tmp = ',' + bd;
912 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
914 // this is the first (or only) database
915 setParam("bibfiles", split(bibfiles, bd, ','));
923 void InsetBibtex::validate(LaTeXFeatures & features) const
925 if (features.bufferParams().use_bibtopic)
926 features.require("bibtopic");
928 // It'd be better to be able to get this from an InsetLayout, but at present
929 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
930 if (features.runparams().flavor == OutputParams::HTML)
931 features.addPreambleSnippet("<style type=\"text/css\">\n"
932 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
933 "span.bibtexlabel:before{ content: \"[\"; }\n"
934 "span.bibtexlabel:after{ content: \"] \"; }\n"
940 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
941 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
942 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
944 BiblioInfo const & bibinfo = buffer().masterBibInfo();
945 vector<docstring> const & cites = bibinfo.citedEntries();
946 CiteEngine const engine = buffer().params().citeEngine();
948 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
950 docstring reflabel = from_ascii("References");
951 Language const * l = buffer().params().language;
953 reflabel = translateIfPossible(reflabel, l->code());
955 xs << html::StartTag("h2", "class='bibtex'")
957 << html::EndTag("h2")
958 << html::StartTag("div", "class='bibtex'");
960 // Now we loop over the entries
961 vector<docstring>::const_iterator vit = cites.begin();
962 vector<docstring>::const_iterator const ven = cites.end();
963 for (; vit != ven; ++vit) {
964 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
965 if (biit == bibinfo.end())
967 BibTeXInfo const & entry = biit->second;
968 xs << html::StartTag("div", "class='bibtexentry'");
970 // The same name/id problem we have elsewhere.
971 string const attr = "id='" + to_utf8(entry.key()) + "'";
972 xs << html::CompTag("a", attr);
975 citekey = entry.citeNumber();
977 docstring const auth = entry.getAbbreviatedAuthor();
978 // we do it this way so as to access the xref, if necessary
979 // note that this also gives us the modifier
980 docstring const year = bibinfo.getYear(*vit, true);
981 if (!auth.empty() && !year.empty())
982 citekey = auth + ' ' + year;
984 if (citekey.empty()) {
985 citekey = entry.label();
987 citekey = entry.key();
989 xs << html::StartTag("span", "class='bibtexlabel'")
991 << html::EndTag("span");
992 // FIXME Right now, we are calling BibInfo::getInfo on the key,
993 // which will give us all the cross-referenced info. But for every
994 // entry, so there's a lot of repitition. This should be fixed.
995 xs << html::StartTag("span", "class='bibtexinfo'")
996 << XHTMLStream::ESCAPE_AND
997 << bibinfo.getInfo(entry.key(), buffer(), true)
998 << html::EndTag("span")
999 << html::EndTag("div");
1002 xs << html::EndTag("div");
1007 docstring InsetBibtex::contextMenuName() const
1009 return from_ascii("context-bibtex");