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 static string normalizeName(Buffer const & buffer,
106 OutputParams const & runparams, string const & name, string const & ext)
108 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
109 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
115 return to_utf8(makeRelPath(from_utf8(fname),
116 from_utf8(buffer.masterBuffer()->filePath())));
120 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
122 // the sequence of the commands:
123 // 1. \bibliographystyle{style}
124 // 2. \addcontentsline{...} - if option bibtotoc set
125 // 3. \bibliography{database}
126 // and with bibtopic:
127 // 1. \bibliographystyle{style}
128 // 2. \begin{btSect}{database}
129 // 3. \btPrint{Cited|NotCited|All}
133 // If we are processing the LaTeX file in a temp directory then
134 // copy the .bib databases to this temp directory, mangling their
135 // names in the process. Store this mangled name in the list of
137 // (We need to do all this because BibTeX *really*, *really*
138 // can't handle "files with spaces" and Windows users tend to
139 // use such filenames.)
140 // Otherwise, store the (maybe absolute) path to the original,
141 // unmangled database name.
142 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
143 vector<docstring>::const_iterator it = bibfilelist.begin();
144 vector<docstring>::const_iterator en = bibfilelist.end();
145 odocstringstream dbs;
148 for (; it != en; ++it) {
149 string utf8input = to_utf8(*it);
151 normalizeName(buffer(), runparams, utf8input, ".bib");
152 FileName const try_in_file =
153 makeAbsPath(database + ".bib", buffer().filePath());
154 bool const not_from_texmf = try_in_file.isReadableFile();
156 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
159 // mangledFilename() needs the extension
160 DocFileName const in_file = DocFileName(try_in_file);
161 database = removeExtension(in_file.mangledFilename());
162 FileName const out_file = makeAbsPath(database + ".bib",
163 buffer().masterBuffer()->temppath());
165 bool const success = in_file.copyTo(out_file);
167 lyxerr << "Failed to copy '" << in_file
168 << "' to '" << out_file << "'"
171 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
172 !isValidLaTeXFilename(database)) {
173 frontend::Alert::warning(_("Invalid filename"),
174 _("The following filename is likely to cause trouble "
175 "when running the exported file through LaTeX: ") +
176 from_utf8(database));
184 dbs << from_utf8(latex_path(database));
186 docstring const db_out = dbs.str();
188 // Post this warning only once.
189 static bool warned_about_spaces = false;
190 if (!warned_about_spaces &&
191 runparams.nice && db_out.find(' ') != docstring::npos) {
192 warned_about_spaces = true;
194 Alert::warning(_("Export Warning!"),
195 _("There are spaces in the paths to your BibTeX databases.\n"
196 "BibTeX will be unable to find them."));
200 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
202 if (prefixIs(style, "bibtotoc")) {
203 bibtotoc = "bibtotoc";
204 if (contains(style, ','))
205 style = split(style, bibtotoc, ',');
211 if (!style.empty()) {
212 string base = normalizeName(buffer(), runparams, style, ".bst");
213 FileName const try_in_file =
214 makeAbsPath(base + ".bst", buffer().filePath());
215 bool const not_from_texmf = try_in_file.isReadableFile();
216 // If this style does not come from texmf and we are not
217 // exporting to .tex copy it to the tmp directory.
218 // This prevents problems with spaces and 8bit charcaters
220 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
222 // use new style name
223 DocFileName const in_file = DocFileName(try_in_file);
224 base = removeExtension(in_file.mangledFilename());
225 FileName const out_file = makeAbsPath(base + ".bst",
226 buffer().masterBuffer()->temppath());
227 bool const success = in_file.copyTo(out_file);
229 lyxerr << "Failed to copy '" << in_file
230 << "' to '" << out_file << "'"
235 os << "\\bibliographystyle{"
236 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
241 // Post this warning only once.
242 static bool warned_about_bst_spaces = false;
243 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
244 warned_about_bst_spaces = true;
245 Alert::warning(_("Export Warning!"),
246 _("There are spaces in the path to your BibTeX style file.\n"
247 "BibTeX will be unable to find it."));
250 if (!db_out.empty() && buffer().params().use_bibtopic) {
251 os << "\\begin{btSect}{" << db_out << "}\n";
252 docstring btprint = getParam("btprint");
255 btprint = from_ascii("btPrintCited");
256 os << "\\" << btprint << "\n"
257 << "\\end{btSect}\n";
262 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
263 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
264 if (buffer().params().sides == OneSide) {
269 os << "\\cleardoublepage";
271 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
272 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
273 os << "\\addcontentsline{toc}{section}{\\refname}";
276 if (!db_out.empty() && !buffer().params().use_bibtopic) {
277 docstring btprint = getParam("btprint");
278 if (btprint == "btPrintAll") {
279 os << "\\nocite{*}\n";
282 os << "\\bibliography{" << db_out << "}\n";
290 support::FileNameList InsetBibtex::getBibFiles() const
292 FileName path(buffer().filePath());
293 support::PathChanger p(path);
297 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
298 vector<docstring>::const_iterator it = bibfilelist.begin();
299 vector<docstring>::const_iterator en = bibfilelist.end();
300 for (; it != en; ++it) {
301 FileName const file =
302 findtexfile(changeExtension(to_utf8(*it), "bib"), "bib");
304 // If we didn't find a matching file name just fail silently
315 // methods for parsing bibtex files
317 typedef map<docstring, docstring> VarMap;
319 /// remove whitespace characters, optionally a single comma,
320 /// and further whitespace characters from the stream.
321 /// @return true if a comma was found, false otherwise
323 bool removeWSAndComma(idocfstream & ifs) {
332 } while (ifs && isSpace(ch));
345 } while (ifs && isSpace(ch));
360 /// remove whitespace characters, read characer sequence
361 /// not containing whitespace characters or characters in
362 /// delimChars, and remove further whitespace characters.
364 /// @return true if a string of length > 0 could be read.
366 bool readTypeOrKey(docstring & val, idocfstream & ifs,
367 docstring const & delimChars, docstring const &illegalChars,
380 } while (ifs && isSpace(ch));
386 bool legalChar = true;
387 while (ifs && !isSpace(ch) &&
388 delimChars.find(ch) == docstring::npos &&
389 (legalChar = (illegalChars.find(ch) == docstring::npos))
392 if (chCase == makeLowerCase)
393 val += lowercase(ch);
405 while (ifs && isSpace(ch)) {
413 return val.length() > 0;
416 /// read subsequent bibtex values that are delimited with a #-character.
417 /// Concatenate all parts and replace names with the associated string in
418 /// the variable strings.
419 /// @return true if reading was successfull (all single parts were delimited
421 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
434 } while (ifs && isSpace(ch));
439 // check for field type
442 // read integer value
446 } while (ifs && isDigit(ch));
451 } else if (ch == '"' || ch == '{') {
453 char_type delim = ch == '"' ? '"': '}';
458 } while (ifs && isSpace(ch));
463 //We now have the first non-whitespace character
464 //We'll collapse adjacent whitespace.
465 bool lastWasWhiteSpace = false;
467 // inside this delimited text braces must match.
468 // Thus we can have a closing delimiter only
469 // when nestLevel == 0
472 while (ifs && (nestLevel > 0 || ch != delim)) {
474 lastWasWhiteSpace = true;
478 //We output the space only after we stop getting
479 //whitespace so as not to output any whitespace
480 //at the end of the value.
481 if (lastWasWhiteSpace) {
482 lastWasWhiteSpace = false;
488 // update nesting level
495 if (nestLevel < 0) return false;
512 // reading a string name
515 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
516 strName += lowercase(ch);
523 // replace the string with its assigned value or
524 // discard it if it's not assigned
525 if (strName.length()) {
526 VarMap::const_iterator pos = strings.find(strName);
527 if (pos != strings.end()) {
534 while (ifs && isSpace(ch)) {
541 // continue reading next value on concatenate with '#'
551 // This method returns a comma separated list of Bibtex entries
552 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
553 InsetIterator const & /*di*/) const
555 // This bibtex parser is a first step to parse bibtex files
558 // - it reads the whole bibtex entry and does a syntax check
559 // (matching delimiters, missing commas,...
560 // - it recovers from errors starting with the next @-character
561 // - it reads @string definitions and replaces them in the
563 // - it accepts more characters in keys or value names than
566 // Officially bibtex does only support ASCII, but in practice
567 // you can use the encoding of the main document as long as
568 // some elements like keys and names are pure ASCII. Therefore
569 // we convert the file from the buffer encoding.
570 // We don't restrict keys to ASCII in LyX, since our own
571 // InsetBibitem can generate non-ASCII keys, and nonstandard
572 // 8bit clean bibtex forks exist.
573 support::FileNameList const & files = getBibFiles();
574 support::FileNameList::const_iterator it = files.begin();
575 support::FileNameList::const_iterator en = files.end();
576 for (; it != en; ++ it) {
577 idocfstream ifs(it->toFilesystemEncoding().c_str(),
578 ios_base::in, buffer().params().encoding().iconvName());
594 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
595 docstring(), makeLowerCase) || !ifs)
598 if (entryType == from_ascii("comment")) {
600 ifs.ignore(numeric_limits<int>::max(), '\n');
608 if ((ch != '(') && (ch != '{')) {
609 // invalid entry delimiter
615 if (entryType == from_ascii("string")) {
617 // read string and add it to the strings map
618 // (or replace it's old value)
622 if (!readTypeOrKey(name, ifs, from_ascii("="),
623 from_ascii("#{}(),"), makeLowerCase) || !ifs)
626 // next char must be an equal sign
628 if (!ifs || ch != '=')
631 if (!readValue(value, ifs, strings))
634 strings[name] = value;
636 } else if (entryType == from_ascii("preamble")) {
638 // preamble definitions are discarded.
639 // can they be of any use in lyx?
642 if (!readValue(value, ifs, strings))
647 // Citation entry. Try to read the key.
650 if (!readTypeOrKey(key, ifs, from_ascii(","),
651 from_ascii("}"), keepCase) || !ifs)
654 /////////////////////////////////////////////
655 // now we have a key, so we will add an entry
656 // (even if it's empty, as bibtex does)
658 // we now read the field = value pairs.
659 // all items must be separated by a comma. If
660 // it is missing the scanning of this entry is
661 // stopped and the next is searched.
665 docstring commaNewline;
667 BibTeXInfo keyvalmap(key, entryType);
669 bool readNext = removeWSAndComma(ifs);
671 while (ifs && readNext) {
674 if (!readTypeOrKey(name, ifs, from_ascii("="),
675 from_ascii("{}(),"), makeLowerCase) || !ifs)
678 // next char must be an equal sign
688 if (!readValue(value, ifs, strings))
691 keyvalmap[name] = value;
692 data += "\n\n" + value;
693 keylist.addFieldName(name);
694 readNext = removeWSAndComma(ifs);
698 keylist.addEntryType(entryType);
699 keyvalmap.setAllData(data);
700 keylist[key] = keyvalmap;
703 } //< for loop over files
707 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
709 string texfile = changeExtension(to_utf8(filename), "bib");
710 // note that, if the filename can be found directly from the path,
711 // findtexfile will just return a FileName object for that path.
712 FileName file(findtexfile(texfile, "bib"));
714 file = FileName(makeAbsPath(texfile, buf.filePath()));
719 bool InsetBibtex::addDatabase(docstring const & db)
721 docstring bibfiles = getParam("bibfiles");
722 if (tokenPos(bibfiles, ',', db) == -1) {
723 if (!bibfiles.empty())
725 setParam("bibfiles", bibfiles + db);
732 bool InsetBibtex::delDatabase(docstring const & db)
734 docstring bibfiles = getParam("bibfiles");
735 if (contains(bibfiles, db)) {
736 int const n = tokenPos(bibfiles, ',', db);
739 // this is not the first database
740 docstring tmp = ',' + bd;
741 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
743 // this is the first (or only) database
744 setParam("bibfiles", split(bibfiles, bd, ','));
752 void InsetBibtex::validate(LaTeXFeatures & features) const
754 if (features.bufferParams().use_bibtopic)
755 features.require("bibtopic");