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"
44 using namespace lyx::support;
48 namespace Alert = frontend::Alert;
49 namespace os = support::os;
52 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
53 : InsetCommand(p, "bibtex")
57 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
59 static ParamInfo param_info_;
60 if (param_info_.empty()) {
61 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
62 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
63 param_info_.add("options", ParamInfo::LYX_INTERNAL);
69 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
77 case LFUN_INSET_MODIFY: {
78 InsetCommandParams p(BIBTEX_CODE);
80 if (!InsetCommand::string2params("bibtex",
81 to_utf8(cmd.argument()), p)) {
85 } catch (ExceptionMessage const & message) {
86 if (message.type_ == WarningException) {
87 Alert::warning(message.title_, message.details_);
95 buffer().updateBibfilesCache();
100 InsetCommand::doDispatch(cur, cmd);
106 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
107 FuncStatus & flag) const
109 switch (cmd.action) {
110 case LFUN_INSET_EDIT:
111 flag.setEnabled(true);
115 return InsetCommand::getStatus(cur, cmd, flag);
120 void InsetBibtex::editDatabases() const
122 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
124 if (bibfilelist.empty())
127 int nr_databases = bibfilelist.size();
128 if (nr_databases > 1) {
129 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
130 "If you proceed, all of them will be opened."),
131 convert<docstring>(nr_databases));
132 int const ret = Alert::prompt(_("Open Databases?"),
133 message, 0, 1, _("&Cancel"), _("&Proceed"));
139 vector<docstring>::const_iterator it = bibfilelist.begin();
140 vector<docstring>::const_iterator en = bibfilelist.end();
141 for (; it != en; ++it) {
142 FileName bibfile = getBibTeXPath(*it, buffer());
143 formats.edit(buffer(), bibfile,
144 formats.getFormatFromFile(bibfile));
149 docstring InsetBibtex::screenLabel() const
151 return _("BibTeX Generated Bibliography");
155 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
157 docstring item = from_ascii("* ");
158 docstring tip = _("Databases:") + "\n";
159 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
161 if (bibfilelist.empty()) {
165 vector<docstring>::const_iterator it = bibfilelist.begin();
166 vector<docstring>::const_iterator en = bibfilelist.end();
167 for (; it != en; ++it) {
175 docstring style = getParam("options"); // maybe empty! and with bibtotoc
176 docstring bibtotoc = from_ascii("bibtotoc");
177 if (prefixIs(style, bibtotoc)) {
179 if (contains(style, char_type(',')))
180 style = split(style, bibtotoc, char_type(','));
183 tip += _("Style File:") +"\n";
190 tip += "\n" + _("Lists:") + " ";
191 docstring btprint = getParam("btprint");
192 if (btprint == "btPrintAll")
193 tip += _("all references");
194 else if (btprint == "btPrintNotCited")
195 tip += _("all uncited references");
197 tip += _("all cited references");
201 tip += _("included in TOC");
208 static string normalizeName(Buffer const & buffer,
209 OutputParams const & runparams, string const & name, string const & ext)
211 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
212 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
218 return to_utf8(makeRelPath(from_utf8(fname),
219 from_utf8(buffer.masterBuffer()->filePath())));
223 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
225 // the sequence of the commands:
226 // 1. \bibliographystyle{style}
227 // 2. \addcontentsline{...} - if option bibtotoc set
228 // 3. \bibliography{database}
229 // and with bibtopic:
230 // 1. \bibliographystyle{style}
231 // 2. \begin{btSect}{database}
232 // 3. \btPrint{Cited|NotCited|All}
236 // If we are processing the LaTeX file in a temp directory then
237 // copy the .bib databases to this temp directory, mangling their
238 // names in the process. Store this mangled name in the list of
240 // (We need to do all this because BibTeX *really*, *really*
241 // can't handle "files with spaces" and Windows users tend to
242 // use such filenames.)
243 // Otherwise, store the (maybe absolute) path to the original,
244 // unmangled database name.
245 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
246 vector<docstring>::const_iterator it = bibfilelist.begin();
247 vector<docstring>::const_iterator en = bibfilelist.end();
248 odocstringstream dbs;
251 for (; it != en; ++it) {
252 string utf8input = to_utf8(*it);
254 normalizeName(buffer(), runparams, utf8input, ".bib");
255 FileName const try_in_file =
256 makeAbsPath(database + ".bib", buffer().filePath());
257 bool const not_from_texmf = try_in_file.isReadableFile();
259 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
262 // mangledFilename() needs the extension
263 DocFileName const in_file = DocFileName(try_in_file);
264 database = removeExtension(in_file.mangledFilename());
265 FileName const out_file = makeAbsPath(database + ".bib",
266 buffer().masterBuffer()->temppath());
268 bool const success = in_file.copyTo(out_file);
270 lyxerr << "Failed to copy '" << in_file
271 << "' to '" << out_file << "'"
274 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
275 !isValidLaTeXFilename(database)) {
276 frontend::Alert::warning(_("Invalid filename"),
277 _("The following filename is likely to cause trouble "
278 "when running the exported file through LaTeX: ") +
279 from_utf8(database));
287 dbs << from_utf8(latex_path(database));
289 docstring const db_out = dbs.str();
291 // Post this warning only once.
292 static bool warned_about_spaces = false;
293 if (!warned_about_spaces &&
294 runparams.nice && db_out.find(' ') != docstring::npos) {
295 warned_about_spaces = true;
297 Alert::warning(_("Export Warning!"),
298 _("There are spaces in the paths to your BibTeX databases.\n"
299 "BibTeX will be unable to find them."));
302 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
304 if (prefixIs(style, "bibtotoc")) {
305 bibtotoc = "bibtotoc";
306 if (contains(style, ','))
307 style = split(style, bibtotoc, ',');
314 if (!style.empty()) {
315 string base = normalizeName(buffer(), runparams, style, ".bst");
316 FileName const try_in_file =
317 makeAbsPath(base + ".bst", buffer().filePath());
318 bool const not_from_texmf = try_in_file.isReadableFile();
319 // If this style does not come from texmf and we are not
320 // exporting to .tex copy it to the tmp directory.
321 // This prevents problems with spaces and 8bit charcaters
323 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
325 // use new style name
326 DocFileName const in_file = DocFileName(try_in_file);
327 base = removeExtension(in_file.mangledFilename());
328 FileName const out_file = makeAbsPath(base + ".bst",
329 buffer().masterBuffer()->temppath());
330 bool const success = in_file.copyTo(out_file);
332 lyxerr << "Failed to copy '" << in_file
333 << "' to '" << out_file << "'"
338 os << "\\bibliographystyle{"
339 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
344 // Post this warning only once.
345 static bool warned_about_bst_spaces = false;
346 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
347 warned_about_bst_spaces = true;
348 Alert::warning(_("Export Warning!"),
349 _("There are spaces in the path to your BibTeX style file.\n"
350 "BibTeX will be unable to find it."));
353 if (!db_out.empty() && buffer().params().use_bibtopic) {
354 os << "\\begin{btSect}{" << db_out << "}\n";
355 docstring btprint = getParam("btprint");
358 btprint = from_ascii("btPrintCited");
359 os << "\\" << btprint << "\n"
360 << "\\end{btSect}\n";
365 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
366 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
367 if (buffer().params().sides == OneSide) {
372 os << "\\cleardoublepage";
374 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
375 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
376 os << "\\addcontentsline{toc}{section}{\\refname}";
379 if (!db_out.empty() && !buffer().params().use_bibtopic) {
380 docstring btprint = getParam("btprint");
381 if (btprint == "btPrintAll") {
382 os << "\\nocite{*}\n";
385 os << "\\bibliography{" << db_out << "}\n";
393 support::FileNameList InsetBibtex::getBibFiles() const
395 FileName path(buffer().filePath());
396 support::PathChanger p(path);
398 support::FileNameList vec;
400 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
401 vector<docstring>::const_iterator it = bibfilelist.begin();
402 vector<docstring>::const_iterator en = bibfilelist.end();
403 for (; it != en; ++it) {
404 FileName const file =
405 findtexfile(changeExtension(to_utf8(*it), "bib"), "bib");
410 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
419 // methods for parsing bibtex files
421 typedef map<docstring, docstring> VarMap;
423 /// remove whitespace characters, optionally a single comma,
424 /// and further whitespace characters from the stream.
425 /// @return true if a comma was found, false otherwise
427 bool removeWSAndComma(idocfstream & ifs) {
436 } while (ifs && isSpace(ch));
449 } while (ifs && isSpace(ch));
464 /// remove whitespace characters, read characer sequence
465 /// not containing whitespace characters or characters in
466 /// delimChars, and remove further whitespace characters.
468 /// @return true if a string of length > 0 could be read.
470 bool readTypeOrKey(docstring & val, idocfstream & ifs,
471 docstring const & delimChars, docstring const &illegalChars,
484 } while (ifs && isSpace(ch));
490 bool legalChar = true;
491 while (ifs && !isSpace(ch) &&
492 delimChars.find(ch) == docstring::npos &&
493 (legalChar = (illegalChars.find(ch) == docstring::npos))
496 if (chCase == makeLowerCase)
497 val += lowercase(ch);
509 while (ifs && isSpace(ch)) {
517 return val.length() > 0;
520 /// read subsequent bibtex values that are delimited with a #-character.
521 /// Concatenate all parts and replace names with the associated string in
522 /// the variable strings.
523 /// @return true if reading was successfull (all single parts were delimited
525 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
538 } while (ifs && isSpace(ch));
543 // check for field type
546 // read integer value
550 } while (ifs && isDigit(ch));
555 } else if (ch == '"' || ch == '{') {
557 char_type delim = ch == '"' ? '"': '}';
562 } while (ifs && isSpace(ch));
567 // We now have the first non-whitespace character
568 // We'll collapse adjacent whitespace.
569 bool lastWasWhiteSpace = false;
571 // inside this delimited text braces must match.
572 // Thus we can have a closing delimiter only
573 // when nestLevel == 0
576 while (ifs && (nestLevel > 0 || ch != delim)) {
578 lastWasWhiteSpace = true;
582 // We output the space only after we stop getting
583 // whitespace so as not to output any whitespace
584 // at the end of the value.
585 if (lastWasWhiteSpace) {
586 lastWasWhiteSpace = false;
592 // update nesting level
599 if (nestLevel < 0) return false;
616 // reading a string name
619 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
620 strName += lowercase(ch);
627 // replace the string with its assigned value or
628 // discard it if it's not assigned
629 if (strName.length()) {
630 VarMap::const_iterator pos = strings.find(strName);
631 if (pos != strings.end()) {
638 while (ifs && isSpace(ch)) {
645 // continue reading next value on concatenate with '#'
655 // This method returns a comma separated list of Bibtex entries
656 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
657 InsetIterator const & /*di*/) const
659 // This bibtex parser is a first step to parse bibtex files
662 // - it reads the whole bibtex entry and does a syntax check
663 // (matching delimiters, missing commas,...
664 // - it recovers from errors starting with the next @-character
665 // - it reads @string definitions and replaces them in the
667 // - it accepts more characters in keys or value names than
670 // Officially bibtex does only support ASCII, but in practice
671 // you can use the encoding of the main document as long as
672 // some elements like keys and names are pure ASCII. Therefore
673 // we convert the file from the buffer encoding.
674 // We don't restrict keys to ASCII in LyX, since our own
675 // InsetBibitem can generate non-ASCII keys, and nonstandard
676 // 8bit clean bibtex forks exist.
677 support::FileNameList const files = getBibFiles();
678 support::FileNameList::const_iterator it = files.begin();
679 support::FileNameList::const_iterator en = files.end();
680 for (; it != en; ++ it) {
681 idocfstream ifs(it->toFilesystemEncoding().c_str(),
682 ios_base::in, buffer().params().encoding().iconvName());
698 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
699 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
704 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
708 if (entryType == from_ascii("comment")) {
709 ifs.ignore(numeric_limits<int>::max(), '\n');
715 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
719 if ((ch != '(') && (ch != '{')) {
720 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
726 if (entryType == from_ascii("string")) {
728 // read string and add it to the strings map
729 // (or replace it's old value)
733 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
734 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
739 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
743 // next char must be an equal sign
745 if (!ifs || ch != '=') {
746 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
747 name << "." << std::endl;
751 if (!readValue(value, ifs, strings)) {
752 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
753 name << "." << std::endl;
757 strings[name] = value;
759 } else if (entryType == from_ascii("preamble")) {
761 // preamble definitions are discarded.
762 // can they be of any use in lyx?
765 if (!readValue(value, ifs, strings)) {
766 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
772 // Citation entry. Try to read the key.
775 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
776 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
777 entryType << "." << std::endl;
782 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
786 /////////////////////////////////////////////
787 // now we have a key, so we will add an entry
788 // (even if it's empty, as bibtex does)
790 // we now read the field = value pairs.
791 // all items must be separated by a comma. If
792 // it is missing the scanning of this entry is
793 // stopped and the next is searched.
797 docstring commaNewline;
799 BibTeXInfo keyvalmap(key, entryType);
801 bool readNext = removeWSAndComma(ifs);
803 while (ifs && readNext) {
806 if (!readTypeOrKey(name, ifs, from_ascii("="),
807 from_ascii("{}(),"), makeLowerCase) || !ifs)
810 // next char must be an equal sign
813 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
817 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
818 name << ", for key: " << key << "." << std::endl;
824 if (!readValue(value, ifs, strings)) {
825 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
826 name << ", for key: " << key << "." << std::endl;
830 keyvalmap[name] = value;
831 data += "\n\n" + value;
832 keylist.addFieldName(name);
833 readNext = removeWSAndComma(ifs);
837 keylist.addEntryType(entryType);
838 keyvalmap.setAllData(data);
839 keylist[key] = keyvalmap;
840 } //< else (citation entry)
842 } //< for loop over files
846 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
848 string texfile = changeExtension(to_utf8(filename), "bib");
849 // note that, if the filename can be found directly from the path,
850 // findtexfile will just return a FileName object for that path.
851 FileName file(findtexfile(texfile, "bib"));
853 file = FileName(makeAbsPath(texfile, buf.filePath()));
858 bool InsetBibtex::addDatabase(docstring const & db)
860 docstring bibfiles = getParam("bibfiles");
861 if (tokenPos(bibfiles, ',', db) != -1)
863 if (!bibfiles.empty())
865 setParam("bibfiles", bibfiles + db);
870 bool InsetBibtex::delDatabase(docstring const & db)
872 docstring bibfiles = getParam("bibfiles");
873 if (contains(bibfiles, db)) {
874 int const n = tokenPos(bibfiles, ',', db);
877 // this is not the first database
878 docstring tmp = ',' + bd;
879 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
881 // this is the first (or only) database
882 setParam("bibfiles", split(bibfiles, bd, ','));
890 void InsetBibtex::validate(LaTeXFeatures & features) const
892 if (features.bufferParams().use_bibtopic)
893 features.require("bibtopic");
897 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
899 return from_ascii("context-bibtex");