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(Buffer const & buf, InsetCommandParams const & p)
53 : InsetCommand(p, "bibtex")
55 Inset::setBuffer(const_cast<Buffer &>(buf));
56 buffer_->invalidateBibinfoCache();
60 InsetBibtex::~InsetBibtex()
63 buffer_->invalidateBibinfoCache();
67 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
69 static ParamInfo param_info_;
70 if (param_info_.empty()) {
71 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
72 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
73 param_info_.add("options", ParamInfo::LYX_INTERNAL);
79 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
87 case LFUN_INSET_MODIFY: {
88 InsetCommandParams p(BIBTEX_CODE);
90 if (!InsetCommand::string2params("bibtex",
91 to_utf8(cmd.argument()), p)) {
95 } catch (ExceptionMessage const & message) {
96 if (message.type_ == WarningException) {
97 Alert::warning(message.title_, message.details_);
105 buffer().updateBibfilesCache();
110 InsetCommand::doDispatch(cur, cmd);
116 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
117 FuncStatus & flag) const
119 switch (cmd.action) {
120 case LFUN_INSET_EDIT:
121 flag.setEnabled(true);
125 return InsetCommand::getStatus(cur, cmd, flag);
130 void InsetBibtex::editDatabases() const
132 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
134 if (bibfilelist.empty())
137 int nr_databases = bibfilelist.size();
138 if (nr_databases > 1) {
139 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
140 "If you proceed, all of them will be opened."),
141 convert<docstring>(nr_databases));
142 int const ret = Alert::prompt(_("Open Databases?"),
143 message, 0, 1, _("&Cancel"), _("&Proceed"));
149 vector<docstring>::const_iterator it = bibfilelist.begin();
150 vector<docstring>::const_iterator en = bibfilelist.end();
151 for (; it != en; ++it) {
152 FileName bibfile = getBibTeXPath(*it, buffer());
153 formats.edit(buffer(), bibfile,
154 formats.getFormatFromFile(bibfile));
159 docstring InsetBibtex::screenLabel() const
161 return _("BibTeX Generated Bibliography");
165 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
167 docstring item = from_ascii("* ");
168 docstring tip = _("Databases:") + "\n";
169 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
171 if (bibfilelist.empty()) {
175 vector<docstring>::const_iterator it = bibfilelist.begin();
176 vector<docstring>::const_iterator en = bibfilelist.end();
177 for (; it != en; ++it) {
185 docstring style = getParam("options"); // maybe empty! and with bibtotoc
186 docstring bibtotoc = from_ascii("bibtotoc");
187 if (prefixIs(style, bibtotoc)) {
189 if (contains(style, char_type(',')))
190 style = split(style, bibtotoc, char_type(','));
193 tip += _("Style File:") +"\n";
200 tip += "\n" + _("Lists:") + " ";
201 docstring btprint = getParam("btprint");
202 if (btprint == "btPrintAll")
203 tip += _("all references");
204 else if (btprint == "btPrintNotCited")
205 tip += _("all uncited references");
207 tip += _("all cited references");
211 tip += _("included in TOC");
218 static string normalizeName(Buffer const & buffer,
219 OutputParams const & runparams, string const & name, string const & ext)
221 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
222 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
228 return to_utf8(makeRelPath(from_utf8(fname),
229 from_utf8(buffer.masterBuffer()->filePath())));
233 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
235 // the sequence of the commands:
236 // 1. \bibliographystyle{style}
237 // 2. \addcontentsline{...} - if option bibtotoc set
238 // 3. \bibliography{database}
239 // and with bibtopic:
240 // 1. \bibliographystyle{style}
241 // 2. \begin{btSect}{database}
242 // 3. \btPrint{Cited|NotCited|All}
246 // If we are processing the LaTeX file in a temp directory then
247 // copy the .bib databases to this temp directory, mangling their
248 // names in the process. Store this mangled name in the list of
250 // (We need to do all this because BibTeX *really*, *really*
251 // can't handle "files with spaces" and Windows users tend to
252 // use such filenames.)
253 // Otherwise, store the (maybe absolute) path to the original,
254 // unmangled database name.
255 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
256 vector<docstring>::const_iterator it = bibfilelist.begin();
257 vector<docstring>::const_iterator en = bibfilelist.end();
258 odocstringstream dbs;
261 for (; it != en; ++it) {
262 string utf8input = to_utf8(*it);
264 normalizeName(buffer(), runparams, utf8input, ".bib");
265 FileName const try_in_file =
266 makeAbsPath(database + ".bib", buffer().filePath());
267 bool const not_from_texmf = try_in_file.isReadableFile();
269 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
271 // mangledFilename() needs the extension
272 DocFileName const in_file = DocFileName(try_in_file);
273 database = removeExtension(in_file.mangledFilename());
274 FileName const out_file = makeAbsPath(database + ".bib",
275 buffer().masterBuffer()->temppath());
277 bool const success = in_file.copyTo(out_file);
279 lyxerr << "Failed to copy '" << in_file
280 << "' to '" << out_file << "'"
283 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
284 !isValidLaTeXFilename(database)) {
285 frontend::Alert::warning(_("Invalid filename"),
286 _("The following filename is likely to cause trouble "
287 "when running the exported file through LaTeX: ") +
288 from_utf8(database));
296 dbs << from_utf8(latex_path(database));
298 docstring const db_out = dbs.str();
300 // Post this warning only once.
301 static bool warned_about_spaces = false;
302 if (!warned_about_spaces &&
303 runparams.nice && db_out.find(' ') != docstring::npos) {
304 warned_about_spaces = true;
305 Alert::warning(_("Export Warning!"),
306 _("There are spaces in the paths to your BibTeX databases.\n"
307 "BibTeX will be unable to find them."));
310 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
312 if (prefixIs(style, "bibtotoc")) {
313 bibtotoc = "bibtotoc";
314 if (contains(style, ','))
315 style = split(style, bibtotoc, ',');
321 if (!style.empty()) {
322 string base = normalizeName(buffer(), runparams, style, ".bst");
323 FileName const try_in_file =
324 makeAbsPath(base + ".bst", buffer().filePath());
325 bool const not_from_texmf = try_in_file.isReadableFile();
326 // If this style does not come from texmf and we are not
327 // exporting to .tex copy it to the tmp directory.
328 // This prevents problems with spaces and 8bit charcaters
330 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
332 // use new style name
333 DocFileName const in_file = DocFileName(try_in_file);
334 base = removeExtension(in_file.mangledFilename());
335 FileName const out_file = makeAbsPath(base + ".bst",
336 buffer().masterBuffer()->temppath());
337 bool const success = in_file.copyTo(out_file);
339 lyxerr << "Failed to copy '" << in_file
340 << "' to '" << out_file << "'"
345 os << "\\bibliographystyle{"
346 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
351 // Post this warning only once.
352 static bool warned_about_bst_spaces = false;
353 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
354 warned_about_bst_spaces = true;
355 Alert::warning(_("Export Warning!"),
356 _("There are spaces in the path to your BibTeX style file.\n"
357 "BibTeX will be unable to find it."));
360 if (!db_out.empty() && buffer().params().use_bibtopic) {
361 os << "\\begin{btSect}{" << db_out << "}\n";
362 docstring btprint = getParam("btprint");
365 btprint = from_ascii("btPrintCited");
366 os << "\\" << btprint << "\n"
367 << "\\end{btSect}\n";
372 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
373 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
374 if (buffer().params().sides == OneSide) {
379 os << "\\cleardoublepage";
381 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
382 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
383 os << "\\addcontentsline{toc}{section}{\\refname}";
386 if (!db_out.empty() && !buffer().params().use_bibtopic) {
387 docstring btprint = getParam("btprint");
388 if (btprint == "btPrintAll") {
389 os << "\\nocite{*}\n";
392 os << "\\bibliography{" << db_out << "}\n";
400 support::FileNameList InsetBibtex::getBibFiles() const
402 FileName path(buffer().filePath());
403 support::PathChanger p(path);
405 support::FileNameList vec;
407 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
408 vector<docstring>::const_iterator it = bibfilelist.begin();
409 vector<docstring>::const_iterator en = bibfilelist.end();
410 for (; it != en; ++it) {
411 FileName const file = getBibTeXPath(*it, buffer());
416 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
425 // methods for parsing bibtex files
427 typedef map<docstring, docstring> VarMap;
429 /// remove whitespace characters, optionally a single comma,
430 /// and further whitespace characters from the stream.
431 /// @return true if a comma was found, false otherwise
433 bool removeWSAndComma(ifdocstream & ifs) {
442 } while (ifs && isSpace(ch));
455 } while (ifs && isSpace(ch));
470 /// remove whitespace characters, read characer sequence
471 /// not containing whitespace characters or characters in
472 /// delimChars, and remove further whitespace characters.
474 /// @return true if a string of length > 0 could be read.
476 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
477 docstring const & delimChars, docstring const &illegalChars,
490 } while (ifs && isSpace(ch));
496 bool legalChar = true;
497 while (ifs && !isSpace(ch) &&
498 delimChars.find(ch) == docstring::npos &&
499 (legalChar = (illegalChars.find(ch) == docstring::npos))
502 if (chCase == makeLowerCase)
503 val += lowercase(ch);
515 while (ifs && isSpace(ch)) {
523 return val.length() > 0;
526 /// read subsequent bibtex values that are delimited with a #-character.
527 /// Concatenate all parts and replace names with the associated string in
528 /// the variable strings.
529 /// @return true if reading was successfull (all single parts were delimited
531 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
544 } while (ifs && isSpace(ch));
549 // check for field type
552 // read integer value
556 } while (ifs && isDigit(ch));
561 } else if (ch == '"' || ch == '{') {
563 char_type delim = ch == '"' ? '"': '}';
568 } while (ifs && isSpace(ch));
573 // We now have the first non-whitespace character
574 // We'll collapse adjacent whitespace.
575 bool lastWasWhiteSpace = false;
577 // inside this delimited text braces must match.
578 // Thus we can have a closing delimiter only
579 // when nestLevel == 0
582 while (ifs && (nestLevel > 0 || ch != delim)) {
584 lastWasWhiteSpace = true;
588 // We output the space only after we stop getting
589 // whitespace so as not to output any whitespace
590 // at the end of the value.
591 if (lastWasWhiteSpace) {
592 lastWasWhiteSpace = false;
598 // update nesting level
605 if (nestLevel < 0) return false;
622 // reading a string name
625 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
626 strName += lowercase(ch);
633 // replace the string with its assigned value or
634 // discard it if it's not assigned
635 if (strName.length()) {
636 VarMap::const_iterator pos = strings.find(strName);
637 if (pos != strings.end()) {
644 while (ifs && isSpace(ch)) {
651 // continue reading next value on concatenate with '#'
661 // This method returns a comma separated list of Bibtex entries
662 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
663 InsetIterator const & /*di*/) const
665 // This bibtex parser is a first step to parse bibtex files
668 // - it reads the whole bibtex entry and does a syntax check
669 // (matching delimiters, missing commas,...
670 // - it recovers from errors starting with the next @-character
671 // - it reads @string definitions and replaces them in the
673 // - it accepts more characters in keys or value names than
676 // Officially bibtex does only support ASCII, but in practice
677 // you can use the encoding of the main document as long as
678 // some elements like keys and names are pure ASCII. Therefore
679 // we convert the file from the buffer encoding.
680 // We don't restrict keys to ASCII in LyX, since our own
681 // InsetBibitem can generate non-ASCII keys, and nonstandard
682 // 8bit clean bibtex forks exist.
683 support::FileNameList const files = getBibFiles();
684 support::FileNameList::const_iterator it = files.begin();
685 support::FileNameList::const_iterator en = files.end();
686 for (; it != en; ++ it) {
687 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
688 ios_base::in, buffer().params().encoding().iconvName());
704 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
705 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading entry type." << std::endl;
710 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
714 if (entryType == from_ascii("comment")) {
715 ifs.ignore(numeric_limits<int>::max(), '\n');
721 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
725 if ((ch != '(') && (ch != '{')) {
726 lyxerr << "InsetBibtex::fillWithBibKeys: Invalid entry delimiter." << std::endl;
732 if (entryType == from_ascii("string")) {
734 // read string and add it to the strings map
735 // (or replace it's old value)
739 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
740 lyxerr << "InsetBibtex::fillWithBibKeys: Error reading string name." << std::endl;
745 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
749 // next char must be an equal sign
751 if (!ifs || ch != '=') {
752 lyxerr << "InsetBibtex::fillWithBibKeys: No `=' after string name: " <<
753 name << "." << std::endl;
757 if (!readValue(value, ifs, strings)) {
758 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for string: " <<
759 name << "." << std::endl;
763 strings[name] = value;
765 } else if (entryType == from_ascii("preamble")) {
767 // preamble definitions are discarded.
768 // can they be of any use in lyx?
771 if (!readValue(value, ifs, strings)) {
772 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read preamble value." << std::endl;
778 // Citation entry. Try to read the key.
781 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
782 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read key for entry type:" <<
783 entryType << "." << std::endl;
788 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
792 /////////////////////////////////////////////
793 // now we have a key, so we will add an entry
794 // (even if it's empty, as bibtex does)
796 // we now read the field = value pairs.
797 // all items must be separated by a comma. If
798 // it is missing the scanning of this entry is
799 // stopped and the next is searched.
803 docstring commaNewline;
805 BibTeXInfo keyvalmap(key, entryType);
807 bool readNext = removeWSAndComma(ifs);
809 while (ifs && readNext) {
812 if (!readTypeOrKey(name, ifs, from_ascii("="),
813 from_ascii("{}(),"), makeLowerCase) || !ifs)
816 // next char must be an equal sign
819 lyxerr << "InsetBibtex::fillWithBibKeys: Unexpected end of file." << std::endl;
823 lyxerr << "InsetBibtex::fillWithBibKeys: Missing `=' after field name: " <<
824 name << ", for key: " << key << "." << std::endl;
830 if (!readValue(value, ifs, strings)) {
831 lyxerr << "InsetBibtex::fillWithBibKeys: Unable to read value for field: " <<
832 name << ", for key: " << key << "." << std::endl;
836 keyvalmap[name] = value;
837 data += "\n\n" + value;
838 keylist.addFieldName(name);
839 readNext = removeWSAndComma(ifs);
843 keylist.addEntryType(entryType);
844 keyvalmap.setAllData(data);
845 keylist[key] = keyvalmap;
846 } //< else (citation entry)
848 } //< for loop over files
852 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
854 string texfile = changeExtension(to_utf8(filename), "bib");
855 // note that, if the filename can be found directly from the path,
856 // findtexfile will just return a FileName object for that path.
857 FileName file(findtexfile(texfile, "bib"));
859 file = FileName(makeAbsPath(texfile, buf.filePath()));
864 bool InsetBibtex::addDatabase(docstring const & db)
866 docstring bibfiles = getParam("bibfiles");
867 if (tokenPos(bibfiles, ',', db) != -1)
869 if (!bibfiles.empty())
871 setParam("bibfiles", bibfiles + db);
876 bool InsetBibtex::delDatabase(docstring const & db)
878 docstring bibfiles = getParam("bibfiles");
879 if (contains(bibfiles, db)) {
880 int const n = tokenPos(bibfiles, ',', db);
883 // this is not the first database
884 docstring tmp = ',' + bd;
885 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
887 // this is the first (or only) database
888 setParam("bibfiles", split(bibfiles, bd, ','));
896 void InsetBibtex::validate(LaTeXFeatures & features) const
898 if (features.bufferParams().use_bibtopic)
899 features.require("bibtopic");
903 int InsetBibtex::xhtml(odocstream &, OutputParams const &) const
905 //Toc const & toc = buffer().tocBackend().toc("citation");
910 docstring InsetBibtex::contextMenu(BufferView const &, int, int) const
912 return from_ascii("context-bibtex");