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) {
125 docstring style = getParam("options"); // maybe empty! and with bibtotoc
126 docstring bibtotoc = from_ascii("bibtotoc");
127 if (prefixIs(style, bibtotoc)) {
129 if (contains(style, char_type(',')))
130 style = split(style, bibtotoc, char_type(','));
133 tip += _("Style File:\n");
140 tip += _("\nLists: ");
141 docstring btprint = getParam("btprint");
142 if (btprint == "btPrintAll")
143 tip += _("all references");
144 else if (btprint == "btPrintNotCited")
145 tip += _("all uncited references");
147 tip += _("all cited references");
151 tip += _("included in TOC");
158 static string normalizeName(Buffer const & buffer,
159 OutputParams const & runparams, string const & name, string const & ext)
161 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
162 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
168 return to_utf8(makeRelPath(from_utf8(fname),
169 from_utf8(buffer.masterBuffer()->filePath())));
173 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
175 // the sequence of the commands:
176 // 1. \bibliographystyle{style}
177 // 2. \addcontentsline{...} - if option bibtotoc set
178 // 3. \bibliography{database}
179 // and with bibtopic:
180 // 1. \bibliographystyle{style}
181 // 2. \begin{btSect}{database}
182 // 3. \btPrint{Cited|NotCited|All}
186 // If we are processing the LaTeX file in a temp directory then
187 // copy the .bib databases to this temp directory, mangling their
188 // names in the process. Store this mangled name in the list of
190 // (We need to do all this because BibTeX *really*, *really*
191 // can't handle "files with spaces" and Windows users tend to
192 // use such filenames.)
193 // Otherwise, store the (maybe absolute) path to the original,
194 // unmangled database name.
195 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
196 vector<docstring>::const_iterator it = bibfilelist.begin();
197 vector<docstring>::const_iterator en = bibfilelist.end();
198 odocstringstream dbs;
201 for (; it != en; ++it) {
202 string utf8input = to_utf8(*it);
204 normalizeName(buffer(), runparams, utf8input, ".bib");
205 FileName const try_in_file =
206 makeAbsPath(database + ".bib", buffer().filePath());
207 bool const not_from_texmf = try_in_file.isReadableFile();
209 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
212 // mangledFilename() needs the extension
213 DocFileName const in_file = DocFileName(try_in_file);
214 database = removeExtension(in_file.mangledFilename());
215 FileName const out_file = makeAbsPath(database + ".bib",
216 buffer().masterBuffer()->temppath());
218 bool const success = in_file.copyTo(out_file);
220 lyxerr << "Failed to copy '" << in_file
221 << "' to '" << out_file << "'"
224 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
225 !isValidLaTeXFilename(database)) {
226 frontend::Alert::warning(_("Invalid filename"),
227 _("The following filename is likely to cause trouble "
228 "when running the exported file through LaTeX: ") +
229 from_utf8(database));
237 dbs << from_utf8(latex_path(database));
239 docstring const db_out = dbs.str();
241 // Post this warning only once.
242 static bool warned_about_spaces = false;
243 if (!warned_about_spaces &&
244 runparams.nice && db_out.find(' ') != docstring::npos) {
245 warned_about_spaces = true;
247 Alert::warning(_("Export Warning!"),
248 _("There are spaces in the paths to your BibTeX databases.\n"
249 "BibTeX will be unable to find them."));
252 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
254 if (prefixIs(style, "bibtotoc")) {
255 bibtotoc = "bibtotoc";
256 if (contains(style, ','))
257 style = split(style, bibtotoc, ',');
264 if (!style.empty()) {
265 string base = normalizeName(buffer(), runparams, style, ".bst");
266 FileName const try_in_file =
267 makeAbsPath(base + ".bst", buffer().filePath());
268 bool const not_from_texmf = try_in_file.isReadableFile();
269 // If this style does not come from texmf and we are not
270 // exporting to .tex copy it to the tmp directory.
271 // This prevents problems with spaces and 8bit charcaters
273 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
275 // use new style name
276 DocFileName const in_file = DocFileName(try_in_file);
277 base = removeExtension(in_file.mangledFilename());
278 FileName const out_file = makeAbsPath(base + ".bst",
279 buffer().masterBuffer()->temppath());
280 bool const success = in_file.copyTo(out_file);
282 lyxerr << "Failed to copy '" << in_file
283 << "' to '" << out_file << "'"
288 os << "\\bibliographystyle{"
289 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
294 // Post this warning only once.
295 static bool warned_about_bst_spaces = false;
296 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
297 warned_about_bst_spaces = true;
298 Alert::warning(_("Export Warning!"),
299 _("There are spaces in the path to your BibTeX style file.\n"
300 "BibTeX will be unable to find it."));
303 if (!db_out.empty() && buffer().params().use_bibtopic) {
304 os << "\\begin{btSect}{" << db_out << "}\n";
305 docstring btprint = getParam("btprint");
308 btprint = from_ascii("btPrintCited");
309 os << "\\" << btprint << "\n"
310 << "\\end{btSect}\n";
315 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
316 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
317 if (buffer().params().sides == OneSide) {
322 os << "\\cleardoublepage";
324 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
325 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
326 os << "\\addcontentsline{toc}{section}{\\refname}";
329 if (!db_out.empty() && !buffer().params().use_bibtopic) {
330 docstring btprint = getParam("btprint");
331 if (btprint == "btPrintAll") {
332 os << "\\nocite{*}\n";
335 os << "\\bibliography{" << db_out << "}\n";
343 support::FileNameList InsetBibtex::getBibFiles() const
345 FileName path(buffer().filePath());
346 support::PathChanger p(path);
348 support::FileNameList vec;
350 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
351 vector<docstring>::const_iterator it = bibfilelist.begin();
352 vector<docstring>::const_iterator en = bibfilelist.end();
353 for (; it != en; ++it) {
354 FileName const file =
355 findtexfile(changeExtension(to_utf8(*it), "bib"), "bib");
357 // If we didn't find a matching file name just fail silently
368 // methods for parsing bibtex files
370 typedef map<docstring, docstring> VarMap;
372 /// remove whitespace characters, optionally a single comma,
373 /// and further whitespace characters from the stream.
374 /// @return true if a comma was found, false otherwise
376 bool removeWSAndComma(idocfstream & ifs) {
385 } while (ifs && isSpace(ch));
398 } while (ifs && isSpace(ch));
413 /// remove whitespace characters, read characer sequence
414 /// not containing whitespace characters or characters in
415 /// delimChars, and remove further whitespace characters.
417 /// @return true if a string of length > 0 could be read.
419 bool readTypeOrKey(docstring & val, idocfstream & ifs,
420 docstring const & delimChars, docstring const &illegalChars,
433 } while (ifs && isSpace(ch));
439 bool legalChar = true;
440 while (ifs && !isSpace(ch) &&
441 delimChars.find(ch) == docstring::npos &&
442 (legalChar = (illegalChars.find(ch) == docstring::npos))
445 if (chCase == makeLowerCase)
446 val += lowercase(ch);
458 while (ifs && isSpace(ch)) {
466 return val.length() > 0;
469 /// read subsequent bibtex values that are delimited with a #-character.
470 /// Concatenate all parts and replace names with the associated string in
471 /// the variable strings.
472 /// @return true if reading was successfull (all single parts were delimited
474 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
487 } while (ifs && isSpace(ch));
492 // check for field type
495 // read integer value
499 } while (ifs && isDigit(ch));
504 } else if (ch == '"' || ch == '{') {
506 char_type delim = ch == '"' ? '"': '}';
511 } while (ifs && isSpace(ch));
516 //We now have the first non-whitespace character
517 //We'll collapse adjacent whitespace.
518 bool lastWasWhiteSpace = false;
520 // inside this delimited text braces must match.
521 // Thus we can have a closing delimiter only
522 // when nestLevel == 0
525 while (ifs && (nestLevel > 0 || ch != delim)) {
527 lastWasWhiteSpace = true;
531 //We output the space only after we stop getting
532 //whitespace so as not to output any whitespace
533 //at the end of the value.
534 if (lastWasWhiteSpace) {
535 lastWasWhiteSpace = false;
541 // update nesting level
548 if (nestLevel < 0) return false;
565 // reading a string name
568 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
569 strName += lowercase(ch);
576 // replace the string with its assigned value or
577 // discard it if it's not assigned
578 if (strName.length()) {
579 VarMap::const_iterator pos = strings.find(strName);
580 if (pos != strings.end()) {
587 while (ifs && isSpace(ch)) {
594 // continue reading next value on concatenate with '#'
604 // This method returns a comma separated list of Bibtex entries
605 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
606 InsetIterator const & /*di*/) const
608 // This bibtex parser is a first step to parse bibtex files
611 // - it reads the whole bibtex entry and does a syntax check
612 // (matching delimiters, missing commas,...
613 // - it recovers from errors starting with the next @-character
614 // - it reads @string definitions and replaces them in the
616 // - it accepts more characters in keys or value names than
619 // Officially bibtex does only support ASCII, but in practice
620 // you can use the encoding of the main document as long as
621 // some elements like keys and names are pure ASCII. Therefore
622 // we convert the file from the buffer encoding.
623 // We don't restrict keys to ASCII in LyX, since our own
624 // InsetBibitem can generate non-ASCII keys, and nonstandard
625 // 8bit clean bibtex forks exist.
626 support::FileNameList const files = getBibFiles();
627 support::FileNameList::const_iterator it = files.begin();
628 support::FileNameList::const_iterator en = files.end();
629 for (; it != en; ++ it) {
630 idocfstream ifs(it->toFilesystemEncoding().c_str(),
631 ios_base::in, buffer().params().encoding().iconvName());
647 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
648 docstring(), makeLowerCase) || !ifs)
651 if (entryType == from_ascii("comment")) {
653 ifs.ignore(numeric_limits<int>::max(), '\n');
661 if ((ch != '(') && (ch != '{')) {
662 // invalid entry delimiter
668 if (entryType == from_ascii("string")) {
670 // read string and add it to the strings map
671 // (or replace it's old value)
675 if (!readTypeOrKey(name, ifs, from_ascii("="),
676 from_ascii("#{}(),"), makeLowerCase) || !ifs)
679 // next char must be an equal sign
681 if (!ifs || ch != '=')
684 if (!readValue(value, ifs, strings))
687 strings[name] = value;
689 } else if (entryType == from_ascii("preamble")) {
691 // preamble definitions are discarded.
692 // can they be of any use in lyx?
695 if (!readValue(value, ifs, strings))
700 // Citation entry. Try to read the key.
703 if (!readTypeOrKey(key, ifs, from_ascii(","),
704 from_ascii("}"), keepCase) || !ifs)
707 /////////////////////////////////////////////
708 // now we have a key, so we will add an entry
709 // (even if it's empty, as bibtex does)
711 // we now read the field = value pairs.
712 // all items must be separated by a comma. If
713 // it is missing the scanning of this entry is
714 // stopped and the next is searched.
718 docstring commaNewline;
720 BibTeXInfo keyvalmap(key, entryType);
722 bool readNext = removeWSAndComma(ifs);
724 while (ifs && readNext) {
727 if (!readTypeOrKey(name, ifs, from_ascii("="),
728 from_ascii("{}(),"), makeLowerCase) || !ifs)
731 // next char must be an equal sign
741 if (!readValue(value, ifs, strings))
744 keyvalmap[name] = value;
745 data += "\n\n" + value;
746 keylist.addFieldName(name);
747 readNext = removeWSAndComma(ifs);
751 keylist.addEntryType(entryType);
752 keyvalmap.setAllData(data);
753 keylist[key] = keyvalmap;
756 } //< for loop over files
760 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
762 string texfile = changeExtension(to_utf8(filename), "bib");
763 // note that, if the filename can be found directly from the path,
764 // findtexfile will just return a FileName object for that path.
765 FileName file(findtexfile(texfile, "bib"));
767 file = FileName(makeAbsPath(texfile, buf.filePath()));
772 bool InsetBibtex::addDatabase(docstring const & db)
774 docstring bibfiles = getParam("bibfiles");
775 if (tokenPos(bibfiles, ',', db) != -1)
777 if (!bibfiles.empty())
779 setParam("bibfiles", bibfiles + db);
784 bool InsetBibtex::delDatabase(docstring const & db)
786 docstring bibfiles = getParam("bibfiles");
787 if (contains(bibfiles, db)) {
788 int const n = tokenPos(bibfiles, ',', db);
791 // this is not the first database
792 docstring tmp = ',' + bd;
793 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
795 // this is the first (or only) database
796 setParam("bibfiles", split(bibfiles, bd, ','));
804 void InsetBibtex::validate(LaTeXFeatures & features) const
806 if (features.bufferParams().use_bibtopic)
807 features.require("bibtopic");