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"
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/PathChanger.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().invalidateBibfileCache();
61 buffer().removeBiblioTempFiles();
65 InsetBibtex::~InsetBibtex()
67 if (isBufferLoaded()) {
68 buffer().invalidateBibfileCache();
69 buffer().removeBiblioTempFiles();
74 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
76 static ParamInfo param_info_;
77 if (param_info_.empty()) {
78 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
79 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
80 param_info_.add("options", ParamInfo::LYX_INTERNAL);
86 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
88 switch (cmd.action()) {
94 case LFUN_INSET_MODIFY: {
95 InsetCommandParams p(BIBTEX_CODE);
97 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
101 } catch (ExceptionMessage const & message) {
102 if (message.type_ == WarningException) {
103 Alert::warning(message.title_, message.details_);
104 cur.noScreenUpdate();
112 buffer().invalidateBibfileCache();
113 buffer().removeBiblioTempFiles();
114 cur.forceBufferUpdate();
119 InsetCommand::doDispatch(cur, cmd);
125 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
126 FuncStatus & flag) const
128 switch (cmd.action()) {
129 case LFUN_INSET_EDIT:
130 flag.setEnabled(true);
134 return InsetCommand::getStatus(cur, cmd, flag);
139 void InsetBibtex::editDatabases() const
141 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
143 if (bibfilelist.empty())
146 int nr_databases = bibfilelist.size();
147 if (nr_databases > 1) {
148 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
149 "If you proceed, all of them will be opened."),
150 convert<docstring>(nr_databases));
151 int const ret = Alert::prompt(_("Open Databases?"),
152 message, 0, 1, _("&Cancel"), _("&Proceed"));
158 vector<docstring>::const_iterator it = bibfilelist.begin();
159 vector<docstring>::const_iterator en = bibfilelist.end();
160 for (; it != en; ++it) {
161 FileName const bibfile = getBibTeXPath(*it, buffer());
162 formats.edit(buffer(), bibfile,
163 formats.getFormatFromFile(bibfile));
168 docstring InsetBibtex::screenLabel() const
170 return _("BibTeX Generated Bibliography");
174 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
176 docstring item = from_ascii("* ");
177 docstring tip = _("Databases:") + "\n";
178 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
180 if (bibfilelist.empty()) {
184 vector<docstring>::const_iterator it = bibfilelist.begin();
185 vector<docstring>::const_iterator en = bibfilelist.end();
186 for (; it != en; ++it) {
194 docstring style = getParam("options"); // maybe empty! and with bibtotoc
195 docstring bibtotoc = from_ascii("bibtotoc");
196 if (prefixIs(style, bibtotoc)) {
198 if (contains(style, char_type(',')))
199 style = split(style, bibtotoc, char_type(','));
202 tip += _("Style File:") +"\n";
209 tip += "\n" + _("Lists:") + " ";
210 docstring btprint = getParam("btprint");
211 if (btprint == "btPrintAll")
212 tip += _("all references");
213 else if (btprint == "btPrintNotCited")
214 tip += _("all uncited references");
216 tip += _("all cited references");
220 tip += _("included in TOC");
227 static string normalizeName(Buffer const & buffer,
228 OutputParams const & runparams, string const & name, string const & ext)
230 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
231 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
237 return to_utf8(makeRelPath(from_utf8(fname),
238 from_utf8(buffer.masterBuffer()->filePath())));
242 void InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
244 // the sequence of the commands:
245 // 1. \bibliographystyle{style}
246 // 2. \addcontentsline{...} - if option bibtotoc set
247 // 3. \bibliography{database}
248 // and with bibtopic:
249 // 1. \bibliographystyle{style}
250 // 2. \begin{btSect}{database}
251 // 3. \btPrint{Cited|NotCited|All}
255 // If we are processing the LaTeX file in a temp directory then
256 // copy the .bib databases to this temp directory, mangling their
257 // names in the process. Store this mangled name in the list of
259 // (We need to do all this because BibTeX *really*, *really*
260 // can't handle "files with spaces" and Windows users tend to
261 // use such filenames.)
262 // Otherwise, store the (maybe absolute) path to the original,
263 // unmangled database name.
264 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
265 vector<docstring>::const_iterator it = bibfilelist.begin();
266 vector<docstring>::const_iterator en = bibfilelist.end();
267 odocstringstream dbs;
270 // determine the export format
271 string const tex_format = flavor2format(runparams.flavor);
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());
288 bool const success = in_file.copyTo(out_file);
290 lyxerr << "Failed to copy '" << in_file
291 << "' to '" << out_file << "'"
294 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
295 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
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, ',');
338 if (style == "default")
339 style = buffer().params().biblio_style;
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")))
370 // Post this warning only once.
371 static bool warned_about_bst_spaces = false;
372 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
373 warned_about_bst_spaces = true;
374 Alert::warning(_("Export Warning!"),
375 _("There are spaces in the path to your BibTeX style file.\n"
376 "BibTeX will be unable to find it."));
379 if (!db_out.empty() && buffer().params().use_bibtopic) {
380 os << "\\begin{btSect}{" << db_out << "}\n";
381 docstring btprint = getParam("btprint");
384 btprint = from_ascii("btPrintCited");
385 os << "\\" << btprint << "\n"
386 << "\\end{btSect}\n";
390 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
391 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
392 if (buffer().params().pdfoptions().use_hyperref)
393 os << "\\phantomsection";
394 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
395 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
396 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
397 os << "\\addcontentsline{toc}{section}{\\refname}";
400 if (!db_out.empty() && !buffer().params().use_bibtopic) {
401 docstring btprint = getParam("btprint");
402 if (btprint == "btPrintAll") {
403 os << "\\nocite{*}\n";
405 os << "\\bibliography{" << db_out << "}\n";
410 support::FileNameList InsetBibtex::getBibFiles() const
412 FileName path(buffer().filePath());
413 support::PathChanger p(path);
415 support::FileNameList vec;
417 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
418 vector<docstring>::const_iterator it = bibfilelist.begin();
419 vector<docstring>::const_iterator en = bibfilelist.end();
420 for (; it != en; ++it) {
421 FileName const file = getBibTeXPath(*it, buffer());
426 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
435 // methods for parsing bibtex files
437 typedef map<docstring, docstring> VarMap;
439 /// remove whitespace characters, optionally a single comma,
440 /// and further whitespace characters from the stream.
441 /// @return true if a comma was found, false otherwise
443 bool removeWSAndComma(ifdocstream & ifs) {
452 } while (ifs && isSpace(ch));
465 } while (ifs && isSpace(ch));
480 /// remove whitespace characters, read characer sequence
481 /// not containing whitespace characters or characters in
482 /// delimChars, and remove further whitespace characters.
484 /// @return true if a string of length > 0 could be read.
486 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
487 docstring const & delimChars, docstring const & illegalChars,
500 } while (ifs && isSpace(ch));
506 bool legalChar = true;
507 while (ifs && !isSpace(ch) &&
508 delimChars.find(ch) == docstring::npos &&
509 (legalChar = (illegalChars.find(ch) == docstring::npos))
512 if (chCase == makeLowerCase)
513 val += lowercase(ch);
525 while (ifs && isSpace(ch)) {
533 return val.length() > 0;
536 /// read subsequent bibtex values that are delimited with a #-character.
537 /// Concatenate all parts and replace names with the associated string in
538 /// the variable strings.
539 /// @return true if reading was successfull (all single parts were delimited
541 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
554 } while (ifs && isSpace(ch));
559 // check for field type
560 if (isDigitASCII(ch)) {
562 // read integer value
566 } while (ifs && isDigitASCII(ch));
571 } else if (ch == '"' || ch == '{') {
573 char_type delim = ch == '"' ? '"': '}';
578 } while (ifs && isSpace(ch));
583 // We now have the first non-whitespace character
584 // We'll collapse adjacent whitespace.
585 bool lastWasWhiteSpace = false;
587 // inside this delimited text braces must match.
588 // Thus we can have a closing delimiter only
589 // when nestLevel == 0
592 while (ifs && (nestLevel > 0 || ch != delim)) {
594 lastWasWhiteSpace = true;
598 // We output the space only after we stop getting
599 // whitespace so as not to output any whitespace
600 // at the end of the value.
601 if (lastWasWhiteSpace) {
602 lastWasWhiteSpace = false;
608 // update nesting level
627 // FIXME Why is this here?
635 // reading a string name
638 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
639 strName += lowercase(ch);
646 // replace the string with its assigned value or
647 // discard it if it's not assigned
648 if (strName.length()) {
649 VarMap::const_iterator pos = strings.find(strName);
650 if (pos != strings.end()) {
657 while (ifs && isSpace(ch)) {
664 // continue reading next value on concatenate with '#'
674 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
680 void InsetBibtex::parseBibTeXFiles() const
682 // This bibtex parser is a first step to parse bibtex files
685 // - it reads the whole bibtex entry and does a syntax check
686 // (matching delimiters, missing commas,...
687 // - it recovers from errors starting with the next @-character
688 // - it reads @string definitions and replaces them in the
690 // - it accepts more characters in keys or value names than
693 // Officially bibtex does only support ASCII, but in practice
694 // you can use the encoding of the main document as long as
695 // some elements like keys and names are pure ASCII. Therefore
696 // we convert the file from the buffer encoding.
697 // We don't restrict keys to ASCII in LyX, since our own
698 // InsetBibitem can generate non-ASCII keys, and nonstandard
699 // 8bit clean bibtex forks exist.
703 support::FileNameList const files = getBibFiles();
704 support::FileNameList::const_iterator it = files.begin();
705 support::FileNameList::const_iterator en = files.end();
706 for (; it != en; ++ it) {
707 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
708 ios_base::in, buffer().params().encoding().iconvName());
724 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
725 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
730 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
734 if (entryType == from_ascii("comment")) {
735 ifs.ignore(numeric_limits<int>::max(), '\n');
741 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
745 if ((ch != '(') && (ch != '{')) {
746 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
752 if (entryType == from_ascii("string")) {
754 // read string and add it to the strings map
755 // (or replace it's old value)
759 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
760 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
765 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
769 // next char must be an equal sign
771 if (!ifs || ch != '=') {
772 lyxerr << "BibTeX Parser: No `=' after string name: " <<
773 name << "." << std::endl;
777 if (!readValue(value, ifs, strings)) {
778 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
779 name << "." << std::endl;
783 strings[name] = value;
785 } else if (entryType == from_ascii("preamble")) {
787 // preamble definitions are discarded.
788 // can they be of any use in lyx?
791 if (!readValue(value, ifs, strings)) {
792 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
798 // Citation entry. Try to read the key.
801 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
802 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
803 entryType << "." << std::endl;
808 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
812 /////////////////////////////////////////////
813 // now we have a key, so we will add an entry
814 // (even if it's empty, as bibtex does)
816 // we now read the field = value pairs.
817 // all items must be separated by a comma. If
818 // it is missing the scanning of this entry is
819 // stopped and the next is searched.
823 BibTeXInfo keyvalmap(key, entryType);
825 bool readNext = removeWSAndComma(ifs);
827 while (ifs && readNext) {
830 if (!readTypeOrKey(name, ifs, from_ascii("="),
831 from_ascii("{}(),"), makeLowerCase) || !ifs)
834 // next char must be an equal sign
835 // FIXME Whitespace??
838 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
842 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
843 name << ", for key: " << key << "." << std::endl;
849 if (!readValue(value, ifs, strings)) {
850 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
851 name << ", for key: " << key << "." << std::endl;
855 keyvalmap[name] = value;
856 data += "\n\n" + value;
857 keylist.addFieldName(name);
858 readNext = removeWSAndComma(ifs);
862 keylist.addEntryType(entryType);
863 keyvalmap.setAllData(data);
864 keylist[key] = keyvalmap;
865 } //< else (citation entry)
867 } //< for loop over files
869 buffer().addBiblioInfo(keylist);
873 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
875 string texfile = changeExtension(to_utf8(filename), "bib");
876 // note that, if the filename can be found directly from the path,
877 // findtexfile will just return a FileName object for that path.
878 FileName file(findtexfile(texfile, "bib"));
880 file = FileName(makeAbsPath(texfile, buf.filePath()));
885 bool InsetBibtex::addDatabase(docstring const & db)
887 docstring bibfiles = getParam("bibfiles");
888 if (tokenPos(bibfiles, ',', db) != -1)
890 if (!bibfiles.empty())
892 setParam("bibfiles", bibfiles + db);
897 bool InsetBibtex::delDatabase(docstring const & db)
899 docstring bibfiles = getParam("bibfiles");
900 if (contains(bibfiles, db)) {
901 int const n = tokenPos(bibfiles, ',', db);
904 // this is not the first database
905 docstring tmp = ',' + bd;
906 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
908 // this is the first (or only) database
909 setParam("bibfiles", split(bibfiles, bd, ','));
917 void InsetBibtex::validate(LaTeXFeatures & features) const
919 if (features.bufferParams().use_bibtopic)
920 features.require("bibtopic");
922 // It'd be better to be able to get this from an InsetLayout, but at present
923 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
924 if (features.runparams().flavor == OutputParams::HTML)
925 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
926 "span.bibtexlabel:before{ content: \"[\"; }\n"
927 "span.bibtexlabel:after{ content: \"] \"; }");
931 int InsetBibtex::plaintext(odocstringstream & os,
932 OutputParams const & op, size_t max_length) const
934 docstring const reflabel = buffer().B_("References");
936 if (op.for_tooltip || op.for_toc) {
938 return reflabel.size();
941 BiblioInfo bibinfo = buffer().masterBibInfo();
942 bibinfo.makeCitationLabels(buffer());
943 vector<docstring> const & cites = bibinfo.citedEntries();
945 size_t start_size = os.str().size();
947 refoutput += reflabel + "\n\n";
949 // Now we loop over the entries
950 vector<docstring>::const_iterator vit = cites.begin();
951 vector<docstring>::const_iterator const ven = cites.end();
952 for (; vit != ven; ++vit) {
953 if (start_size + refoutput.size() >= max_length)
955 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
956 if (biit == bibinfo.end())
958 BibTeXInfo const & entry = biit->second;
959 refoutput += "[" + entry.label() + "] ";
960 // FIXME Right now, we are calling BibInfo::getInfo on the key,
961 // which will give us all the cross-referenced info. But for every
962 // entry, so there's a lot of repitition. This should be fixed.
963 refoutput += bibinfo.getInfo(entry.key(), buffer(), false) + "\n\n";
966 return refoutput.size();
971 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
972 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
973 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
975 BiblioInfo const & bibinfo = buffer().masterBibInfo();
976 vector<docstring> const & cites = bibinfo.citedEntries();
978 docstring const reflabel = buffer().B_("References");
980 xs << html::StartTag("h2", "class='bibtex'")
982 << html::EndTag("h2")
983 << html::StartTag("div", "class='bibtex'");
985 // Now we loop over the entries
986 vector<docstring>::const_iterator vit = cites.begin();
987 vector<docstring>::const_iterator const ven = cites.end();
988 for (; vit != ven; ++vit) {
989 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
990 if (biit == bibinfo.end())
992 BibTeXInfo const & entry = biit->second;
993 xs << html::StartTag("div", "class='bibtexentry'");
995 // The same name/id problem we have elsewhere.
997 "id='LyXCite-" + to_utf8(html::cleanAttr(entry.key())) + "'";
998 xs << html::CompTag("a", attr);
999 xs << html::StartTag("span", "class='bibtexlabel'")
1001 << html::EndTag("span");
1002 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1003 // which will give us all the cross-referenced info. But for every
1004 // entry, so there's a lot of repitition. This should be fixed.
1005 xs << html::StartTag("span", "class='bibtexinfo'")
1006 << XHTMLStream::ESCAPE_AND
1007 << bibinfo.getInfo(entry.key(), buffer(), true)
1008 << html::EndTag("span")
1009 << html::EndTag("div")
1012 xs << html::EndTag("div");
1017 string InsetBibtex::contextMenuName() const
1019 return "context-bibtex";