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();
65 InsetBibtex::~InsetBibtex()
68 buffer().invalidateBibfileCache();
72 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
74 static ParamInfo param_info_;
75 if (param_info_.empty()) {
76 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
77 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
78 param_info_.add("options", ParamInfo::LYX_INTERNAL);
84 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
86 switch (cmd.action()) {
92 case LFUN_INSET_MODIFY: {
93 InsetCommandParams p(BIBTEX_CODE);
95 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
99 } catch (ExceptionMessage const & message) {
100 if (message.type_ == WarningException) {
101 Alert::warning(message.title_, message.details_);
102 cur.noScreenUpdate();
110 buffer().invalidateBibfileCache();
111 cur.forceBufferUpdate();
116 InsetCommand::doDispatch(cur, cmd);
122 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
123 FuncStatus & flag) const
125 switch (cmd.action()) {
126 case LFUN_INSET_EDIT:
127 flag.setEnabled(true);
131 return InsetCommand::getStatus(cur, cmd, flag);
136 void InsetBibtex::editDatabases() const
138 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
140 if (bibfilelist.empty())
143 int nr_databases = bibfilelist.size();
144 if (nr_databases > 1) {
145 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
146 "If you proceed, all of them will be opened."),
147 convert<docstring>(nr_databases));
148 int const ret = Alert::prompt(_("Open Databases?"),
149 message, 0, 1, _("&Cancel"), _("&Proceed"));
155 vector<docstring>::const_iterator it = bibfilelist.begin();
156 vector<docstring>::const_iterator en = bibfilelist.end();
157 for (; it != en; ++it) {
158 FileName const bibfile = getBibTeXPath(*it, buffer());
159 formats.edit(buffer(), bibfile,
160 formats.getFormatFromFile(bibfile));
165 docstring InsetBibtex::screenLabel() const
167 return _("BibTeX Generated Bibliography");
171 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
173 docstring item = from_ascii("* ");
174 docstring tip = _("Databases:") + "\n";
175 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
177 if (bibfilelist.empty()) {
181 vector<docstring>::const_iterator it = bibfilelist.begin();
182 vector<docstring>::const_iterator en = bibfilelist.end();
183 for (; it != en; ++it) {
191 docstring style = getParam("options"); // maybe empty! and with bibtotoc
192 docstring bibtotoc = from_ascii("bibtotoc");
193 if (prefixIs(style, bibtotoc)) {
195 if (contains(style, char_type(',')))
196 style = split(style, bibtotoc, char_type(','));
199 tip += _("Style File:") +"\n";
206 tip += "\n" + _("Lists:") + " ";
207 docstring btprint = getParam("btprint");
208 if (btprint == "btPrintAll")
209 tip += _("all references");
210 else if (btprint == "btPrintNotCited")
211 tip += _("all uncited references");
213 tip += _("all cited references");
217 tip += _("included in TOC");
224 static string normalizeName(Buffer const & buffer,
225 OutputParams const & runparams, string const & name, string const & ext)
227 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
228 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
234 return to_utf8(makeRelPath(from_utf8(fname),
235 from_utf8(buffer.masterBuffer()->filePath())));
239 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
241 // the sequence of the commands:
242 // 1. \bibliographystyle{style}
243 // 2. \addcontentsline{...} - if option bibtotoc set
244 // 3. \bibliography{database}
245 // and with bibtopic:
246 // 1. \bibliographystyle{style}
247 // 2. \begin{btSect}{database}
248 // 3. \btPrint{Cited|NotCited|All}
252 // If we are processing the LaTeX file in a temp directory then
253 // copy the .bib databases to this temp directory, mangling their
254 // names in the process. Store this mangled name in the list of
256 // (We need to do all this because BibTeX *really*, *really*
257 // can't handle "files with spaces" and Windows users tend to
258 // use such filenames.)
259 // Otherwise, store the (maybe absolute) path to the original,
260 // unmangled database name.
261 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
262 vector<docstring>::const_iterator it = bibfilelist.begin();
263 vector<docstring>::const_iterator en = bibfilelist.end();
264 odocstringstream dbs;
267 // determine the export format
268 string const tex_format = flavor2format(runparams.flavor);
270 for (; it != en; ++it) {
271 string utf8input = to_utf8(*it);
273 normalizeName(buffer(), runparams, utf8input, ".bib");
274 FileName const try_in_file =
275 makeAbsPath(database + ".bib", buffer().filePath());
276 bool const not_from_texmf = try_in_file.isReadableFile();
278 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
280 // mangledFileName() needs the extension
281 DocFileName const in_file = DocFileName(try_in_file);
282 database = removeExtension(in_file.mangledFileName());
283 FileName const out_file = makeAbsPath(database + ".bib",
284 buffer().masterBuffer()->temppath());
285 bool const success = in_file.copyTo(out_file);
287 lyxerr << "Failed to copy '" << in_file
288 << "' to '" << out_file << "'"
291 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
292 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
293 if (!isValidLaTeXFileName(database)) {
294 frontend::Alert::warning(_("Invalid filename"),
295 _("The following filename will cause troubles "
296 "when running the exported file through LaTeX: ") +
297 from_utf8(database));
299 if (!isValidDVIFileName(database)) {
300 frontend::Alert::warning(_("Problematic filename for DVI"),
301 _("The following filename can cause troubles "
302 "when running the exported file through LaTeX "
303 "and opening the resulting DVI: ") +
304 from_utf8(database), true);
313 dbs << from_utf8(latex_path(database));
315 docstring const db_out = dbs.str();
317 // Post this warning only once.
318 static bool warned_about_spaces = false;
319 if (!warned_about_spaces &&
320 runparams.nice && db_out.find(' ') != docstring::npos) {
321 warned_about_spaces = true;
322 Alert::warning(_("Export Warning!"),
323 _("There are spaces in the paths to your BibTeX databases.\n"
324 "BibTeX will be unable to find them."));
327 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
329 if (prefixIs(style, "bibtotoc")) {
330 bibtotoc = "bibtotoc";
331 if (contains(style, ','))
332 style = split(style, bibtotoc, ',');
335 if (!style.empty()) {
336 string base = normalizeName(buffer(), runparams, style, ".bst");
337 FileName const try_in_file =
338 makeAbsPath(base + ".bst", buffer().filePath());
339 bool const not_from_texmf = try_in_file.isReadableFile();
340 // If this style does not come from texmf and we are not
341 // exporting to .tex copy it to the tmp directory.
342 // This prevents problems with spaces and 8bit charcaters
344 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
346 // use new style name
347 DocFileName const in_file = DocFileName(try_in_file);
348 base = removeExtension(in_file.mangledFileName());
349 FileName const out_file = makeAbsPath(base + ".bst",
350 buffer().masterBuffer()->temppath());
351 bool const success = in_file.copyTo(out_file);
353 lyxerr << "Failed to copy '" << in_file
354 << "' to '" << out_file << "'"
359 os << "\\bibliographystyle{"
360 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
364 // Post this warning only once.
365 static bool warned_about_bst_spaces = false;
366 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
367 warned_about_bst_spaces = true;
368 Alert::warning(_("Export Warning!"),
369 _("There are spaces in the path to your BibTeX style file.\n"
370 "BibTeX will be unable to find it."));
373 if (!db_out.empty() && buffer().params().use_bibtopic) {
374 os << "\\begin{btSect}{" << db_out << "}\n";
375 docstring btprint = getParam("btprint");
378 btprint = from_ascii("btPrintCited");
379 os << "\\" << btprint << "\n"
380 << "\\end{btSect}\n";
384 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
385 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
386 if (buffer().params().pdfoptions().use_hyperref)
387 os << "\\phantomsection";
388 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
389 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
390 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
391 os << "\\addcontentsline{toc}{section}{\\refname}";
394 if (!db_out.empty() && !buffer().params().use_bibtopic) {
395 docstring btprint = getParam("btprint");
396 if (btprint == "btPrintAll") {
397 os << "\\nocite{*}\n";
399 os << "\\bibliography{" << db_out << "}\n";
404 support::FileNameList InsetBibtex::getBibFiles() const
406 FileName path(buffer().filePath());
407 support::PathChanger p(path);
409 support::FileNameList vec;
411 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
412 vector<docstring>::const_iterator it = bibfilelist.begin();
413 vector<docstring>::const_iterator en = bibfilelist.end();
414 for (; it != en; ++it) {
415 FileName const file = getBibTeXPath(*it, buffer());
420 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
429 // methods for parsing bibtex files
431 typedef map<docstring, docstring> VarMap;
433 /// remove whitespace characters, optionally a single comma,
434 /// and further whitespace characters from the stream.
435 /// @return true if a comma was found, false otherwise
437 bool removeWSAndComma(ifdocstream & ifs) {
446 } while (ifs && isSpace(ch));
459 } while (ifs && isSpace(ch));
474 /// remove whitespace characters, read characer sequence
475 /// not containing whitespace characters or characters in
476 /// delimChars, and remove further whitespace characters.
478 /// @return true if a string of length > 0 could be read.
480 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
481 docstring const & delimChars, docstring const & illegalChars,
494 } while (ifs && isSpace(ch));
500 bool legalChar = true;
501 while (ifs && !isSpace(ch) &&
502 delimChars.find(ch) == docstring::npos &&
503 (legalChar = (illegalChars.find(ch) == docstring::npos))
506 if (chCase == makeLowerCase)
507 val += lowercase(ch);
519 while (ifs && isSpace(ch)) {
527 return val.length() > 0;
530 /// read subsequent bibtex values that are delimited with a #-character.
531 /// Concatenate all parts and replace names with the associated string in
532 /// the variable strings.
533 /// @return true if reading was successfull (all single parts were delimited
535 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
548 } while (ifs && isSpace(ch));
553 // check for field type
554 if (isDigitASCII(ch)) {
556 // read integer value
560 } while (ifs && isDigitASCII(ch));
565 } else if (ch == '"' || ch == '{') {
567 char_type delim = ch == '"' ? '"': '}';
572 } while (ifs && isSpace(ch));
577 // We now have the first non-whitespace character
578 // We'll collapse adjacent whitespace.
579 bool lastWasWhiteSpace = false;
581 // inside this delimited text braces must match.
582 // Thus we can have a closing delimiter only
583 // when nestLevel == 0
586 while (ifs && (nestLevel > 0 || ch != delim)) {
588 lastWasWhiteSpace = true;
592 // We output the space only after we stop getting
593 // whitespace so as not to output any whitespace
594 // at the end of the value.
595 if (lastWasWhiteSpace) {
596 lastWasWhiteSpace = false;
602 // update nesting level
621 // FIXME Why is this here?
629 // reading a string name
632 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
633 strName += lowercase(ch);
640 // replace the string with its assigned value or
641 // discard it if it's not assigned
642 if (strName.length()) {
643 VarMap::const_iterator pos = strings.find(strName);
644 if (pos != strings.end()) {
651 while (ifs && isSpace(ch)) {
658 // continue reading next value on concatenate with '#'
668 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
674 void InsetBibtex::parseBibTeXFiles() const
676 // This bibtex parser is a first step to parse bibtex files
679 // - it reads the whole bibtex entry and does a syntax check
680 // (matching delimiters, missing commas,...
681 // - it recovers from errors starting with the next @-character
682 // - it reads @string definitions and replaces them in the
684 // - it accepts more characters in keys or value names than
687 // Officially bibtex does only support ASCII, but in practice
688 // you can use the encoding of the main document as long as
689 // some elements like keys and names are pure ASCII. Therefore
690 // we convert the file from the buffer encoding.
691 // We don't restrict keys to ASCII in LyX, since our own
692 // InsetBibitem can generate non-ASCII keys, and nonstandard
693 // 8bit clean bibtex forks exist.
697 support::FileNameList const files = getBibFiles();
698 support::FileNameList::const_iterator it = files.begin();
699 support::FileNameList::const_iterator en = files.end();
700 for (; it != en; ++ it) {
701 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
702 ios_base::in, buffer().params().encoding().iconvName());
718 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
719 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
724 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
728 if (entryType == from_ascii("comment")) {
729 ifs.ignore(numeric_limits<int>::max(), '\n');
735 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
739 if ((ch != '(') && (ch != '{')) {
740 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
746 if (entryType == from_ascii("string")) {
748 // read string and add it to the strings map
749 // (or replace it's old value)
753 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
754 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
759 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
763 // next char must be an equal sign
765 if (!ifs || ch != '=') {
766 lyxerr << "BibTeX Parser: No `=' after string name: " <<
767 name << "." << std::endl;
771 if (!readValue(value, ifs, strings)) {
772 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
773 name << "." << std::endl;
777 strings[name] = value;
779 } else if (entryType == from_ascii("preamble")) {
781 // preamble definitions are discarded.
782 // can they be of any use in lyx?
785 if (!readValue(value, ifs, strings)) {
786 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
792 // Citation entry. Try to read the key.
795 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
796 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
797 entryType << "." << std::endl;
802 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
806 /////////////////////////////////////////////
807 // now we have a key, so we will add an entry
808 // (even if it's empty, as bibtex does)
810 // we now read the field = value pairs.
811 // all items must be separated by a comma. If
812 // it is missing the scanning of this entry is
813 // stopped and the next is searched.
817 BibTeXInfo keyvalmap(key, entryType);
819 bool readNext = removeWSAndComma(ifs);
821 while (ifs && readNext) {
824 if (!readTypeOrKey(name, ifs, from_ascii("="),
825 from_ascii("{}(),"), makeLowerCase) || !ifs)
828 // next char must be an equal sign
829 // FIXME Whitespace??
832 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
836 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
837 name << ", for key: " << key << "." << std::endl;
843 if (!readValue(value, ifs, strings)) {
844 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
845 name << ", for key: " << key << "." << std::endl;
849 keyvalmap[name] = value;
850 data += "\n\n" + value;
851 keylist.addFieldName(name);
852 readNext = removeWSAndComma(ifs);
856 keylist.addEntryType(entryType);
857 keyvalmap.setAllData(data);
858 keylist[key] = keyvalmap;
859 } //< else (citation entry)
861 } //< for loop over files
863 buffer().addBiblioInfo(keylist);
867 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
869 string texfile = changeExtension(to_utf8(filename), "bib");
870 // note that, if the filename can be found directly from the path,
871 // findtexfile will just return a FileName object for that path.
872 FileName file(findtexfile(texfile, "bib"));
874 file = FileName(makeAbsPath(texfile, buf.filePath()));
879 bool InsetBibtex::addDatabase(docstring const & db)
881 docstring bibfiles = getParam("bibfiles");
882 if (tokenPos(bibfiles, ',', db) != -1)
884 if (!bibfiles.empty())
886 setParam("bibfiles", bibfiles + db);
891 bool InsetBibtex::delDatabase(docstring const & db)
893 docstring bibfiles = getParam("bibfiles");
894 if (contains(bibfiles, db)) {
895 int const n = tokenPos(bibfiles, ',', db);
898 // this is not the first database
899 docstring tmp = ',' + bd;
900 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
902 // this is the first (or only) database
903 setParam("bibfiles", split(bibfiles, bd, ','));
911 void InsetBibtex::validate(LaTeXFeatures & features) const
913 if (features.bufferParams().use_bibtopic)
914 features.require("bibtopic");
916 // It'd be better to be able to get this from an InsetLayout, but at present
917 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
918 if (features.runparams().flavor == OutputParams::HTML)
919 features.addPreambleSnippet("<style type=\"text/css\">\n"
920 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
921 "span.bibtexlabel:before{ content: \"[\"; }\n"
922 "span.bibtexlabel:after{ content: \"] \"; }\n"
928 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
929 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
930 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
932 BiblioInfo const & bibinfo = buffer().masterBibInfo();
933 vector<docstring> const & cites = bibinfo.citedEntries();
934 CiteEngine const engine = buffer().params().citeEngine();
936 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
938 docstring reflabel = from_ascii("References");
939 Language const * l = buffer().params().language;
941 reflabel = translateIfPossible(reflabel, l->code());
943 xs << html::StartTag("h2", "class='bibtex'")
945 << html::EndTag("h2")
946 << html::StartTag("div", "class='bibtex'");
948 // Now we loop over the entries
949 vector<docstring>::const_iterator vit = cites.begin();
950 vector<docstring>::const_iterator const ven = cites.end();
951 for (; vit != ven; ++vit) {
952 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
953 if (biit == bibinfo.end())
955 BibTeXInfo const & entry = biit->second;
956 xs << html::StartTag("div", "class='bibtexentry'");
958 // The same name/id problem we have elsewhere.
959 string const attr = "id='" + to_utf8(entry.key()) + "'";
960 xs << html::CompTag("a", attr);
963 citekey = entry.citeNumber();
965 docstring const auth = entry.getAbbreviatedAuthor();
966 // we do it this way so as to access the xref, if necessary
967 // note that this also gives us the modifier
968 docstring const year = bibinfo.getYear(*vit, true);
969 if (!auth.empty() && !year.empty())
970 citekey = auth + ' ' + year;
972 if (citekey.empty()) {
973 citekey = entry.label();
975 citekey = entry.key();
977 xs << html::StartTag("span", "class='bibtexlabel'")
979 << html::EndTag("span");
980 // FIXME Right now, we are calling BibInfo::getInfo on the key,
981 // which will give us all the cross-referenced info. But for every
982 // entry, so there's a lot of repitition. This should be fixed.
983 xs << html::StartTag("span", "class='bibtexinfo'")
984 << XHTMLStream::ESCAPE_AND
985 << bibinfo.getInfo(entry.key(), buffer(), true)
986 << html::EndTag("span")
987 << html::EndTag("div")
990 xs << html::EndTag("div");
995 string InsetBibtex::contextMenuName() const
997 return "context-bibtex";