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() && !buffer().params().use_bibtopic) {
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}";
382 os << "[" << style << "]";
383 os << "{" << db_out << "}\n";
384 docstring btprint = getParam("btprint");
387 btprint = from_ascii("btPrintCited");
388 os << "\\" << btprint << "\n"
389 << "\\end{btSect}\n";
393 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
394 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
395 if (buffer().params().pdfoptions().use_hyperref)
396 os << "\\phantomsection";
397 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
398 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
399 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
400 os << "\\addcontentsline{toc}{section}{\\refname}";
403 if (!db_out.empty() && !buffer().params().use_bibtopic) {
404 docstring btprint = getParam("btprint");
405 if (btprint == "btPrintAll") {
406 os << "\\nocite{*}\n";
408 os << "\\bibliography{" << db_out << "}\n";
413 support::FileNameList InsetBibtex::getBibFiles() const
415 FileName path(buffer().filePath());
416 support::PathChanger p(path);
418 support::FileNameList vec;
420 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
421 vector<docstring>::const_iterator it = bibfilelist.begin();
422 vector<docstring>::const_iterator en = bibfilelist.end();
423 for (; it != en; ++it) {
424 FileName const file = getBibTeXPath(*it, buffer());
429 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
438 // methods for parsing bibtex files
440 typedef map<docstring, docstring> VarMap;
442 /// remove whitespace characters, optionally a single comma,
443 /// and further whitespace characters from the stream.
444 /// @return true if a comma was found, false otherwise
446 bool removeWSAndComma(ifdocstream & ifs) {
455 } while (ifs && isSpace(ch));
468 } while (ifs && isSpace(ch));
483 /// remove whitespace characters, read characer sequence
484 /// not containing whitespace characters or characters in
485 /// delimChars, and remove further whitespace characters.
487 /// @return true if a string of length > 0 could be read.
489 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
490 docstring const & delimChars, docstring const & illegalChars,
503 } while (ifs && isSpace(ch));
509 bool legalChar = true;
510 while (ifs && !isSpace(ch) &&
511 delimChars.find(ch) == docstring::npos &&
512 (legalChar = (illegalChars.find(ch) == docstring::npos))
515 if (chCase == makeLowerCase)
516 val += lowercase(ch);
528 while (ifs && isSpace(ch)) {
536 return val.length() > 0;
539 /// read subsequent bibtex values that are delimited with a #-character.
540 /// Concatenate all parts and replace names with the associated string in
541 /// the variable strings.
542 /// @return true if reading was successfull (all single parts were delimited
544 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
557 } while (ifs && isSpace(ch));
562 // check for field type
563 if (isDigitASCII(ch)) {
565 // read integer value
569 } while (ifs && isDigitASCII(ch));
574 } else if (ch == '"' || ch == '{') {
576 char_type delim = ch == '"' ? '"': '}';
581 } while (ifs && isSpace(ch));
586 // We now have the first non-whitespace character
587 // We'll collapse adjacent whitespace.
588 bool lastWasWhiteSpace = false;
590 // inside this delimited text braces must match.
591 // Thus we can have a closing delimiter only
592 // when nestLevel == 0
595 while (ifs && (nestLevel > 0 || ch != delim)) {
597 lastWasWhiteSpace = true;
601 // We output the space only after we stop getting
602 // whitespace so as not to output any whitespace
603 // at the end of the value.
604 if (lastWasWhiteSpace) {
605 lastWasWhiteSpace = false;
611 // update nesting level
630 // FIXME Why is this here?
638 // reading a string name
641 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
642 strName += lowercase(ch);
649 // replace the string with its assigned value or
650 // discard it if it's not assigned
651 if (strName.length()) {
652 VarMap::const_iterator pos = strings.find(strName);
653 if (pos != strings.end()) {
660 while (ifs && isSpace(ch)) {
667 // continue reading next value on concatenate with '#'
677 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
683 void InsetBibtex::parseBibTeXFiles() const
685 // This bibtex parser is a first step to parse bibtex files
688 // - it reads the whole bibtex entry and does a syntax check
689 // (matching delimiters, missing commas,...
690 // - it recovers from errors starting with the next @-character
691 // - it reads @string definitions and replaces them in the
693 // - it accepts more characters in keys or value names than
696 // Officially bibtex does only support ASCII, but in practice
697 // you can use the encoding of the main document as long as
698 // some elements like keys and names are pure ASCII. Therefore
699 // we convert the file from the buffer encoding.
700 // We don't restrict keys to ASCII in LyX, since our own
701 // InsetBibitem can generate non-ASCII keys, and nonstandard
702 // 8bit clean bibtex forks exist.
706 support::FileNameList const files = getBibFiles();
707 support::FileNameList::const_iterator it = files.begin();
708 support::FileNameList::const_iterator en = files.end();
709 for (; it != en; ++ it) {
710 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
711 ios_base::in, buffer().params().encoding().iconvName());
727 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
728 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
733 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
737 if (entryType == from_ascii("comment")) {
738 ifs.ignore(numeric_limits<int>::max(), '\n');
744 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
748 if ((ch != '(') && (ch != '{')) {
749 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
755 if (entryType == from_ascii("string")) {
757 // read string and add it to the strings map
758 // (or replace it's old value)
762 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
763 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
768 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
772 // next char must be an equal sign
774 if (!ifs || ch != '=') {
775 lyxerr << "BibTeX Parser: No `=' after string name: " <<
776 name << "." << std::endl;
780 if (!readValue(value, ifs, strings)) {
781 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
782 name << "." << std::endl;
786 strings[name] = value;
788 } else if (entryType == from_ascii("preamble")) {
790 // preamble definitions are discarded.
791 // can they be of any use in lyx?
794 if (!readValue(value, ifs, strings)) {
795 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
801 // Citation entry. Try to read the key.
804 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
805 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
806 entryType << "." << std::endl;
811 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
815 /////////////////////////////////////////////
816 // now we have a key, so we will add an entry
817 // (even if it's empty, as bibtex does)
819 // we now read the field = value pairs.
820 // all items must be separated by a comma. If
821 // it is missing the scanning of this entry is
822 // stopped and the next is searched.
826 BibTeXInfo keyvalmap(key, entryType);
828 bool readNext = removeWSAndComma(ifs);
830 while (ifs && readNext) {
833 if (!readTypeOrKey(name, ifs, from_ascii("="),
834 from_ascii("{}(),"), makeLowerCase) || !ifs)
837 // next char must be an equal sign
838 // FIXME Whitespace??
841 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
845 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
846 name << ", for key: " << key << "." << std::endl;
852 if (!readValue(value, ifs, strings)) {
853 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
854 name << ", for key: " << key << "." << std::endl;
858 keyvalmap[name] = value;
859 data += "\n\n" + value;
860 keylist.addFieldName(name);
861 readNext = removeWSAndComma(ifs);
865 keylist.addEntryType(entryType);
866 keyvalmap.setAllData(data);
867 keylist[key] = keyvalmap;
868 } //< else (citation entry)
870 } //< for loop over files
872 buffer().addBiblioInfo(keylist);
876 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
878 string texfile = changeExtension(to_utf8(filename), "bib");
879 // note that, if the filename can be found directly from the path,
880 // findtexfile will just return a FileName object for that path.
881 FileName file(findtexfile(texfile, "bib"));
883 file = FileName(makeAbsPath(texfile, buf.filePath()));
888 bool InsetBibtex::addDatabase(docstring const & db)
890 docstring bibfiles = getParam("bibfiles");
891 if (tokenPos(bibfiles, ',', db) != -1)
893 if (!bibfiles.empty())
895 setParam("bibfiles", bibfiles + db);
900 bool InsetBibtex::delDatabase(docstring const & db)
902 docstring bibfiles = getParam("bibfiles");
903 if (contains(bibfiles, db)) {
904 int const n = tokenPos(bibfiles, ',', db);
907 // this is not the first database
908 docstring tmp = ',' + bd;
909 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
911 // this is the first (or only) database
912 setParam("bibfiles", split(bibfiles, bd, ','));
920 void InsetBibtex::validate(LaTeXFeatures & features) const
922 if (features.bufferParams().use_bibtopic)
923 features.require("bibtopic");
925 // It'd be better to be able to get this from an InsetLayout, but at present
926 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
927 if (features.runparams().flavor == OutputParams::HTML)
928 features.addCSSSnippet("div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
929 "span.bibtexlabel:before{ content: \"[\"; }\n"
930 "span.bibtexlabel:after{ content: \"] \"; }");
934 int InsetBibtex::plaintext(odocstringstream & os,
935 OutputParams const & op, size_t max_length) const
937 docstring const reflabel = buffer().B_("References");
939 // We could output more information here, e.g., what databases are included
940 // and information about options. But I don't necessarily see any reason to
941 // do this right now.
942 if (op.for_tooltip || op.for_toc || op.for_search) {
943 os << '[' << reflabel << ']' << '\n';
944 return PLAINTEXT_NEWLINE;
947 BiblioInfo bibinfo = buffer().masterBibInfo();
948 bibinfo.makeCitationLabels(buffer());
949 vector<docstring> const & cites = bibinfo.citedEntries();
951 size_t start_size = os.str().size();
953 refoutput += reflabel + "\n\n";
955 // Now we loop over the entries
956 vector<docstring>::const_iterator vit = cites.begin();
957 vector<docstring>::const_iterator const ven = cites.end();
958 for (; vit != ven; ++vit) {
959 if (start_size + refoutput.size() >= max_length)
961 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
962 if (biit == bibinfo.end())
964 BibTeXInfo const & entry = biit->second;
965 refoutput += "[" + entry.label() + "] ";
966 // FIXME Right now, we are calling BibInfo::getInfo on the key,
967 // which will give us all the cross-referenced info. But for every
968 // entry, so there's a lot of repitition. This should be fixed.
969 refoutput += bibinfo.getInfo(entry.key(), buffer(), false) + "\n\n";
972 return refoutput.size();
977 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
978 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
979 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
981 BiblioInfo const & bibinfo = buffer().masterBibInfo();
982 bool const all_entries = getParam("btprint") == "btPrintAll";
983 vector<docstring> const & cites =
984 all_entries ? bibinfo.getKeys() : bibinfo.citedEntries();
986 docstring const reflabel = buffer().B_("References");
988 xs << html::StartTag("h2", "class='bibtex'")
990 << html::EndTag("h2")
991 << html::StartTag("div", "class='bibtex'");
993 // Now we loop over the entries
994 vector<docstring>::const_iterator vit = cites.begin();
995 vector<docstring>::const_iterator const ven = cites.end();
996 for (; vit != ven; ++vit) {
997 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
998 if (biit == bibinfo.end())
1001 BibTeXInfo const & entry = biit->second;
1002 string const attr = "class='bibtexentry' id='LyXCite-"
1003 + to_utf8(html::cleanAttr(entry.key())) + "'";
1004 xs << html::StartTag("div", attr);
1006 // don't print labels if we're outputting all entries
1008 xs << html::StartTag("span", "class='bibtexlabel'")
1010 << html::EndTag("span");
1013 // FIXME Right now, we are calling BibInfo::getInfo on the key,
1014 // which will give us all the cross-referenced info. But for every
1015 // entry, so there's a lot of repitition. This should be fixed.
1016 xs << html::StartTag("span", "class='bibtexinfo'")
1017 << XHTMLStream::ESCAPE_AND
1018 << bibinfo.getInfo(entry.key(), buffer(), true)
1019 << html::EndTag("span")
1020 << html::EndTag("div")
1023 xs << html::EndTag("div");
1028 void InsetBibtex::write(ostream & os) const
1030 params().Write(os, &buffer());
1034 string InsetBibtex::contextMenuName() const
1036 return "context-bibtex";