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"
20 #include "FuncRequest.h"
21 #include "LaTeXFeatures.h"
22 #include "MetricsInfo.h"
23 #include "OutputParams.h"
24 #include "TextClass.h"
26 #include "frontends/alert.h"
28 #include "support/debug.h"
29 #include "support/docstream.h"
30 #include "support/ExceptionMessage.h"
31 #include "support/filetools.h"
32 #include "support/gettext.h"
33 #include "support/lstrings.h"
34 #include "support/os.h"
35 #include "support/Path.h"
36 #include "support/textutils.h"
41 using namespace lyx::support;
45 namespace Alert = frontend::Alert;
46 namespace os = support::os;
49 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
50 : InsetCommand(p, "bibtex")
54 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
56 static ParamInfo param_info_;
57 if (param_info_.empty()) {
58 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
59 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
60 param_info_.add("options", ParamInfo::LYX_INTERNAL);
66 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
70 case LFUN_INSET_MODIFY: {
71 InsetCommandParams p(BIBTEX_CODE);
73 if (!InsetCommand::string2params("bibtex",
74 to_utf8(cmd.argument()), p)) {
78 } catch (ExceptionMessage const & message) {
79 if (message.type_ == WarningException) {
80 Alert::warning(message.title_, message.details_);
88 buffer().updateBibfilesCache();
93 InsetCommand::doDispatch(cur, cmd);
99 docstring InsetBibtex::screenLabel() const
101 return _("BibTeX Generated Bibliography");
105 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
107 docstring item = from_ascii("* ");
108 docstring tip = _("Databases:\n");
109 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
111 if (bibfilelist.empty()) {
115 vector<docstring>::const_iterator it = bibfilelist.begin();
116 vector<docstring>::const_iterator en = bibfilelist.end();
117 for (; it != en; ++it) {
124 docstring style = getParam("options"); // maybe empty! and with bibtotoc
125 docstring bibtotoc = from_ascii("bibtotoc");
126 if (prefixIs(style, bibtotoc)) {
127 if (contains(style, char_type(',')))
128 style = split(style, bibtotoc, char_type(','));
131 tip += _("Style File:\n");
142 static string normalizeName(Buffer const & buffer,
143 OutputParams const & runparams, string const & name, string const & ext)
145 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
146 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
152 return to_utf8(makeRelPath(from_utf8(fname),
153 from_utf8(buffer.masterBuffer()->filePath())));
157 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
159 // the sequence of the commands:
160 // 1. \bibliographystyle{style}
161 // 2. \addcontentsline{...} - if option bibtotoc set
162 // 3. \bibliography{database}
163 // and with bibtopic:
164 // 1. \bibliographystyle{style}
165 // 2. \begin{btSect}{database}
166 // 3. \btPrint{Cited|NotCited|All}
170 // If we are processing the LaTeX file in a temp directory then
171 // copy the .bib databases to this temp directory, mangling their
172 // names in the process. Store this mangled name in the list of
174 // (We need to do all this because BibTeX *really*, *really*
175 // can't handle "files with spaces" and Windows users tend to
176 // use such filenames.)
177 // Otherwise, store the (maybe absolute) path to the original,
178 // unmangled database name.
179 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
180 vector<docstring>::const_iterator it = bibfilelist.begin();
181 vector<docstring>::const_iterator en = bibfilelist.end();
182 odocstringstream dbs;
185 for (; it != en; ++it) {
186 string utf8input = to_utf8(*it);
188 normalizeName(buffer(), runparams, utf8input, ".bib");
189 FileName const try_in_file =
190 makeAbsPath(database + ".bib", buffer().filePath());
191 bool const not_from_texmf = try_in_file.isReadableFile();
193 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
196 // mangledFilename() needs the extension
197 DocFileName const in_file = DocFileName(try_in_file);
198 database = removeExtension(in_file.mangledFilename());
199 FileName const out_file = makeAbsPath(database + ".bib",
200 buffer().masterBuffer()->temppath());
202 bool const success = in_file.copyTo(out_file);
204 lyxerr << "Failed to copy '" << in_file
205 << "' to '" << out_file << "'"
208 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
209 !isValidLaTeXFilename(database)) {
210 frontend::Alert::warning(_("Invalid filename"),
211 _("The following filename is likely to cause trouble "
212 "when running the exported file through LaTeX: ") +
213 from_utf8(database));
221 dbs << from_utf8(latex_path(database));
223 docstring const db_out = dbs.str();
225 // Post this warning only once.
226 static bool warned_about_spaces = false;
227 if (!warned_about_spaces &&
228 runparams.nice && db_out.find(' ') != docstring::npos) {
229 warned_about_spaces = true;
231 Alert::warning(_("Export Warning!"),
232 _("There are spaces in the paths to your BibTeX databases.\n"
233 "BibTeX will be unable to find them."));
236 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
238 if (prefixIs(style, "bibtotoc")) {
239 bibtotoc = "bibtotoc";
240 if (contains(style, ','))
241 style = split(style, bibtotoc, ',');
248 if (!style.empty()) {
249 string base = normalizeName(buffer(), runparams, style, ".bst");
250 FileName const try_in_file =
251 makeAbsPath(base + ".bst", buffer().filePath());
252 bool const not_from_texmf = try_in_file.isReadableFile();
253 // If this style does not come from texmf and we are not
254 // exporting to .tex copy it to the tmp directory.
255 // This prevents problems with spaces and 8bit charcaters
257 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
259 // use new style name
260 DocFileName const in_file = DocFileName(try_in_file);
261 base = removeExtension(in_file.mangledFilename());
262 FileName const out_file = makeAbsPath(base + ".bst",
263 buffer().masterBuffer()->temppath());
264 bool const success = in_file.copyTo(out_file);
266 lyxerr << "Failed to copy '" << in_file
267 << "' to '" << out_file << "'"
272 os << "\\bibliographystyle{"
273 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
278 // Post this warning only once.
279 static bool warned_about_bst_spaces = false;
280 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
281 warned_about_bst_spaces = true;
282 Alert::warning(_("Export Warning!"),
283 _("There are spaces in the path to your BibTeX style file.\n"
284 "BibTeX will be unable to find it."));
287 if (!db_out.empty() && buffer().params().use_bibtopic) {
288 os << "\\begin{btSect}{" << db_out << "}\n";
289 docstring btprint = getParam("btprint");
292 btprint = from_ascii("btPrintCited");
293 os << "\\" << btprint << "\n"
294 << "\\end{btSect}\n";
299 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
300 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
301 if (buffer().params().sides == OneSide) {
306 os << "\\cleardoublepage";
308 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
309 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
310 os << "\\addcontentsline{toc}{section}{\\refname}";
313 if (!db_out.empty() && !buffer().params().use_bibtopic) {
314 docstring btprint = getParam("btprint");
315 if (btprint == "btPrintAll") {
316 os << "\\nocite{*}\n";
319 os << "\\bibliography{" << db_out << "}\n";
327 support::FileNameList InsetBibtex::getBibFiles() const
329 FileName path(buffer().filePath());
330 support::PathChanger p(path);
332 support::FileNameList vec;
334 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
335 vector<docstring>::const_iterator it = bibfilelist.begin();
336 vector<docstring>::const_iterator en = bibfilelist.end();
337 for (; it != en; ++it) {
338 FileName const file =
339 findtexfile(changeExtension(to_utf8(*it), "bib"), "bib");
341 // If we didn't find a matching file name just fail silently
352 // methods for parsing bibtex files
354 typedef map<docstring, docstring> VarMap;
356 /// remove whitespace characters, optionally a single comma,
357 /// and further whitespace characters from the stream.
358 /// @return true if a comma was found, false otherwise
360 bool removeWSAndComma(idocfstream & ifs) {
369 } while (ifs && isSpace(ch));
382 } while (ifs && isSpace(ch));
397 /// remove whitespace characters, read characer sequence
398 /// not containing whitespace characters or characters in
399 /// delimChars, and remove further whitespace characters.
401 /// @return true if a string of length > 0 could be read.
403 bool readTypeOrKey(docstring & val, idocfstream & ifs,
404 docstring const & delimChars, docstring const &illegalChars,
417 } while (ifs && isSpace(ch));
423 bool legalChar = true;
424 while (ifs && !isSpace(ch) &&
425 delimChars.find(ch) == docstring::npos &&
426 (legalChar = (illegalChars.find(ch) == docstring::npos))
429 if (chCase == makeLowerCase)
430 val += lowercase(ch);
442 while (ifs && isSpace(ch)) {
450 return val.length() > 0;
453 /// read subsequent bibtex values that are delimited with a #-character.
454 /// Concatenate all parts and replace names with the associated string in
455 /// the variable strings.
456 /// @return true if reading was successfull (all single parts were delimited
458 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
471 } while (ifs && isSpace(ch));
476 // check for field type
479 // read integer value
483 } while (ifs && isDigit(ch));
488 } else if (ch == '"' || ch == '{') {
490 char_type delim = ch == '"' ? '"': '}';
495 } while (ifs && isSpace(ch));
500 //We now have the first non-whitespace character
501 //We'll collapse adjacent whitespace.
502 bool lastWasWhiteSpace = false;
504 // inside this delimited text braces must match.
505 // Thus we can have a closing delimiter only
506 // when nestLevel == 0
509 while (ifs && (nestLevel > 0 || ch != delim)) {
511 lastWasWhiteSpace = true;
515 //We output the space only after we stop getting
516 //whitespace so as not to output any whitespace
517 //at the end of the value.
518 if (lastWasWhiteSpace) {
519 lastWasWhiteSpace = false;
525 // update nesting level
532 if (nestLevel < 0) return false;
549 // reading a string name
552 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
553 strName += lowercase(ch);
560 // replace the string with its assigned value or
561 // discard it if it's not assigned
562 if (strName.length()) {
563 VarMap::const_iterator pos = strings.find(strName);
564 if (pos != strings.end()) {
571 while (ifs && isSpace(ch)) {
578 // continue reading next value on concatenate with '#'
588 // This method returns a comma separated list of Bibtex entries
589 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
590 InsetIterator const & /*di*/) const
592 // This bibtex parser is a first step to parse bibtex files
595 // - it reads the whole bibtex entry and does a syntax check
596 // (matching delimiters, missing commas,...
597 // - it recovers from errors starting with the next @-character
598 // - it reads @string definitions and replaces them in the
600 // - it accepts more characters in keys or value names than
603 // Officially bibtex does only support ASCII, but in practice
604 // you can use the encoding of the main document as long as
605 // some elements like keys and names are pure ASCII. Therefore
606 // we convert the file from the buffer encoding.
607 // We don't restrict keys to ASCII in LyX, since our own
608 // InsetBibitem can generate non-ASCII keys, and nonstandard
609 // 8bit clean bibtex forks exist.
610 support::FileNameList const files = getBibFiles();
611 support::FileNameList::const_iterator it = files.begin();
612 support::FileNameList::const_iterator en = files.end();
613 for (; it != en; ++ it) {
614 idocfstream ifs(it->toFilesystemEncoding().c_str(),
615 ios_base::in, buffer().params().encoding().iconvName());
631 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
632 docstring(), makeLowerCase) || !ifs)
635 if (entryType == from_ascii("comment")) {
637 ifs.ignore(numeric_limits<int>::max(), '\n');
645 if ((ch != '(') && (ch != '{')) {
646 // invalid entry delimiter
652 if (entryType == from_ascii("string")) {
654 // read string and add it to the strings map
655 // (or replace it's old value)
659 if (!readTypeOrKey(name, ifs, from_ascii("="),
660 from_ascii("#{}(),"), makeLowerCase) || !ifs)
663 // next char must be an equal sign
665 if (!ifs || ch != '=')
668 if (!readValue(value, ifs, strings))
671 strings[name] = value;
673 } else if (entryType == from_ascii("preamble")) {
675 // preamble definitions are discarded.
676 // can they be of any use in lyx?
679 if (!readValue(value, ifs, strings))
684 // Citation entry. Try to read the key.
687 if (!readTypeOrKey(key, ifs, from_ascii(","),
688 from_ascii("}"), keepCase) || !ifs)
691 /////////////////////////////////////////////
692 // now we have a key, so we will add an entry
693 // (even if it's empty, as bibtex does)
695 // we now read the field = value pairs.
696 // all items must be separated by a comma. If
697 // it is missing the scanning of this entry is
698 // stopped and the next is searched.
702 docstring commaNewline;
704 BibTeXInfo keyvalmap(key, entryType);
706 bool readNext = removeWSAndComma(ifs);
708 while (ifs && readNext) {
711 if (!readTypeOrKey(name, ifs, from_ascii("="),
712 from_ascii("{}(),"), makeLowerCase) || !ifs)
715 // next char must be an equal sign
725 if (!readValue(value, ifs, strings))
728 keyvalmap[name] = value;
729 data += "\n\n" + value;
730 keylist.addFieldName(name);
731 readNext = removeWSAndComma(ifs);
735 keylist.addEntryType(entryType);
736 keyvalmap.setAllData(data);
737 keylist[key] = keyvalmap;
740 } //< for loop over files
744 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
746 string texfile = changeExtension(to_utf8(filename), "bib");
747 // note that, if the filename can be found directly from the path,
748 // findtexfile will just return a FileName object for that path.
749 FileName file(findtexfile(texfile, "bib"));
751 file = FileName(makeAbsPath(texfile, buf.filePath()));
756 bool InsetBibtex::addDatabase(docstring const & db)
758 docstring bibfiles = getParam("bibfiles");
759 if (tokenPos(bibfiles, ',', db) != -1)
761 if (!bibfiles.empty())
763 setParam("bibfiles", bibfiles + db);
768 bool InsetBibtex::delDatabase(docstring const & db)
770 docstring bibfiles = getParam("bibfiles");
771 if (contains(bibfiles, db)) {
772 int const n = tokenPos(bibfiles, ',', db);
775 // this is not the first database
776 docstring tmp = ',' + bd;
777 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
779 // this is the first (or only) database
780 setParam("bibfiles", split(bibfiles, bd, ','));
788 void InsetBibtex::validate(LaTeXFeatures & features) const
790 if (features.bufferParams().use_bibtopic)
791 features.require("bibtopic");