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"
17 #include "BufferParams.h"
18 #include "DispatchResult.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "LaTeXFeatures.h"
24 #include "output_xhtml.h"
25 #include "OutputParams.h"
26 #include "TextClass.h"
28 #include "frontends/alert.h"
30 #include "support/convert.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/ExceptionMessage.h"
34 #include "support/filetools.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/os.h"
38 #include "support/Path.h"
39 #include "support/textutils.h"
44 using namespace lyx::support;
48 namespace Alert = frontend::Alert;
49 namespace os = support::os;
52 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
53 : InsetCommand(buf, p, "bibtex")
55 buffer_->invalidateBibinfoCache();
59 InsetBibtex::~InsetBibtex()
62 buffer_->invalidateBibinfoCache();
66 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
68 static ParamInfo param_info_;
69 if (param_info_.empty()) {
70 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
71 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
72 param_info_.add("options", ParamInfo::LYX_INTERNAL);
78 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
80 switch (cmd.action()) {
86 case LFUN_INSET_MODIFY: {
87 InsetCommandParams p(BIBTEX_CODE);
89 if (!InsetCommand::string2params("bibtex",
90 to_utf8(cmd.argument()), p)) {
94 } catch (ExceptionMessage const & message) {
95 if (message.type_ == WarningException) {
96 Alert::warning(message.title_, message.details_);
104 buffer().updateBibfilesCache();
109 InsetCommand::doDispatch(cur, cmd);
115 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
116 FuncStatus & flag) const
118 switch (cmd.action()) {
119 case LFUN_INSET_EDIT:
120 flag.setEnabled(true);
124 return InsetCommand::getStatus(cur, cmd, flag);
129 void InsetBibtex::editDatabases() const
131 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
133 if (bibfilelist.empty())
136 int nr_databases = bibfilelist.size();
137 if (nr_databases > 1) {
138 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
139 "If you proceed, all of them will be opened."),
140 convert<docstring>(nr_databases));
141 int const ret = Alert::prompt(_("Open Databases?"),
142 message, 0, 1, _("&Cancel"), _("&Proceed"));
148 vector<docstring>::const_iterator it = bibfilelist.begin();
149 vector<docstring>::const_iterator en = bibfilelist.end();
150 for (; it != en; ++it) {
151 FileName bibfile = getBibTeXPath(*it, buffer());
152 formats.edit(buffer(), bibfile,
153 formats.getFormatFromFile(bibfile));
158 docstring InsetBibtex::screenLabel() const
160 return _("BibTeX Generated Bibliography");
164 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
166 docstring item = from_ascii("* ");
167 docstring tip = _("Databases:") + "\n";
168 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
170 if (bibfilelist.empty()) {
174 vector<docstring>::const_iterator it = bibfilelist.begin();
175 vector<docstring>::const_iterator en = bibfilelist.end();
176 for (; it != en; ++it) {
184 docstring style = getParam("options"); // maybe empty! and with bibtotoc
185 docstring bibtotoc = from_ascii("bibtotoc");
186 if (prefixIs(style, bibtotoc)) {
188 if (contains(style, char_type(',')))
189 style = split(style, bibtotoc, char_type(','));
192 tip += _("Style File:") +"\n";
199 tip += "\n" + _("Lists:") + " ";
200 docstring btprint = getParam("btprint");
201 if (btprint == "btPrintAll")
202 tip += _("all references");
203 else if (btprint == "btPrintNotCited")
204 tip += _("all uncited references");
206 tip += _("all cited references");
210 tip += _("included in TOC");
217 static string normalizeName(Buffer const & buffer,
218 OutputParams const & runparams, string const & name, string const & ext)
220 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
221 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
227 return to_utf8(makeRelPath(from_utf8(fname),
228 from_utf8(buffer.masterBuffer()->filePath())));
232 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
234 // the sequence of the commands:
235 // 1. \bibliographystyle{style}
236 // 2. \addcontentsline{...} - if option bibtotoc set
237 // 3. \bibliography{database}
238 // and with bibtopic:
239 // 1. \bibliographystyle{style}
240 // 2. \begin{btSect}{database}
241 // 3. \btPrint{Cited|NotCited|All}
245 // If we are processing the LaTeX file in a temp directory then
246 // copy the .bib databases to this temp directory, mangling their
247 // names in the process. Store this mangled name in the list of
249 // (We need to do all this because BibTeX *really*, *really*
250 // can't handle "files with spaces" and Windows users tend to
251 // use such filenames.)
252 // Otherwise, store the (maybe absolute) path to the original,
253 // unmangled database name.
254 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
255 vector<docstring>::const_iterator it = bibfilelist.begin();
256 vector<docstring>::const_iterator en = bibfilelist.end();
257 odocstringstream dbs;
260 for (; it != en; ++it) {
261 string utf8input = to_utf8(*it);
263 normalizeName(buffer(), runparams, utf8input, ".bib");
264 FileName const try_in_file =
265 makeAbsPath(database + ".bib", buffer().filePath());
266 bool const not_from_texmf = try_in_file.isReadableFile();
268 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
270 // mangledFileName() needs the extension
271 DocFileName const in_file = DocFileName(try_in_file);
272 database = removeExtension(in_file.mangledFileName());
273 FileName const out_file = makeAbsPath(database + ".bib",
274 buffer().masterBuffer()->temppath());
276 bool const success = in_file.copyTo(out_file);
278 lyxerr << "Failed to copy '" << in_file
279 << "' to '" << out_file << "'"
282 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
283 !isValidLaTeXFileName(database)) {
284 frontend::Alert::warning(_("Invalid filename"),
285 _("The following filename is likely to cause trouble "
286 "when running the exported file through LaTeX: ") +
287 from_utf8(database));
295 dbs << from_utf8(latex_path(database));
297 docstring const db_out = dbs.str();
299 // Post this warning only once.
300 static bool warned_about_spaces = false;
301 if (!warned_about_spaces &&
302 runparams.nice && db_out.find(' ') != docstring::npos) {
303 warned_about_spaces = true;
304 Alert::warning(_("Export Warning!"),
305 _("There are spaces in the paths to your BibTeX databases.\n"
306 "BibTeX will be unable to find them."));
309 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
311 if (prefixIs(style, "bibtotoc")) {
312 bibtotoc = "bibtotoc";
313 if (contains(style, ','))
314 style = split(style, bibtotoc, ',');
320 if (!style.empty()) {
321 string base = normalizeName(buffer(), runparams, style, ".bst");
322 FileName const try_in_file =
323 makeAbsPath(base + ".bst", buffer().filePath());
324 bool const not_from_texmf = try_in_file.isReadableFile();
325 // If this style does not come from texmf and we are not
326 // exporting to .tex copy it to the tmp directory.
327 // This prevents problems with spaces and 8bit charcaters
329 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
331 // use new style name
332 DocFileName const in_file = DocFileName(try_in_file);
333 base = removeExtension(in_file.mangledFileName());
334 FileName const out_file = makeAbsPath(base + ".bst",
335 buffer().masterBuffer()->temppath());
336 bool const success = in_file.copyTo(out_file);
338 lyxerr << "Failed to copy '" << in_file
339 << "' to '" << out_file << "'"
344 os << "\\bibliographystyle{"
345 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
350 // Post this warning only once.
351 static bool warned_about_bst_spaces = false;
352 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
353 warned_about_bst_spaces = true;
354 Alert::warning(_("Export Warning!"),
355 _("There are spaces in the path to your BibTeX style file.\n"
356 "BibTeX will be unable to find it."));
359 if (!db_out.empty() && buffer().params().use_bibtopic) {
360 os << "\\begin{btSect}{" << db_out << "}\n";
361 docstring btprint = getParam("btprint");
364 btprint = from_ascii("btPrintCited");
365 os << "\\" << btprint << "\n"
366 << "\\end{btSect}\n";
371 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
372 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
373 if (buffer().params().sides == OneSide) {
378 os << "\\cleardoublepage";
380 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
381 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
382 os << "\\addcontentsline{toc}{section}{\\refname}";
385 if (!db_out.empty() && !buffer().params().use_bibtopic) {
386 docstring btprint = getParam("btprint");
387 if (btprint == "btPrintAll") {
388 os << "\\nocite{*}\n";
391 os << "\\bibliography{" << db_out << "}\n";
399 support::FileNameList InsetBibtex::getBibFiles() const
401 FileName path(buffer().filePath());
402 support::PathChanger p(path);
404 support::FileNameList vec;
406 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
407 vector<docstring>::const_iterator it = bibfilelist.begin();
408 vector<docstring>::const_iterator en = bibfilelist.end();
409 for (; it != en; ++it) {
410 FileName const file = getBibTeXPath(*it, buffer());
415 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
424 // methods for parsing bibtex files
426 typedef map<docstring, docstring> VarMap;
428 /// remove whitespace characters, optionally a single comma,
429 /// and further whitespace characters from the stream.
430 /// @return true if a comma was found, false otherwise
432 bool removeWSAndComma(ifdocstream & ifs) {
441 } while (ifs && isSpace(ch));
454 } while (ifs && isSpace(ch));
469 /// remove whitespace characters, read characer sequence
470 /// not containing whitespace characters or characters in
471 /// delimChars, and remove further whitespace characters.
473 /// @return true if a string of length > 0 could be read.
475 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
476 docstring const & delimChars, docstring const &illegalChars,
489 } while (ifs && isSpace(ch));
495 bool legalChar = true;
496 while (ifs && !isSpace(ch) &&
497 delimChars.find(ch) == docstring::npos &&
498 (legalChar = (illegalChars.find(ch) == docstring::npos))
501 if (chCase == makeLowerCase)
502 val += lowercase(ch);
514 while (ifs && isSpace(ch)) {
522 return val.length() > 0;
525 /// read subsequent bibtex values that are delimited with a #-character.
526 /// Concatenate all parts and replace names with the associated string in
527 /// the variable strings.
528 /// @return true if reading was successfull (all single parts were delimited
530 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
543 } while (ifs && isSpace(ch));
548 // check for field type
551 // read integer value
555 } while (ifs && isDigit(ch));
560 } else if (ch == '"' || ch == '{') {
562 char_type delim = ch == '"' ? '"': '}';
567 } while (ifs && isSpace(ch));
572 // We now have the first non-whitespace character
573 // We'll collapse adjacent whitespace.
574 bool lastWasWhiteSpace = false;
576 // inside this delimited text braces must match.
577 // Thus we can have a closing delimiter only
578 // when nestLevel == 0
581 while (ifs && (nestLevel > 0 || ch != delim)) {
583 lastWasWhiteSpace = true;
587 // We output the space only after we stop getting
588 // whitespace so as not to output any whitespace
589 // at the end of the value.
590 if (lastWasWhiteSpace) {
591 lastWasWhiteSpace = false;
597 // update nesting level
604 if (nestLevel < 0) return false;
621 // reading a string name
624 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
625 strName += lowercase(ch);
632 // replace the string with its assigned value or
633 // discard it if it's not assigned
634 if (strName.length()) {
635 VarMap::const_iterator pos = strings.find(strName);
636 if (pos != strings.end()) {
643 while (ifs && isSpace(ch)) {
650 // continue reading next value on concatenate with '#'
660 // This method returns a comma separated list of Bibtex entries
661 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
662 InsetIterator const & /*di*/) const
664 // This bibtex parser is a first step to parse bibtex files
667 // - it reads the whole bibtex entry and does a syntax check
668 // (matching delimiters, missing commas,...
669 // - it recovers from errors starting with the next @-character
670 // - it reads @string definitions and replaces them in the
672 // - it accepts more characters in keys or value names than
675 // Officially bibtex does only support ASCII, but in practice
676 // you can use the encoding of the main document as long as
677 // some elements like keys and names are pure ASCII. Therefore
678 // we convert the file from the buffer encoding.
679 // We don't restrict keys to ASCII in LyX, since our own
680 // InsetBibitem can generate non-ASCII keys, and nonstandard
681 // 8bit clean bibtex forks exist.
682 support::FileNameList const files = getBibFiles();
683 support::FileNameList::const_iterator it = files.begin();
684 support::FileNameList::const_iterator en = files.end();
685 for (; it != en; ++ it) {
686 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
687 ios_base::in, buffer().params().encoding().iconvName());
703 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
704 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
709 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
713 if (entryType == from_ascii("comment")) {
714 ifs.ignore(numeric_limits<int>::max(), '\n');
720 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
724 if ((ch != '(') && (ch != '{')) {
725 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
731 if (entryType == from_ascii("string")) {
733 // read string and add it to the strings map
734 // (or replace it's old value)
738 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
739 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
744 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
748 // next char must be an equal sign
750 if (!ifs || ch != '=') {
751 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
752 name << "." << std::endl;
756 if (!readValue(value, ifs, strings)) {
757 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
758 name << "." << std::endl;
762 strings[name] = value;
764 } else if (entryType == from_ascii("preamble")) {
766 // preamble definitions are discarded.
767 // can they be of any use in lyx?
770 if (!readValue(value, ifs, strings)) {
771 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
777 // Citation entry. Try to read the key.
780 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
781 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
782 entryType << "." << std::endl;
787 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
791 /////////////////////////////////////////////
792 // now we have a key, so we will add an entry
793 // (even if it's empty, as bibtex does)
795 // we now read the field = value pairs.
796 // all items must be separated by a comma. If
797 // it is missing the scanning of this entry is
798 // stopped and the next is searched.
802 docstring commaNewline;
804 BibTeXInfo keyvalmap(key, entryType);
806 bool readNext = removeWSAndComma(ifs);
808 while (ifs && readNext) {
811 if (!readTypeOrKey(name, ifs, from_ascii("="),
812 from_ascii("{}(),"), makeLowerCase) || !ifs)
815 // next char must be an equal sign
818 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
822 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
823 name << ", for key: " << key << "." << std::endl;
829 if (!readValue(value, ifs, strings)) {
830 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
831 name << ", for key: " << key << "." << std::endl;
835 keyvalmap[name] = value;
836 data += "\n\n" + value;
837 keylist.addFieldName(name);
838 readNext = removeWSAndComma(ifs);
842 keylist.addEntryType(entryType);
843 keyvalmap.setAllData(data);
844 keylist[key] = keyvalmap;
845 } //< else (citation entry)
847 } //< for loop over files
851 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
853 string texfile = changeExtension(to_utf8(filename), "bib");
854 // note that, if the filename can be found directly from the path,
855 // findtexfile will just return a FileName object for that path.
856 FileName file(findtexfile(texfile, "bib"));
858 file = FileName(makeAbsPath(texfile, buf.filePath()));
863 bool InsetBibtex::addDatabase(docstring const & db)
865 docstring bibfiles = getParam("bibfiles");
866 if (tokenPos(bibfiles, ',', db) != -1)
868 if (!bibfiles.empty())
870 setParam("bibfiles", bibfiles + db);
875 bool InsetBibtex::delDatabase(docstring const & db)
877 docstring bibfiles = getParam("bibfiles");
878 if (contains(bibfiles, db)) {
879 int const n = tokenPos(bibfiles, ',', db);
882 // this is not the first database
883 docstring tmp = ',' + bd;
884 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
886 // this is the first (or only) database
887 setParam("bibfiles", split(bibfiles, bd, ','));
895 void InsetBibtex::validate(LaTeXFeatures & features) const
897 if (features.bufferParams().use_bibtopic)
898 features.require("bibtopic");
900 // It'd be better to be able to get this from an InsetLayout, but at present
901 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
902 if (features.runparams().flavor == OutputParams::HTML)
903 features.addPreambleSnippet("<style type=\"text/css\">\n"
904 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
905 "span.bibtexlabel:before{ content: \"[\"; }\n"
906 "span.bibtexlabel:after{ content: \"] \"; }\n"
912 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
913 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
914 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
916 BiblioInfo const & bibinfo = buffer().masterBibInfo();
917 vector<docstring> const & cites = bibinfo.citedEntries();
918 CiteEngine const engine = buffer().params().citeEngine();
920 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
922 xs << html::StartTag("h2", "class='bibtex'")
924 << html::EndTag("h2")
925 << html::StartTag("div", "class='bibtex'");
927 // Now we loop over the entries
928 vector<docstring>::const_iterator vit = cites.begin();
929 vector<docstring>::const_iterator const ven = cites.end();
930 for (; vit != ven; ++vit) {
931 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
932 if (biit == bibinfo.end())
934 BibTeXInfo const & entry = biit->second;
935 xs << html::StartTag("div", "class='bibtexentry'");
937 // The same name/id problem we have elsewhere.
938 string const attr = "id='" + to_utf8(entry.key()) + "'";
939 xs << html::CompTag("a", attr);
942 citekey = entry.citeNumber();
944 docstring const auth = entry.getAbbreviatedAuthor();
945 // we do it this way so as to access the xref, if necessary
946 // note that this also gives us the modifier
947 docstring const year = bibinfo.getYear(*vit, true);
948 if (!auth.empty() && !year.empty())
949 citekey = auth + ' ' + year;
951 if (citekey.empty()) {
952 citekey = entry.label();
954 citekey = entry.key();
956 xs << html::StartTag("span", "class='bibtexlabel'")
958 << html::EndTag("span");
959 // FIXME Right now, we are calling BibInfo::getInfo on the key,
960 // which will give us all the cross-referenced info. But for every
961 // entry, so there's a lot of repitition. This should be fixed.
962 xs << html::StartTag("span", "class='bibtexinfo'")
963 << bibinfo.getInfo(entry.key(), buffer(), true)
964 << html::EndTag("span")
965 << html::EndTag("div");
968 xs << html::EndTag("div");
973 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
975 return from_ascii("context-bibtex");