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"
23 #include "LaTeXFeatures.h"
24 #include "MetricsInfo.h"
25 #include "OutputParams.h"
27 #include "frontends/alert.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/docstream.h"
31 #include "support/filetools.h"
32 #include "support/lstrings.h"
33 #include "support/lyxlib.h"
34 #include "support/os.h"
35 #include "support/Path.h"
36 #include "support/textutils.h"
38 #include <boost/tokenizer.hpp>
43 using support::absolutePath;
44 using support::ascii_lowercase;
45 using support::changeExtension;
46 using support::contains;
48 using support::DocFileName;
49 using support::FileName;
50 using support::findtexfile;
51 using support::isValidLaTeXFilename;
52 using support::latex_path;
54 using support::makeAbsPath;
55 using support::makeRelPath;
56 using support::prefixIs;
57 using support::removeExtension;
61 using support::tokenPos;
63 using support::lowercase;
65 namespace Alert = frontend::Alert;
66 namespace os = support::os;
77 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
78 : InsetCommand(p, "bibtex")
82 CommandInfo const * InsetBibtex::findInfo(std::string const & /* cmdName */)
84 static const char * const paramnames[] =
85 {"options", "btprint", "bibfiles", ""};
86 static const bool isoptional[] = {true, true, false};
87 static const CommandInfo info = {3, paramnames, isoptional};
92 Inset * InsetBibtex::clone() const
94 return new InsetBibtex(*this);
98 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
100 switch (cmd.action) {
102 case LFUN_INSET_MODIFY: {
103 InsetCommandParams p(BIBTEX_CODE);
105 if (!InsetCommandMailer::string2params("bibtex",
106 to_utf8(cmd.argument()), p)) {
110 } catch (support::ExceptionMessage const & message) {
111 if (message.type_ == support::WarningException) {
112 Alert::warning(message.title_, message.details_);
119 cur.buffer().updateBibfilesCache();
124 InsetCommand::doDispatch(cur, cmd);
130 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
132 return _("BibTeX Generated Bibliography");
138 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
139 string const & name, string const & ext)
141 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
142 if (absolutePath(name) || !FileName(fname + ext).isFileReadable())
148 return to_utf8(makeRelPath(from_utf8(fname),
149 from_utf8(buffer.masterBuffer()->filePath())));
155 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
156 OutputParams const & runparams) const
158 // the sequence of the commands:
159 // 1. \bibliographystyle{style}
160 // 2. \addcontentsline{...} - if option bibtotoc set
161 // 3. \bibliography{database}
162 // and with bibtopic:
163 // 1. \bibliographystyle{style}
164 // 2. \begin{btSect}{database}
165 // 3. \btPrint{Cited|NotCited|All}
169 // If we are processing the LaTeX file in a temp directory then
170 // copy the .bib databases to this temp directory, mangling their
171 // names in the process. Store this mangled name in the list of
173 // (We need to do all this because BibTeX *really*, *really*
174 // can't handle "files with spaces" and Windows users tend to
175 // use such filenames.)
176 // Otherwise, store the (maybe absolute) path to the original,
177 // unmangled database name.
178 typedef boost::char_separator<char_type> Separator;
179 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
181 Separator const separator(from_ascii(",").c_str());
182 // The tokenizer must not be called with temporary strings, since
183 // it does not make a copy and uses iterators of the string further
184 // down. getParam returns a reference, so this is OK.
185 Tokenizer const tokens(getParam("bibfiles"), separator);
186 Tokenizer::const_iterator const begin = tokens.begin();
187 Tokenizer::const_iterator const end = tokens.end();
189 odocstringstream dbs;
190 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
191 docstring const input = trim(*it);
193 string utf8input = to_utf8(input);
195 normalizeName(buffer, runparams, utf8input, ".bib");
196 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
197 bool const not_from_texmf = try_in_file.isFileReadable();
199 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
202 // mangledFilename() needs the extension
203 DocFileName const in_file = DocFileName(try_in_file);
204 database = removeExtension(in_file.mangledFilename());
205 FileName const out_file = makeAbsPath(database + ".bib",
206 buffer.masterBuffer()->temppath());
208 bool const success = copy(in_file, out_file);
210 lyxerr << "Failed to copy '" << in_file
211 << "' to '" << out_file << "'"
214 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
215 !isValidLaTeXFilename(database)) {
216 frontend::Alert::warning(_("Invalid filename"),
217 _("The following filename is likely to cause trouble "
218 "when running the exported file through LaTeX: ") +
219 from_utf8(database));
225 dbs << from_utf8(latex_path(database));
227 docstring const db_out = dbs.str();
229 // Post this warning only once.
230 static bool warned_about_spaces = false;
231 if (!warned_about_spaces &&
232 runparams.nice && db_out.find(' ') != docstring::npos) {
233 warned_about_spaces = true;
235 Alert::warning(_("Export Warning!"),
236 _("There are spaces in the paths to your BibTeX databases.\n"
237 "BibTeX will be unable to find them."));
241 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
243 if (prefixIs(style, "bibtotoc")) {
244 bibtotoc = "bibtotoc";
245 if (contains(style, ','))
246 style = split(style, bibtotoc, ',');
252 if (!style.empty()) {
253 string base = normalizeName(buffer, runparams, style, ".bst");
254 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
255 bool const not_from_texmf = try_in_file.isFileReadable();
256 // If this style does not come from texmf and we are not
257 // exporting to .tex copy it to the tmp directory.
258 // This prevents problems with spaces and 8bit charcaters
260 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
262 // use new style name
263 DocFileName const in_file = DocFileName(try_in_file);
264 base = removeExtension(in_file.mangledFilename());
265 FileName const out_file(makeAbsPath(base + ".bst",
266 buffer.masterBuffer()->temppath()));
267 bool const success = copy(in_file, out_file);
269 lyxerr << "Failed to copy '" << in_file
270 << "' to '" << out_file << "'"
275 os << "\\bibliographystyle{"
276 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
281 // Post this warning only once.
282 static bool warned_about_bst_spaces = false;
283 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
284 warned_about_bst_spaces = true;
285 Alert::warning(_("Export Warning!"),
286 _("There are spaces in the path to your BibTeX style file.\n"
287 "BibTeX will be unable to find it."));
290 if (!db_out.empty() && buffer.params().use_bibtopic){
291 os << "\\begin{btSect}{" << db_out << "}\n";
292 docstring btprint = getParam("btprint");
295 btprint = from_ascii("btPrintCited");
296 os << "\\" << btprint << "\n"
297 << "\\end{btSect}\n";
302 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
303 // maybe a problem when a textclass has no "art" as
304 // part of its name, because it's than book.
305 // For the "official" lyx-layouts it's no problem to support
307 if (!contains(buffer.params().getTextClass().name(),
309 if (buffer.params().sides == TextClass::OneSide) {
314 os << "\\cleardoublepage";
318 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
322 os << "\\addcontentsline{toc}{section}{\\refname}";
326 if (!db_out.empty() && !buffer.params().use_bibtopic){
327 os << "\\bibliography{" << db_out << "}\n";
335 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
337 FileName path(buffer.filePath());
338 support::Path p(path);
340 vector<FileName> vec;
344 string bibfiles = to_utf8(getParam("bibfiles"));
345 bibfiles = split(bibfiles, tmp, ',');
346 while (!tmp.empty()) {
347 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
348 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
350 // If we didn't find a matching file name just fail silently
354 // Get next file name
355 bibfiles = split(bibfiles, tmp, ',');
363 // methods for parsing bibtex files
365 typedef map<docstring, docstring> VarMap;
367 /// remove whitespace characters, optionally a single comma,
368 /// and further whitespace characters from the stream.
369 /// @return true if a comma was found, false otherwise
371 bool removeWSAndComma(idocfstream & ifs) {
380 } while (ifs && isSpace(ch));
393 } while (ifs && isSpace(ch));
408 /// remove whitespace characters, read characer sequence
409 /// not containing whitespace characters or characters in
410 /// delimChars, and remove further whitespace characters.
412 /// @return true if a string of length > 0 could be read.
414 bool readTypeOrKey(docstring & val, idocfstream & ifs,
415 docstring const & delimChars, docstring const &illegalChars,
428 } while (ifs && isSpace(ch));
434 bool legalChar = true;
435 while (ifs && !isSpace(ch) &&
436 delimChars.find(ch) == docstring::npos &&
437 (legalChar = (illegalChars.find(ch) == docstring::npos))
440 if (chCase == makeLowerCase)
441 val += lowercase(ch);
453 while (ifs && isSpace(ch)) {
461 return val.length() > 0;
464 /// read subsequent bibtex values that are delimited with a #-character.
465 /// Concatenate all parts and replace names with the associated string in
466 /// the variable strings.
467 /// @return true if reading was successfull (all single parts were delimited
469 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
482 } while (ifs && isSpace(ch));
487 // check for field type
490 // read integer value
494 } while (ifs && isDigit(ch));
499 } else if (ch == '"' || ch == '{') {
501 char_type delim = ch == '"' ? '"': '}';
506 } while (ifs && isSpace(ch));
511 //We now have the first non-whitespace character
512 //We'll collapse adjacent whitespace.
513 bool lastWasWhiteSpace = false;
515 // inside this delimited text braces must match.
516 // Thus we can have a closing delimiter only
517 // when nestLevel == 0
520 while (ifs && (nestLevel > 0 || ch != delim)) {
522 lastWasWhiteSpace = true;
526 //We output the space only after we stop getting
527 //whitespace so as not to output any whitespace
528 //at the end of the value.
529 if (lastWasWhiteSpace) {
530 lastWasWhiteSpace = false;
536 // update nesting level
543 if (nestLevel < 0) return false;
560 // reading a string name
563 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
564 strName += lowercase(ch);
571 // replace the string with its assigned value or
572 // discard it if it's not assigned
573 if (strName.length()) {
574 VarMap::const_iterator pos = strings.find(strName);
575 if (pos != strings.end()) {
582 while (ifs && isSpace(ch)) {
589 // continue reading next value on concatenate with '#'
599 // This method returns a comma separated list of Bibtex entries
600 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
601 BiblioInfo & keylist, InsetIterator const & /*di*/) const
603 vector<FileName> const files = getFiles(buffer);
604 for (vector<FileName>::const_iterator it = files.begin();
605 it != files.end(); ++ it) {
606 // This bibtex parser is a first step to parse bibtex files
609 // - it reads the whole bibtex entry and does a syntax check
610 // (matching delimiters, missing commas,...
611 // - it recovers from errors starting with the next @-character
612 // - it reads @string definitions and replaces them in the
614 // - it accepts more characters in keys or value names than
617 // Officially bibtex does only support ASCII, but in practice
618 // you can use the encoding of the main document as long as
619 // some elements like keys and names are pure ASCII. Therefore
620 // we convert the file from the buffer encoding.
621 // We don't restrict keys to ASCII in LyX, since our own
622 // InsetBibitem can generate non-ASCII keys, and nonstandard
623 // 8bit clean bibtex forks exist.
625 idocfstream ifs(it->toFilesystemEncoding().c_str(),
627 buffer.params().encoding().iconvName());
643 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
644 docstring(), makeLowerCase) || !ifs)
647 if (entryType == from_ascii("comment")) {
649 ifs.ignore(std::numeric_limits<int>::max(), '\n');
657 if ((ch != '(') && (ch != '{')) {
658 // invalid entry delimiter
664 if (entryType == from_ascii("string")) {
666 // read string and add it to the strings map
667 // (or replace it's old value)
671 if (!readTypeOrKey(name, ifs, from_ascii("="),
672 from_ascii("#{}(),"), makeLowerCase) || !ifs)
675 // next char must be an equal sign
677 if (!ifs || ch != '=')
680 if (!readValue(value, ifs, strings))
683 strings[name] = value;
685 } else if (entryType == from_ascii("preamble")) {
687 // preamble definitions are discarded.
688 // can they be of any use in lyx?
691 if (!readValue(value, ifs, strings))
696 // Citation entry. Try to read the key.
699 if (!readTypeOrKey(key, ifs, from_ascii(","),
700 from_ascii("}"), keepCase) || !ifs)
703 /////////////////////////////////////////////
704 // now we have a key, so we will add an entry
705 // (even if it's empty, as bibtex does)
707 // we now read the field = value pairs.
708 // all items must be separated by a comma. If
709 // it is missing the scanning of this entry is
710 // stopped and the next is searched.
714 docstring commaNewline;
716 BibTeXInfo keyvalmap;
717 keyvalmap.entryType = entryType;
719 bool readNext = removeWSAndComma(ifs);
721 while (ifs && readNext) {
724 if (!readTypeOrKey(name, ifs, from_ascii("="),
725 from_ascii("{}(),"), makeLowerCase) || !ifs)
728 // next char must be an equal sign
738 if (!readValue(value, ifs, strings))
741 keyvalmap[name] = value;
742 data += "\n\n" + value;
743 keylist.fieldNames.insert(name);
744 readNext = removeWSAndComma(ifs);
748 keylist.entryTypes.insert(entryType);
749 keyvalmap.allData = data;
750 keyvalmap.isBibTeX = true;
751 keyvalmap.bibKey = key;
752 keylist[key] = keyvalmap;
755 } //< for loop over files
760 bool InsetBibtex::addDatabase(string const & db)
763 string bibfiles(to_utf8(getParam("bibfiles")));
764 if (tokenPos(bibfiles, ',', db) == -1) {
765 if (!bibfiles.empty())
767 setParam("bibfiles", from_utf8(bibfiles + db));
774 bool InsetBibtex::delDatabase(string const & db)
777 string bibfiles(to_utf8(getParam("bibfiles")));
778 if (contains(bibfiles, db)) {
779 int const n = tokenPos(bibfiles, ',', db);
782 // this is not the first database
783 string tmp = ',' + bd;
784 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
786 // this is the first (or only) database
787 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
795 void InsetBibtex::validate(LaTeXFeatures & features) const
797 if (features.bufferParams().use_bibtopic)
798 features.require("bibtopic");