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 "MetricsInfo.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"
41 #include <boost/regex.hpp>
46 using namespace lyx::support;
50 namespace Alert = frontend::Alert;
51 namespace os = support::os;
54 InsetBibtex::InsetBibtex(Buffer const & buf, InsetCommandParams const & p)
55 : InsetCommand(p, "bibtex")
57 Inset::setBuffer(const_cast<Buffer &>(buf));
58 buffer_->invalidateBibinfoCache();
62 InsetBibtex::~InsetBibtex()
65 buffer_->invalidateBibinfoCache();
69 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
71 static ParamInfo param_info_;
72 if (param_info_.empty()) {
73 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
74 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
75 param_info_.add("options", ParamInfo::LYX_INTERNAL);
81 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
89 case LFUN_INSET_MODIFY: {
90 InsetCommandParams p(BIBTEX_CODE);
92 if (!InsetCommand::string2params("bibtex",
93 to_utf8(cmd.argument()), p)) {
97 } catch (ExceptionMessage const & message) {
98 if (message.type_ == WarningException) {
99 Alert::warning(message.title_, message.details_);
107 buffer().updateBibfilesCache();
112 InsetCommand::doDispatch(cur, cmd);
118 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
119 FuncStatus & flag) const
121 switch (cmd.action) {
122 case LFUN_INSET_EDIT:
123 flag.setEnabled(true);
127 return InsetCommand::getStatus(cur, cmd, flag);
132 void InsetBibtex::editDatabases() const
134 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
136 if (bibfilelist.empty())
139 int nr_databases = bibfilelist.size();
140 if (nr_databases > 1) {
141 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
142 "If you proceed, all of them will be opened."),
143 convert<docstring>(nr_databases));
144 int const ret = Alert::prompt(_("Open Databases?"),
145 message, 0, 1, _("&Cancel"), _("&Proceed"));
151 vector<docstring>::const_iterator it = bibfilelist.begin();
152 vector<docstring>::const_iterator en = bibfilelist.end();
153 for (; it != en; ++it) {
154 FileName bibfile = getBibTeXPath(*it, buffer());
155 formats.edit(buffer(), bibfile,
156 formats.getFormatFromFile(bibfile));
161 docstring InsetBibtex::screenLabel() const
163 return _("BibTeX Generated Bibliography");
167 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
169 docstring item = from_ascii("* ");
170 docstring tip = _("Databases:") + "\n";
171 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
173 if (bibfilelist.empty()) {
177 vector<docstring>::const_iterator it = bibfilelist.begin();
178 vector<docstring>::const_iterator en = bibfilelist.end();
179 for (; it != en; ++it) {
187 docstring style = getParam("options"); // maybe empty! and with bibtotoc
188 docstring bibtotoc = from_ascii("bibtotoc");
189 if (prefixIs(style, bibtotoc)) {
191 if (contains(style, char_type(',')))
192 style = split(style, bibtotoc, char_type(','));
195 tip += _("Style File:") +"\n";
202 tip += "\n" + _("Lists:") + " ";
203 docstring btprint = getParam("btprint");
204 if (btprint == "btPrintAll")
205 tip += _("all references");
206 else if (btprint == "btPrintNotCited")
207 tip += _("all uncited references");
209 tip += _("all cited references");
213 tip += _("included in TOC");
220 static string normalizeName(Buffer const & buffer,
221 OutputParams const & runparams, string const & name, string const & ext)
223 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
224 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
230 return to_utf8(makeRelPath(from_utf8(fname),
231 from_utf8(buffer.masterBuffer()->filePath())));
235 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
237 // the sequence of the commands:
238 // 1. \bibliographystyle{style}
239 // 2. \addcontentsline{...} - if option bibtotoc set
240 // 3. \bibliography{database}
241 // and with bibtopic:
242 // 1. \bibliographystyle{style}
243 // 2. \begin{btSect}{database}
244 // 3. \btPrint{Cited|NotCited|All}
248 // If we are processing the LaTeX file in a temp directory then
249 // copy the .bib databases to this temp directory, mangling their
250 // names in the process. Store this mangled name in the list of
252 // (We need to do all this because BibTeX *really*, *really*
253 // can't handle "files with spaces" and Windows users tend to
254 // use such filenames.)
255 // Otherwise, store the (maybe absolute) path to the original,
256 // unmangled database name.
257 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
258 vector<docstring>::const_iterator it = bibfilelist.begin();
259 vector<docstring>::const_iterator en = bibfilelist.end();
260 odocstringstream dbs;
263 for (; it != en; ++it) {
264 string utf8input = to_utf8(*it);
266 normalizeName(buffer(), runparams, utf8input, ".bib");
267 FileName const try_in_file =
268 makeAbsPath(database + ".bib", buffer().filePath());
269 bool const not_from_texmf = try_in_file.isReadableFile();
271 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
273 // mangledFilename() needs the extension
274 DocFileName const in_file = DocFileName(try_in_file);
275 database = removeExtension(in_file.mangledFilename());
276 FileName const out_file = makeAbsPath(database + ".bib",
277 buffer().masterBuffer()->temppath());
279 bool const success = in_file.copyTo(out_file);
281 lyxerr << "Failed to copy '" << in_file
282 << "' to '" << out_file << "'"
285 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
286 !isValidLaTeXFilename(database)) {
287 frontend::Alert::warning(_("Invalid filename"),
288 _("The following filename is likely to cause trouble "
289 "when running the exported file through LaTeX: ") +
290 from_utf8(database));
298 dbs << from_utf8(latex_path(database));
300 docstring const db_out = dbs.str();
302 // Post this warning only once.
303 static bool warned_about_spaces = false;
304 if (!warned_about_spaces &&
305 runparams.nice && db_out.find(' ') != docstring::npos) {
306 warned_about_spaces = true;
307 Alert::warning(_("Export Warning!"),
308 _("There are spaces in the paths to your BibTeX databases.\n"
309 "BibTeX will be unable to find them."));
312 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
314 if (prefixIs(style, "bibtotoc")) {
315 bibtotoc = "bibtotoc";
316 if (contains(style, ','))
317 style = split(style, bibtotoc, ',');
323 if (!style.empty()) {
324 string base = normalizeName(buffer(), runparams, style, ".bst");
325 FileName const try_in_file =
326 makeAbsPath(base + ".bst", buffer().filePath());
327 bool const not_from_texmf = try_in_file.isReadableFile();
328 // If this style does not come from texmf and we are not
329 // exporting to .tex copy it to the tmp directory.
330 // This prevents problems with spaces and 8bit charcaters
332 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
334 // use new style name
335 DocFileName const in_file = DocFileName(try_in_file);
336 base = removeExtension(in_file.mangledFilename());
337 FileName const out_file = makeAbsPath(base + ".bst",
338 buffer().masterBuffer()->temppath());
339 bool const success = in_file.copyTo(out_file);
341 lyxerr << "Failed to copy '" << in_file
342 << "' to '" << out_file << "'"
347 os << "\\bibliographystyle{"
348 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
353 // Post this warning only once.
354 static bool warned_about_bst_spaces = false;
355 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
356 warned_about_bst_spaces = true;
357 Alert::warning(_("Export Warning!"),
358 _("There are spaces in the path to your BibTeX style file.\n"
359 "BibTeX will be unable to find it."));
362 if (!db_out.empty() && buffer().params().use_bibtopic) {
363 os << "\\begin{btSect}{" << db_out << "}\n";
364 docstring btprint = getParam("btprint");
367 btprint = from_ascii("btPrintCited");
368 os << "\\" << btprint << "\n"
369 << "\\end{btSect}\n";
374 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
375 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
376 if (buffer().params().sides == OneSide) {
381 os << "\\cleardoublepage";
383 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
384 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
385 os << "\\addcontentsline{toc}{section}{\\refname}";
388 if (!db_out.empty() && !buffer().params().use_bibtopic) {
389 docstring btprint = getParam("btprint");
390 if (btprint == "btPrintAll") {
391 os << "\\nocite{*}\n";
394 os << "\\bibliography{" << db_out << "}\n";
402 support::FileNameList InsetBibtex::getBibFiles() const
404 FileName path(buffer().filePath());
405 support::PathChanger p(path);
407 support::FileNameList vec;
409 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
410 vector<docstring>::const_iterator it = bibfilelist.begin();
411 vector<docstring>::const_iterator en = bibfilelist.end();
412 for (; it != en; ++it) {
413 FileName const file =
414 findtexfile(changeExtension(to_utf8(*it), "bib"), "bib");
419 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
428 // methods for parsing bibtex files
430 typedef map<docstring, docstring> VarMap;
432 /// remove whitespace characters, optionally a single comma,
433 /// and further whitespace characters from the stream.
434 /// @return true if a comma was found, false otherwise
436 bool removeWSAndComma(ifdocstream & ifs) {
445 } while (ifs && isSpace(ch));
458 } while (ifs && isSpace(ch));
473 /// remove whitespace characters, read characer sequence
474 /// not containing whitespace characters or characters in
475 /// delimChars, and remove further whitespace characters.
477 /// @return true if a string of length > 0 could be read.
479 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
480 docstring const & delimChars, docstring const &illegalChars,
493 } while (ifs && isSpace(ch));
499 bool legalChar = true;
500 while (ifs && !isSpace(ch) &&
501 delimChars.find(ch) == docstring::npos &&
502 (legalChar = (illegalChars.find(ch) == docstring::npos))
505 if (chCase == makeLowerCase)
506 val += lowercase(ch);
518 while (ifs && isSpace(ch)) {
526 return val.length() > 0;
529 /// read subsequent bibtex values that are delimited with a #-character.
530 /// Concatenate all parts and replace names with the associated string in
531 /// the variable strings.
532 /// @return true if reading was successfull (all single parts were delimited
534 bool readValue(docstring & value, ifdocstream & ifs, const VarMap & strings) {
548 } while (ifs && isSpace(ch));
553 // check for field type
556 // read integer value
560 } while (ifs && isDigit(ch));
565 } else if (ch == '"' || ch == '{') {
567 char_type delim = ch == '"' ? '"': '}';
572 } while (ifs && isSpace(ch));
577 // We now have the first non-whitespace character
578 // We'll collapse adjacent whitespace.
579 bool lastWasWhiteSpace = false;
581 // inside this delimited text braces must match.
582 // Thus we can have a closing delimiter only
583 // when nestLevel == 0
586 while (ifs && (nestLevel > 0 || ch != delim)) {
588 lastWasWhiteSpace = true;
592 // We output the space only after we stop getting
593 // whitespace so as not to output any whitespace
594 // at the end of the value.
595 if (lastWasWhiteSpace) {
596 lastWasWhiteSpace = false;
602 // update nesting level
609 if (nestLevel < 0) return false;
626 // reading a string name
629 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
630 strName += lowercase(ch);
637 // replace the string with its assigned value or
638 // discard it if it's not assigned
639 if (strName.length()) {
640 VarMap::const_iterator pos = strings.find(strName);
641 if (pos != strings.end()) {
648 while (ifs && isSpace(ch)) {
655 // continue reading next value on concatenate with '#'
660 // Ok, we now have the value. Now we are going to go
661 // through it and replace e.g. \"a with its unicode value.
662 // We'll also strip commands, like \emph, and the like, so
663 // it will look nice in the UI.
664 bool scanning_cmd = false;
665 bool scanning_math = false;
666 bool escaped = false; // used to catch \$, etc.
668 char_type const ch = val[0];
670 // if we're scanning math, we output everything until we
671 // find an unescaped $, at which point we break out.
678 scanning_math = false;
684 // if we're scanning a command name, then we just
685 // discard characters until we hit something that
688 if (isAlphaASCII(ch)) {
693 // so we're done with this command.
694 // now we fall through and check this character.
695 scanning_cmd = false;
698 // was the last character a \? If so, then this is something like: \\,
699 // or \$, so we'll just output it. That's probably not always right...
710 scanning_math = true;
714 // we just ignore braces
715 if (ch == '{' || ch == '}') {
720 // we're going to check things that look like commands, so if
721 // this doesn't, just output it.
728 // ok, could be a command of some sort
729 // let's see if it corresponds to some unicode
730 // unicodesymbols has things in the form: \"{u},
731 // whereas we may see things like: \"u. So we'll
732 // look for that and change it, if necessary.
733 static boost::regex const reg("^\\\\\\W\\w");
734 if (boost::regex_search(to_utf8(val), reg)) {
735 val.insert(3, from_ascii("}"));
736 val.insert(2, from_ascii("{"));
739 docstring const cnvtd = Encodings::fromLaTeXCommand(val, rem);
740 if (!cnvtd.empty()) {
741 // it did, so we'll take that bit and proceed with what's left
746 // it's a command of some sort
757 // This method returns a comma separated list of Bibtex entries
758 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
759 InsetIterator const & /*di*/) const
761 // This bibtex parser is a first step to parse bibtex files
764 // - it reads the whole bibtex entry and does a syntax check
765 // (matching delimiters, missing commas,...
766 // - it recovers from errors starting with the next @-character
767 // - it reads @string definitions and replaces them in the
769 // - it accepts more characters in keys or value names than
772 // Officially bibtex does only support ASCII, but in practice
773 // you can use the encoding of the main document as long as
774 // some elements like keys and names are pure ASCII. Therefore
775 // we convert the file from the buffer encoding.
776 // We don't restrict keys to ASCII in LyX, since our own
777 // InsetBibitem can generate non-ASCII keys, and nonstandard
778 // 8bit clean bibtex forks exist.
779 support::FileNameList const files = getBibFiles();
780 support::FileNameList::const_iterator it = files.begin();
781 support::FileNameList::const_iterator en = files.end();
782 for (; it != en; ++ it) {
783 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
784 ios_base::in, buffer().params().encoding().iconvName());
800 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
801 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
806 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
810 if (entryType == from_ascii("comment")) {
811 ifs.ignore(numeric_limits<int>::max(), '\n');
817 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
821 if ((ch != '(') && (ch != '{')) {
822 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
828 if (entryType == from_ascii("string")) {
830 // read string and add it to the strings map
831 // (or replace it's old value)
835 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
836 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
841 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
845 // next char must be an equal sign
847 if (!ifs || ch != '=') {
848 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
849 name << "." << std::endl;
853 if (!readValue(value, ifs, strings)) {
854 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
855 name << "." << std::endl;
859 strings[name] = value;
861 } else if (entryType == from_ascii("preamble")) {
863 // preamble definitions are discarded.
864 // can they be of any use in lyx?
867 if (!readValue(value, ifs, strings)) {
868 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
874 // Citation entry. Try to read the key.
877 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
878 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
879 entryType << "." << std::endl;
884 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
888 /////////////////////////////////////////////
889 // now we have a key, so we will add an entry
890 // (even if it's empty, as bibtex does)
892 // we now read the field = value pairs.
893 // all items must be separated by a comma. If
894 // it is missing the scanning of this entry is
895 // stopped and the next is searched.
899 docstring commaNewline;
901 BibTeXInfo keyvalmap(key, entryType);
903 bool readNext = removeWSAndComma(ifs);
905 while (ifs && readNext) {
908 if (!readTypeOrKey(name, ifs, from_ascii("="),
909 from_ascii("{}(),"), makeLowerCase) || !ifs)
912 // next char must be an equal sign
915 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
919 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
920 name << ", for key: " << key << "." << std::endl;
926 if (!readValue(value, ifs, strings)) {
927 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
928 name << ", for key: " << key << "." << std::endl;
932 keyvalmap[name] = value;
933 data += "\n\n" + value;
934 keylist.addFieldName(name);
935 readNext = removeWSAndComma(ifs);
939 keylist.addEntryType(entryType);
940 keyvalmap.setAllData(data);
941 keylist[key] = keyvalmap;
942 } //< else (citation entry)
944 } //< for loop over files
948 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
950 string texfile = changeExtension(to_utf8(filename), "bib");
951 // note that, if the filename can be found directly from the path,
952 // findtexfile will just return a FileName object for that path.
953 FileName file(findtexfile(texfile, "bib"));
955 file = FileName(makeAbsPath(texfile, buf.filePath()));
960 bool InsetBibtex::addDatabase(docstring const & db)
962 docstring bibfiles = getParam("bibfiles");
963 if (tokenPos(bibfiles, ',', db) != -1)
965 if (!bibfiles.empty())
967 setParam("bibfiles", bibfiles + db);
972 bool InsetBibtex::delDatabase(docstring const & db)
974 docstring bibfiles = getParam("bibfiles");
975 if (contains(bibfiles, db)) {
976 int const n = tokenPos(bibfiles, ',', db);
979 // this is not the first database
980 docstring tmp = ',' + bd;
981 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
983 // this is the first (or only) database
984 setParam("bibfiles", split(bibfiles, bd, ','));
992 void InsetBibtex::validate(LaTeXFeatures & features) const
994 if (features.bufferParams().use_bibtopic)
995 features.require("bibtopic");
999 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
1001 return from_ascii("context-bibtex");