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
623 // reading a string name
626 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
627 strName += lowercase(ch);
634 // replace the string with its assigned value or
635 // discard it if it's not assigned
636 if (strName.length()) {
637 VarMap::const_iterator pos = strings.find(strName);
638 if (pos != strings.end()) {
645 while (ifs && isSpace(ch)) {
652 // continue reading next value on concatenate with '#'
662 // This method returns a comma separated list of Bibtex entries
663 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
664 InsetIterator const & /*di*/) const
666 // This bibtex parser is a first step to parse bibtex files
669 // - it reads the whole bibtex entry and does a syntax check
670 // (matching delimiters, missing commas,...
671 // - it recovers from errors starting with the next @-character
672 // - it reads @string definitions and replaces them in the
674 // - it accepts more characters in keys or value names than
677 // Officially bibtex does only support ASCII, but in practice
678 // you can use the encoding of the main document as long as
679 // some elements like keys and names are pure ASCII. Therefore
680 // we convert the file from the buffer encoding.
681 // We don't restrict keys to ASCII in LyX, since our own
682 // InsetBibitem can generate non-ASCII keys, and nonstandard
683 // 8bit clean bibtex forks exist.
684 support::FileNameList const files = getBibFiles();
685 support::FileNameList::const_iterator it = files.begin();
686 support::FileNameList::const_iterator en = files.end();
687 for (; it != en; ++ it) {
688 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
689 ios_base::in, buffer().params().encoding().iconvName());
705 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
706 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
711 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
715 if (entryType == from_ascii("comment")) {
716 ifs.ignore(numeric_limits<int>::max(), '\n');
722 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
726 if ((ch != '(') && (ch != '{')) {
727 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
733 if (entryType == from_ascii("string")) {
735 // read string and add it to the strings map
736 // (or replace it's old value)
740 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
741 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
746 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
750 // next char must be an equal sign
752 if (!ifs || ch != '=') {
753 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
754 name << "." << std::endl;
758 if (!readValue(value, ifs, strings)) {
759 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
760 name << "." << std::endl;
764 strings[name] = value;
766 } else if (entryType == from_ascii("preamble")) {
768 // preamble definitions are discarded.
769 // can they be of any use in lyx?
772 if (!readValue(value, ifs, strings)) {
773 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
779 // Citation entry. Try to read the key.
782 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
783 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
784 entryType << "." << std::endl;
789 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
793 /////////////////////////////////////////////
794 // now we have a key, so we will add an entry
795 // (even if it's empty, as bibtex does)
797 // we now read the field = value pairs.
798 // all items must be separated by a comma. If
799 // it is missing the scanning of this entry is
800 // stopped and the next is searched.
804 docstring commaNewline;
806 BibTeXInfo keyvalmap(key, entryType);
808 bool readNext = removeWSAndComma(ifs);
810 while (ifs && readNext) {
813 if (!readTypeOrKey(name, ifs, from_ascii("="),
814 from_ascii("{}(),"), makeLowerCase) || !ifs)
817 // next char must be an equal sign
820 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
824 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
825 name << ", for key: " << key << "." << std::endl;
831 if (!readValue(value, ifs, strings)) {
832 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
833 name << ", for key: " << key << "." << std::endl;
837 keyvalmap[name] = value;
838 data += "\n\n" + value;
839 keylist.addFieldName(name);
840 readNext = removeWSAndComma(ifs);
844 keylist.addEntryType(entryType);
845 keyvalmap.setAllData(data);
846 keylist[key] = keyvalmap;
847 } //< else (citation entry)
849 } //< for loop over files
853 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
855 string texfile = changeExtension(to_utf8(filename), "bib");
856 // note that, if the filename can be found directly from the path,
857 // findtexfile will just return a FileName object for that path.
858 FileName file(findtexfile(texfile, "bib"));
860 file = FileName(makeAbsPath(texfile, buf.filePath()));
865 bool InsetBibtex::addDatabase(docstring const & db)
867 docstring bibfiles = getParam("bibfiles");
868 if (tokenPos(bibfiles, ',', db) != -1)
870 if (!bibfiles.empty())
872 setParam("bibfiles", bibfiles + db);
877 bool InsetBibtex::delDatabase(docstring const & db)
879 docstring bibfiles = getParam("bibfiles");
880 if (contains(bibfiles, db)) {
881 int const n = tokenPos(bibfiles, ',', db);
884 // this is not the first database
885 docstring tmp = ',' + bd;
886 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
888 // this is the first (or only) database
889 setParam("bibfiles", split(bibfiles, bd, ','));
897 void InsetBibtex::validate(LaTeXFeatures & features) const
899 if (features.bufferParams().use_bibtopic)
900 features.require("bibtopic");
902 // It'd be better to be able to get this from an InsetLayout, but at present
903 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
904 if (features.runparams().flavor == OutputParams::HTML)
905 features.addPreambleSnippet("<style type=\"text/css\">\n"
906 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
907 "span.bibtexlabel:before{ content: \"[\"; }\n"
908 "span.bibtexlabel:after{ content: \"] \"; }\n"
914 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
915 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
916 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
918 BiblioInfo const & bibinfo = buffer().masterBibInfo();
919 vector<docstring> const & cites = bibinfo.citedEntries();
920 CiteEngine const engine = buffer().params().citeEngine();
922 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
924 xs << html::StartTag("h2", "class='bibtex'")
926 << html::EndTag("h2")
927 << html::StartTag("div", "class='bibtex'");
929 // Now we loop over the entries
930 vector<docstring>::const_iterator vit = cites.begin();
931 vector<docstring>::const_iterator const ven = cites.end();
932 for (; vit != ven; ++vit) {
933 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
934 if (biit == bibinfo.end())
936 BibTeXInfo const & entry = biit->second;
937 xs << html::StartTag("div", "class='bibtexentry'");
939 // The same name/id problem we have elsewhere.
940 string const attr = "id='" + to_utf8(entry.key()) + "'";
941 xs << html::CompTag("a", attr);
944 citekey = entry.citeNumber();
946 docstring const auth = entry.getAbbreviatedAuthor();
947 // we do it this way so as to access the xref, if necessary
948 // note that this also gives us the modifier
949 docstring const year = bibinfo.getYear(*vit, true);
950 if (!auth.empty() && !year.empty())
951 citekey = auth + ' ' + year;
953 if (citekey.empty()) {
954 citekey = entry.label();
956 citekey = entry.key();
958 xs << html::StartTag("span", "class='bibtexlabel'")
960 << html::EndTag("span");
961 // FIXME Right now, we are calling BibInfo::getInfo on the key,
962 // which will give us all the cross-referenced info. But for every
963 // entry, so there's a lot of repitition. This should be fixed.
964 xs << html::StartTag("span", "class='bibtexinfo'")
965 << bibinfo.getInfo(entry.key(), buffer(), true)
966 << html::EndTag("span")
967 << html::EndTag("div");
970 xs << html::EndTag("div");
975 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
977 return from_ascii("context-bibtex");