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:
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 += _("\nLists: ");
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");
407 // If we didn't find a matching file name just fail silently
418 // methods for parsing bibtex files
420 typedef map<docstring, docstring> VarMap;
422 /// remove whitespace characters, optionally a single comma,
423 /// and further whitespace characters from the stream.
424 /// @return true if a comma was found, false otherwise
426 bool removeWSAndComma(idocfstream & ifs) {
435 } while (ifs && isSpace(ch));
448 } while (ifs && isSpace(ch));
463 /// remove whitespace characters, read characer sequence
464 /// not containing whitespace characters or characters in
465 /// delimChars, and remove further whitespace characters.
467 /// @return true if a string of length > 0 could be read.
469 bool readTypeOrKey(docstring & val, idocfstream & ifs,
470 docstring const & delimChars, docstring const &illegalChars,
483 } while (ifs && isSpace(ch));
489 bool legalChar = true;
490 while (ifs && !isSpace(ch) &&
491 delimChars.find(ch) == docstring::npos &&
492 (legalChar = (illegalChars.find(ch) == docstring::npos))
495 if (chCase == makeLowerCase)
496 val += lowercase(ch);
508 while (ifs && isSpace(ch)) {
516 return val.length() > 0;
519 /// read subsequent bibtex values that are delimited with a #-character.
520 /// Concatenate all parts and replace names with the associated string in
521 /// the variable strings.
522 /// @return true if reading was successfull (all single parts were delimited
524 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
537 } while (ifs && isSpace(ch));
542 // check for field type
545 // read integer value
549 } while (ifs && isDigit(ch));
554 } else if (ch == '"' || ch == '{') {
556 char_type delim = ch == '"' ? '"': '}';
561 } while (ifs && isSpace(ch));
566 // We now have the first non-whitespace character
567 // We'll collapse adjacent whitespace.
568 bool lastWasWhiteSpace = false;
570 // inside this delimited text braces must match.
571 // Thus we can have a closing delimiter only
572 // when nestLevel == 0
575 while (ifs && (nestLevel > 0 || ch != delim)) {
577 lastWasWhiteSpace = true;
581 // We output the space only after we stop getting
582 // whitespace so as not to output any whitespace
583 // at the end of the value.
584 if (lastWasWhiteSpace) {
585 lastWasWhiteSpace = false;
591 // update nesting level
598 if (nestLevel < 0) return false;
615 // reading a string name
618 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
619 strName += lowercase(ch);
626 // replace the string with its assigned value or
627 // discard it if it's not assigned
628 if (strName.length()) {
629 VarMap::const_iterator pos = strings.find(strName);
630 if (pos != strings.end()) {
637 while (ifs && isSpace(ch)) {
644 // continue reading next value on concatenate with '#'
654 // This method returns a comma separated list of Bibtex entries
655 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
656 InsetIterator const & /*di*/) const
658 // This bibtex parser is a first step to parse bibtex files
661 // - it reads the whole bibtex entry and does a syntax check
662 // (matching delimiters, missing commas,...
663 // - it recovers from errors starting with the next @-character
664 // - it reads @string definitions and replaces them in the
666 // - it accepts more characters in keys or value names than
669 // Officially bibtex does only support ASCII, but in practice
670 // you can use the encoding of the main document as long as
671 // some elements like keys and names are pure ASCII. Therefore
672 // we convert the file from the buffer encoding.
673 // We don't restrict keys to ASCII in LyX, since our own
674 // InsetBibitem can generate non-ASCII keys, and nonstandard
675 // 8bit clean bibtex forks exist.
676 support::FileNameList const files = getBibFiles();
677 support::FileNameList::const_iterator it = files.begin();
678 support::FileNameList::const_iterator en = files.end();
679 for (; it != en; ++ it) {
680 idocfstream ifs(it->toFilesystemEncoding().c_str(),
681 ios_base::in, buffer().params().encoding().iconvName());
698 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
702 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
703 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
707 if (entryType == from_ascii("comment")) {
708 ifs.ignore(numeric_limits<int>::max(), '\n');
714 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
718 if ((ch != '(') && (ch != '{')) {
719 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
725 if (entryType == from_ascii("string")) {
727 // read string and add it to the strings map
728 // (or replace it's old value)
733 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
737 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
738 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
742 // next char must be an equal sign
744 if (!ifs || ch != '=') {
745 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
746 name << "." << std::endl;
750 if (!readValue(value, ifs, strings)) {
751 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
752 name << "." << std::endl;
756 strings[name] = value;
758 } else if (entryType == from_ascii("preamble")) {
760 // preamble definitions are discarded.
761 // can they be of any use in lyx?
764 if (!readValue(value, ifs, strings)) {
765 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
771 // Citation entry. Try to read the key.
775 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
779 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
780 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
781 entryType << "." << std::endl;
785 /////////////////////////////////////////////
786 // now we have a key, so we will add an entry
787 // (even if it's empty, as bibtex does)
789 // we now read the field = value pairs.
790 // all items must be separated by a comma. If
791 // it is missing the scanning of this entry is
792 // stopped and the next is searched.
796 docstring commaNewline;
798 BibTeXInfo keyvalmap(key, entryType);
800 bool readNext = removeWSAndComma(ifs);
802 while (ifs && readNext) {
805 if (!readTypeOrKey(name, ifs, from_ascii("="),
806 from_ascii("{}(),"), makeLowerCase) || !ifs)
809 // next char must be an equal sign
812 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
816 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
817 name << ", for key: " << key << "." << std::endl;
823 if (!readValue(value, ifs, strings)) {
824 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
825 name << ", for key: " << key << "." << std::endl;
829 keyvalmap[name] = value;
830 data += "\n\n" + value;
831 keylist.addFieldName(name);
832 readNext = removeWSAndComma(ifs);
836 keylist.addEntryType(entryType);
837 keyvalmap.setAllData(data);
838 keylist[key] = keyvalmap;
839 } //< else (citation entry)
841 } //< for loop over files
845 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
847 string texfile = changeExtension(to_utf8(filename), "bib");
848 // note that, if the filename can be found directly from the path,
849 // findtexfile will just return a FileName object for that path.
850 FileName file(findtexfile(texfile, "bib"));
852 file = FileName(makeAbsPath(texfile, buf.filePath()));
857 bool InsetBibtex::addDatabase(docstring const & db)
859 docstring bibfiles = getParam("bibfiles");
860 if (tokenPos(bibfiles, ',', db) != -1)
862 if (!bibfiles.empty())
864 setParam("bibfiles", bibfiles + db);
869 bool InsetBibtex::delDatabase(docstring const & db)
871 docstring bibfiles = getParam("bibfiles");
872 if (contains(bibfiles, db)) {
873 int const n = tokenPos(bibfiles, ',', db);
876 // this is not the first database
877 docstring tmp = ',' + bd;
878 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
880 // this is the first (or only) database
881 setParam("bibfiles", split(bibfiles, bd, ','));
889 void InsetBibtex::validate(LaTeXFeatures & features) const
891 if (features.bufferParams().use_bibtopic)
892 features.require("bibtopic");
896 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
898 return from_ascii("context-bibtex");