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();
109 buffer().invalidateBibfileCache();
110 cur.forceBufferUpdate();
115 InsetCommand::doDispatch(cur, cmd);
121 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
122 FuncStatus & flag) const
124 switch (cmd.action()) {
125 case LFUN_INSET_EDIT:
126 flag.setEnabled(true);
130 return InsetCommand::getStatus(cur, cmd, flag);
135 void InsetBibtex::editDatabases() const
137 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
139 if (bibfilelist.empty())
142 int nr_databases = bibfilelist.size();
143 if (nr_databases > 1) {
144 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
145 "If you proceed, all of them will be opened."),
146 convert<docstring>(nr_databases));
147 int const ret = Alert::prompt(_("Open Databases?"),
148 message, 0, 1, _("&Cancel"), _("&Proceed"));
154 vector<docstring>::const_iterator it = bibfilelist.begin();
155 vector<docstring>::const_iterator en = bibfilelist.end();
156 for (; it != en; ++it) {
157 FileName const bibfile = getBibTeXPath(*it, buffer());
158 formats.edit(buffer(), bibfile,
159 formats.getFormatFromFile(bibfile));
164 docstring InsetBibtex::screenLabel() const
166 return _("BibTeX Generated Bibliography");
170 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
172 docstring item = from_ascii("* ");
173 docstring tip = _("Databases:") + "\n";
174 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
176 if (bibfilelist.empty()) {
180 vector<docstring>::const_iterator it = bibfilelist.begin();
181 vector<docstring>::const_iterator en = bibfilelist.end();
182 for (; it != en; ++it) {
190 docstring style = getParam("options"); // maybe empty! and with bibtotoc
191 docstring bibtotoc = from_ascii("bibtotoc");
192 if (prefixIs(style, bibtotoc)) {
194 if (contains(style, char_type(',')))
195 style = split(style, bibtotoc, char_type(','));
198 tip += _("Style File:") +"\n";
205 tip += "\n" + _("Lists:") + " ";
206 docstring btprint = getParam("btprint");
207 if (btprint == "btPrintAll")
208 tip += _("all references");
209 else if (btprint == "btPrintNotCited")
210 tip += _("all uncited references");
212 tip += _("all cited references");
216 tip += _("included in TOC");
223 static string normalizeName(Buffer const & buffer,
224 OutputParams const & runparams, string const & name, string const & ext)
226 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
227 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
233 return to_utf8(makeRelPath(from_utf8(fname),
234 from_utf8(buffer.masterBuffer()->filePath())));
238 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
240 // the sequence of the commands:
241 // 1. \bibliographystyle{style}
242 // 2. \addcontentsline{...} - if option bibtotoc set
243 // 3. \bibliography{database}
244 // and with bibtopic:
245 // 1. \bibliographystyle{style}
246 // 2. \begin{btSect}{database}
247 // 3. \btPrint{Cited|NotCited|All}
251 // If we are processing the LaTeX file in a temp directory then
252 // copy the .bib databases to this temp directory, mangling their
253 // names in the process. Store this mangled name in the list of
255 // (We need to do all this because BibTeX *really*, *really*
256 // can't handle "files with spaces" and Windows users tend to
257 // use such filenames.)
258 // Otherwise, store the (maybe absolute) path to the original,
259 // unmangled database name.
260 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
261 vector<docstring>::const_iterator it = bibfilelist.begin();
262 vector<docstring>::const_iterator en = bibfilelist.end();
263 odocstringstream dbs;
266 for (; it != en; ++it) {
267 string utf8input = to_utf8(*it);
269 normalizeName(buffer(), runparams, utf8input, ".bib");
270 FileName const try_in_file =
271 makeAbsPath(database + ".bib", buffer().filePath());
272 bool const not_from_texmf = try_in_file.isReadableFile();
274 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
276 // mangledFileName() needs the extension
277 DocFileName const in_file = DocFileName(try_in_file);
278 database = removeExtension(in_file.mangledFileName());
279 FileName const out_file = makeAbsPath(database + ".bib",
280 buffer().masterBuffer()->temppath());
282 bool const success = in_file.copyTo(out_file);
284 lyxerr << "Failed to copy '" << in_file
285 << "' to '" << out_file << "'"
288 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
289 if (!isValidLaTeXFileName(database)) {
290 frontend::Alert::warning(_("Invalid filename"),
291 _("The following filename will cause troubles "
292 "when running the exported file through LaTeX: ") +
293 from_utf8(database));
295 if (!isValidDVIFileName(database)) {
296 frontend::Alert::warning(_("Problematic filename for DVI"),
297 _("The following filename can cause troubles "
298 "when running the exported file through LaTeX "
299 "and opening the resulting DVI: ") +
300 from_utf8(database), true);
309 dbs << from_utf8(latex_path(database));
311 docstring const db_out = dbs.str();
313 // Post this warning only once.
314 static bool warned_about_spaces = false;
315 if (!warned_about_spaces &&
316 runparams.nice && db_out.find(' ') != docstring::npos) {
317 warned_about_spaces = true;
318 Alert::warning(_("Export Warning!"),
319 _("There are spaces in the paths to your BibTeX databases.\n"
320 "BibTeX will be unable to find them."));
323 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
325 if (prefixIs(style, "bibtotoc")) {
326 bibtotoc = "bibtotoc";
327 if (contains(style, ','))
328 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")))
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";
380 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
381 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
382 if (buffer().params().pdfoptions().use_hyperref)
383 os << "\\phantomsection";
384 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
385 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
386 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
387 os << "\\addcontentsline{toc}{section}{\\refname}";
390 if (!db_out.empty() && !buffer().params().use_bibtopic) {
391 docstring btprint = getParam("btprint");
392 if (btprint == "btPrintAll") {
393 os << "\\nocite{*}\n";
395 os << "\\bibliography{" << db_out << "}\n";
400 support::FileNameList InsetBibtex::getBibFiles() const
402 FileName path(buffer().filePath());
403 support::PathChanger p(path);
405 support::FileNameList vec;
407 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
408 vector<docstring>::const_iterator it = bibfilelist.begin();
409 vector<docstring>::const_iterator en = bibfilelist.end();
410 for (; it != en; ++it) {
411 FileName const file = getBibTeXPath(*it, buffer());
416 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
425 // methods for parsing bibtex files
427 typedef map<docstring, docstring> VarMap;
429 /// remove whitespace characters, optionally a single comma,
430 /// and further whitespace characters from the stream.
431 /// @return true if a comma was found, false otherwise
433 bool removeWSAndComma(ifdocstream & ifs) {
442 } while (ifs && isSpace(ch));
455 } while (ifs && isSpace(ch));
470 /// remove whitespace characters, read characer sequence
471 /// not containing whitespace characters or characters in
472 /// delimChars, and remove further whitespace characters.
474 /// @return true if a string of length > 0 could be read.
476 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
477 docstring const & delimChars, docstring const & illegalChars,
490 } while (ifs && isSpace(ch));
496 bool legalChar = true;
497 while (ifs && !isSpace(ch) &&
498 delimChars.find(ch) == docstring::npos &&
499 (legalChar = (illegalChars.find(ch) == docstring::npos))
502 if (chCase == makeLowerCase)
503 val += lowercase(ch);
515 while (ifs && isSpace(ch)) {
523 return val.length() > 0;
526 /// read subsequent bibtex values that are delimited with a #-character.
527 /// Concatenate all parts and replace names with the associated string in
528 /// the variable strings.
529 /// @return true if reading was successfull (all single parts were delimited
531 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
544 } while (ifs && isSpace(ch));
549 // check for field type
550 if (isDigitASCII(ch)) {
552 // read integer value
556 } while (ifs && isDigitASCII(ch));
561 } else if (ch == '"' || ch == '{') {
563 char_type delim = ch == '"' ? '"': '}';
568 } while (ifs && isSpace(ch));
573 // We now have the first non-whitespace character
574 // We'll collapse adjacent whitespace.
575 bool lastWasWhiteSpace = false;
577 // inside this delimited text braces must match.
578 // Thus we can have a closing delimiter only
579 // when nestLevel == 0
582 while (ifs && (nestLevel > 0 || ch != delim)) {
584 lastWasWhiteSpace = true;
588 // We output the space only after we stop getting
589 // whitespace so as not to output any whitespace
590 // at the end of the value.
591 if (lastWasWhiteSpace) {
592 lastWasWhiteSpace = false;
598 // update nesting level
617 // FIXME Why is this here?
625 // reading a string name
628 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
629 strName += lowercase(ch);
636 // replace the string with its assigned value or
637 // discard it if it's not assigned
638 if (strName.length()) {
639 VarMap::const_iterator pos = strings.find(strName);
640 if (pos != strings.end()) {
647 while (ifs && isSpace(ch)) {
654 // continue reading next value on concatenate with '#'
664 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
670 void InsetBibtex::parseBibTeXFiles() const
672 // This bibtex parser is a first step to parse bibtex files
675 // - it reads the whole bibtex entry and does a syntax check
676 // (matching delimiters, missing commas,...
677 // - it recovers from errors starting with the next @-character
678 // - it reads @string definitions and replaces them in the
680 // - it accepts more characters in keys or value names than
683 // Officially bibtex does only support ASCII, but in practice
684 // you can use the encoding of the main document as long as
685 // some elements like keys and names are pure ASCII. Therefore
686 // we convert the file from the buffer encoding.
687 // We don't restrict keys to ASCII in LyX, since our own
688 // InsetBibitem can generate non-ASCII keys, and nonstandard
689 // 8bit clean bibtex forks exist.
693 support::FileNameList const files = getBibFiles();
694 support::FileNameList::const_iterator it = files.begin();
695 support::FileNameList::const_iterator en = files.end();
696 for (; it != en; ++ it) {
697 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
698 ios_base::in, buffer().params().encoding().iconvName());
714 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
715 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
720 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
724 if (entryType == from_ascii("comment")) {
725 ifs.ignore(numeric_limits<int>::max(), '\n');
731 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
735 if ((ch != '(') && (ch != '{')) {
736 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
742 if (entryType == from_ascii("string")) {
744 // read string and add it to the strings map
745 // (or replace it's old value)
749 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
750 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
755 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
759 // next char must be an equal sign
761 if (!ifs || ch != '=') {
762 lyxerr << "BibTeX Parser: No `=' after string name: " <<
763 name << "." << std::endl;
767 if (!readValue(value, ifs, strings)) {
768 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
769 name << "." << std::endl;
773 strings[name] = value;
775 } else if (entryType == from_ascii("preamble")) {
777 // preamble definitions are discarded.
778 // can they be of any use in lyx?
781 if (!readValue(value, ifs, strings)) {
782 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
788 // Citation entry. Try to read the key.
791 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
792 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
793 entryType << "." << std::endl;
798 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
802 /////////////////////////////////////////////
803 // now we have a key, so we will add an entry
804 // (even if it's empty, as bibtex does)
806 // we now read the field = value pairs.
807 // all items must be separated by a comma. If
808 // it is missing the scanning of this entry is
809 // stopped and the next is searched.
813 BibTeXInfo keyvalmap(key, entryType);
815 bool readNext = removeWSAndComma(ifs);
817 while (ifs && readNext) {
820 if (!readTypeOrKey(name, ifs, from_ascii("="),
821 from_ascii("{}(),"), makeLowerCase) || !ifs)
824 // next char must be an equal sign
825 // FIXME Whitespace??
828 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
832 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
833 name << ", for key: " << key << "." << std::endl;
839 if (!readValue(value, ifs, strings)) {
840 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
841 name << ", for key: " << key << "." << std::endl;
845 keyvalmap[name] = value;
846 data += "\n\n" + value;
847 keylist.addFieldName(name);
848 readNext = removeWSAndComma(ifs);
852 keylist.addEntryType(entryType);
853 keyvalmap.setAllData(data);
854 keylist[key] = keyvalmap;
855 } //< else (citation entry)
857 } //< for loop over files
859 buffer().addBiblioInfo(keylist);
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::ESCAPE_AND
981 << bibinfo.getInfo(entry.key(), buffer(), true)
982 << html::EndTag("span")
983 << html::EndTag("div")
986 xs << html::EndTag("div");
991 docstring InsetBibtex::contextMenuName() const
993 return from_ascii("context-bibtex");