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"
19 #include "DispatchResult.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
25 #include "LaTeXFeatures.h"
26 #include "output_xhtml.h"
27 #include "OutputParams.h"
28 #include "PDFOptions.h"
29 #include "TextClass.h"
31 #include "frontends/alert.h"
33 #include "support/convert.h"
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/ExceptionMessage.h"
37 #include "support/FileNameList.h"
38 #include "support/filetools.h"
39 #include "support/gettext.h"
40 #include "support/lstrings.h"
41 #include "support/os.h"
42 #include "support/Path.h"
43 #include "support/textutils.h"
48 using namespace lyx::support;
52 namespace Alert = frontend::Alert;
53 namespace os = support::os;
56 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
57 : InsetCommand(buf, p)
59 buffer().invalidateBibinfoCache();
63 InsetBibtex::~InsetBibtex()
66 buffer().invalidateBibfileCache();
70 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
72 static ParamInfo param_info_;
73 if (param_info_.empty()) {
74 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
75 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
76 param_info_.add("options", ParamInfo::LYX_INTERNAL);
82 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
84 switch (cmd.action()) {
90 case LFUN_INSET_MODIFY: {
91 InsetCommandParams p(BIBTEX_CODE);
93 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
97 } catch (ExceptionMessage const & message) {
98 if (message.type_ == WarningException) {
99 Alert::warning(message.title_, message.details_);
100 cur.noScreenUpdate();
107 buffer().invalidateBibfileCache();
108 cur.forceBufferUpdate();
113 InsetCommand::doDispatch(cur, cmd);
119 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
120 FuncStatus & flag) const
122 switch (cmd.action()) {
123 case LFUN_INSET_EDIT:
124 flag.setEnabled(true);
128 return InsetCommand::getStatus(cur, cmd, flag);
133 void InsetBibtex::editDatabases() const
135 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
137 if (bibfilelist.empty())
140 int nr_databases = bibfilelist.size();
141 if (nr_databases > 1) {
142 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
143 "If you proceed, all of them will be opened."),
144 convert<docstring>(nr_databases));
145 int const ret = Alert::prompt(_("Open Databases?"),
146 message, 0, 1, _("&Cancel"), _("&Proceed"));
152 vector<docstring>::const_iterator it = bibfilelist.begin();
153 vector<docstring>::const_iterator en = bibfilelist.end();
154 for (; it != en; ++it) {
155 FileName const bibfile = getBibTeXPath(*it, buffer());
156 formats.edit(buffer(), bibfile,
157 formats.getFormatFromFile(bibfile));
162 docstring InsetBibtex::screenLabel() const
164 return _("BibTeX Generated Bibliography");
168 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
170 docstring item = from_ascii("* ");
171 docstring tip = _("Databases:") + "\n";
172 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
174 if (bibfilelist.empty()) {
178 vector<docstring>::const_iterator it = bibfilelist.begin();
179 vector<docstring>::const_iterator en = bibfilelist.end();
180 for (; it != en; ++it) {
188 docstring style = getParam("options"); // maybe empty! and with bibtotoc
189 docstring bibtotoc = from_ascii("bibtotoc");
190 if (prefixIs(style, bibtotoc)) {
192 if (contains(style, char_type(',')))
193 style = split(style, bibtotoc, char_type(','));
196 tip += _("Style File:") +"\n";
203 tip += "\n" + _("Lists:") + " ";
204 docstring btprint = getParam("btprint");
205 if (btprint == "btPrintAll")
206 tip += _("all references");
207 else if (btprint == "btPrintNotCited")
208 tip += _("all uncited references");
210 tip += _("all cited references");
214 tip += _("included in TOC");
221 static string normalizeName(Buffer const & buffer,
222 OutputParams const & runparams, string const & name, string const & ext)
224 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
225 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
231 return to_utf8(makeRelPath(from_utf8(fname),
232 from_utf8(buffer.masterBuffer()->filePath())));
236 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
238 // the sequence of the commands:
239 // 1. \bibliographystyle{style}
240 // 2. \addcontentsline{...} - if option bibtotoc set
241 // 3. \bibliography{database}
242 // and with bibtopic:
243 // 1. \bibliographystyle{style}
244 // 2. \begin{btSect}{database}
245 // 3. \btPrint{Cited|NotCited|All}
249 // If we are processing the LaTeX file in a temp directory then
250 // copy the .bib databases to this temp directory, mangling their
251 // names in the process. Store this mangled name in the list of
253 // (We need to do all this because BibTeX *really*, *really*
254 // can't handle "files with spaces" and Windows users tend to
255 // use such filenames.)
256 // Otherwise, store the (maybe absolute) path to the original,
257 // unmangled database name.
258 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
259 vector<docstring>::const_iterator it = bibfilelist.begin();
260 vector<docstring>::const_iterator en = bibfilelist.end();
261 odocstringstream dbs;
264 for (; it != en; ++it) {
265 string utf8input = to_utf8(*it);
267 normalizeName(buffer(), runparams, utf8input, ".bib");
268 FileName const try_in_file =
269 makeAbsPath(database + ".bib", buffer().filePath());
270 bool const not_from_texmf = try_in_file.isReadableFile();
272 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
274 // mangledFileName() needs the extension
275 DocFileName const in_file = DocFileName(try_in_file);
276 database = removeExtension(in_file.mangledFileName());
277 FileName const out_file = makeAbsPath(database + ".bib",
278 buffer().masterBuffer()->temppath());
280 bool const success = in_file.copyTo(out_file);
282 lyxerr << "Failed to copy '" << in_file
283 << "' to '" << out_file << "'"
286 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
287 if (!isValidLaTeXFileName(database)) {
288 frontend::Alert::warning(_("Invalid filename"),
289 _("The following filename will cause troubles "
290 "when running the exported file through LaTeX: ") +
291 from_utf8(database));
293 if (!isValidDVIFileName(database)) {
294 frontend::Alert::warning(_("Problematic filename for DVI"),
295 _("The following filename can cause troubles "
296 "when running the exported file through LaTeX "
297 "and opening the resulting DVI: ") +
298 from_utf8(database), true);
307 dbs << from_utf8(latex_path(database));
309 docstring const db_out = dbs.str();
311 // Post this warning only once.
312 static bool warned_about_spaces = false;
313 if (!warned_about_spaces &&
314 runparams.nice && db_out.find(' ') != docstring::npos) {
315 warned_about_spaces = true;
316 Alert::warning(_("Export Warning!"),
317 _("There are spaces in the paths to your BibTeX databases.\n"
318 "BibTeX will be unable to find them."));
321 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
323 if (prefixIs(style, "bibtotoc")) {
324 bibtotoc = "bibtotoc";
325 if (contains(style, ','))
326 style = split(style, bibtotoc, ',');
332 if (!style.empty()) {
333 string base = normalizeName(buffer(), runparams, style, ".bst");
334 FileName const try_in_file =
335 makeAbsPath(base + ".bst", buffer().filePath());
336 bool const not_from_texmf = try_in_file.isReadableFile();
337 // If this style does not come from texmf and we are not
338 // exporting to .tex copy it to the tmp directory.
339 // This prevents problems with spaces and 8bit charcaters
341 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
343 // use new style name
344 DocFileName const in_file = DocFileName(try_in_file);
345 base = removeExtension(in_file.mangledFileName());
346 FileName const out_file = makeAbsPath(base + ".bst",
347 buffer().masterBuffer()->temppath());
348 bool const success = in_file.copyTo(out_file);
350 lyxerr << "Failed to copy '" << in_file
351 << "' to '" << out_file << "'"
356 os << "\\bibliographystyle{"
357 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
362 // Post this warning only once.
363 static bool warned_about_bst_spaces = false;
364 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
365 warned_about_bst_spaces = true;
366 Alert::warning(_("Export Warning!"),
367 _("There are spaces in the path to your BibTeX style file.\n"
368 "BibTeX will be unable to find it."));
371 if (!db_out.empty() && buffer().params().use_bibtopic) {
372 os << "\\begin{btSect}{" << db_out << "}\n";
373 docstring btprint = getParam("btprint");
376 btprint = from_ascii("btPrintCited");
377 os << "\\" << btprint << "\n"
378 << "\\end{btSect}\n";
383 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
384 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
385 if (buffer().params().pdfoptions().use_hyperref)
386 os << "\\phantomsection";
387 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
388 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
389 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
390 os << "\\addcontentsline{toc}{section}{\\refname}";
393 if (!db_out.empty() && !buffer().params().use_bibtopic) {
394 docstring btprint = getParam("btprint");
395 if (btprint == "btPrintAll") {
396 os << "\\nocite{*}\n";
399 os << "\\bibliography{" << db_out << "}\n";
407 support::FileNameList InsetBibtex::getBibFiles() const
409 FileName path(buffer().filePath());
410 support::PathChanger p(path);
412 support::FileNameList vec;
414 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
415 vector<docstring>::const_iterator it = bibfilelist.begin();
416 vector<docstring>::const_iterator en = bibfilelist.end();
417 for (; it != en; ++it) {
418 FileName const file = getBibTeXPath(*it, buffer());
423 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
432 // methods for parsing bibtex files
434 typedef map<docstring, docstring> VarMap;
436 /// remove whitespace characters, optionally a single comma,
437 /// and further whitespace characters from the stream.
438 /// @return true if a comma was found, false otherwise
440 bool removeWSAndComma(ifdocstream & ifs) {
449 } while (ifs && isSpace(ch));
462 } while (ifs && isSpace(ch));
477 /// remove whitespace characters, read characer sequence
478 /// not containing whitespace characters or characters in
479 /// delimChars, and remove further whitespace characters.
481 /// @return true if a string of length > 0 could be read.
483 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
484 docstring const & delimChars, docstring const & illegalChars,
497 } while (ifs && isSpace(ch));
503 bool legalChar = true;
504 while (ifs && !isSpace(ch) &&
505 delimChars.find(ch) == docstring::npos &&
506 (legalChar = (illegalChars.find(ch) == docstring::npos))
509 if (chCase == makeLowerCase)
510 val += lowercase(ch);
522 while (ifs && isSpace(ch)) {
530 return val.length() > 0;
533 /// read subsequent bibtex values that are delimited with a #-character.
534 /// Concatenate all parts and replace names with the associated string in
535 /// the variable strings.
536 /// @return true if reading was successfull (all single parts were delimited
538 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
551 } while (ifs && isSpace(ch));
556 // check for field type
559 // read integer value
563 } while (ifs && isDigit(ch));
568 } else if (ch == '"' || ch == '{') {
570 char_type delim = ch == '"' ? '"': '}';
575 } while (ifs && isSpace(ch));
580 // We now have the first non-whitespace character
581 // We'll collapse adjacent whitespace.
582 bool lastWasWhiteSpace = false;
584 // inside this delimited text braces must match.
585 // Thus we can have a closing delimiter only
586 // when nestLevel == 0
589 while (ifs && (nestLevel > 0 || ch != delim)) {
591 lastWasWhiteSpace = true;
595 // We output the space only after we stop getting
596 // whitespace so as not to output any whitespace
597 // at the end of the value.
598 if (lastWasWhiteSpace) {
599 lastWasWhiteSpace = false;
605 // update nesting level
624 // FIXME Why is this here?
632 // reading a string name
635 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
636 strName += lowercase(ch);
643 // replace the string with its assigned value or
644 // discard it if it's not assigned
645 if (strName.length()) {
646 VarMap::const_iterator pos = strings.find(strName);
647 if (pos != strings.end()) {
654 while (ifs && isSpace(ch)) {
661 // continue reading next value on concatenate with '#'
671 // This method returns a comma separated list of Bibtex entries
672 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
673 InsetIterator const & /*di*/) const
675 // This bibtex parser is a first step to parse bibtex files
678 // - it reads the whole bibtex entry and does a syntax check
679 // (matching delimiters, missing commas,...
680 // - it recovers from errors starting with the next @-character
681 // - it reads @string definitions and replaces them in the
683 // - it accepts more characters in keys or value names than
686 // Officially bibtex does only support ASCII, but in practice
687 // you can use the encoding of the main document as long as
688 // some elements like keys and names are pure ASCII. Therefore
689 // we convert the file from the buffer encoding.
690 // We don't restrict keys to ASCII in LyX, since our own
691 // InsetBibitem can generate non-ASCII keys, and nonstandard
692 // 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
861 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
863 string texfile = changeExtension(to_utf8(filename), "bib");
864 // note that, if the filename can be found directly from the path,
865 // findtexfile will just return a FileName object for that path.
866 FileName file(findtexfile(texfile, "bib"));
868 file = FileName(makeAbsPath(texfile, buf.filePath()));
873 bool InsetBibtex::addDatabase(docstring const & db)
875 docstring bibfiles = getParam("bibfiles");
876 if (tokenPos(bibfiles, ',', db) != -1)
878 if (!bibfiles.empty())
880 setParam("bibfiles", bibfiles + db);
885 bool InsetBibtex::delDatabase(docstring const & db)
887 docstring bibfiles = getParam("bibfiles");
888 if (contains(bibfiles, db)) {
889 int const n = tokenPos(bibfiles, ',', db);
892 // this is not the first database
893 docstring tmp = ',' + bd;
894 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
896 // this is the first (or only) database
897 setParam("bibfiles", split(bibfiles, bd, ','));
905 void InsetBibtex::validate(LaTeXFeatures & features) const
907 if (features.bufferParams().use_bibtopic)
908 features.require("bibtopic");
910 // It'd be better to be able to get this from an InsetLayout, but at present
911 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
912 if (features.runparams().flavor == OutputParams::HTML)
913 features.addPreambleSnippet("<style type=\"text/css\">\n"
914 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
915 "span.bibtexlabel:before{ content: \"[\"; }\n"
916 "span.bibtexlabel:after{ content: \"] \"; }\n"
922 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
923 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
924 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
926 BiblioInfo const & bibinfo = buffer().masterBibInfo();
927 vector<docstring> const & cites = bibinfo.citedEntries();
928 CiteEngine const engine = buffer().params().citeEngine();
930 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
932 docstring reflabel = from_ascii("References");
933 Language const * l = buffer().params().language;
935 reflabel = translateIfPossible(reflabel, l->code());
937 xs << html::StartTag("h2", "class='bibtex'")
939 << html::EndTag("h2")
940 << html::StartTag("div", "class='bibtex'");
942 // Now we loop over the entries
943 vector<docstring>::const_iterator vit = cites.begin();
944 vector<docstring>::const_iterator const ven = cites.end();
945 for (; vit != ven; ++vit) {
946 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
947 if (biit == bibinfo.end())
949 BibTeXInfo const & entry = biit->second;
950 xs << html::StartTag("div", "class='bibtexentry'");
952 // The same name/id problem we have elsewhere.
953 string const attr = "id='" + to_utf8(entry.key()) + "'";
954 xs << html::CompTag("a", attr);
957 citekey = entry.citeNumber();
959 docstring const auth = entry.getAbbreviatedAuthor();
960 // we do it this way so as to access the xref, if necessary
961 // note that this also gives us the modifier
962 docstring const year = bibinfo.getYear(*vit, true);
963 if (!auth.empty() && !year.empty())
964 citekey = auth + ' ' + year;
966 if (citekey.empty()) {
967 citekey = entry.label();
969 citekey = entry.key();
971 xs << html::StartTag("span", "class='bibtexlabel'")
973 << html::EndTag("span");
974 // FIXME Right now, we are calling BibInfo::getInfo on the key,
975 // which will give us all the cross-referenced info. But for every
976 // entry, so there's a lot of repitition. This should be fixed.
977 xs << html::StartTag("span", "class='bibtexinfo'")
978 << XHTMLStream::NextRaw()
979 << bibinfo.getInfo(entry.key(), buffer(), true)
980 << html::EndTag("span")
981 << html::EndTag("div");
984 xs << html::EndTag("div");
989 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
991 return from_ascii("context-bibtex");