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"
19 #include "support/debug.h"
21 #include "FuncRequest.h"
22 #include "support/gettext.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/ExceptionMessage.h"
31 #include "support/docstream.h"
32 #include "support/FileNameList.h"
33 #include "support/filetools.h"
34 #include "support/lstrings.h"
35 #include "support/lyxlib.h"
36 #include "support/os.h"
37 #include "support/Path.h"
38 #include "support/textutils.h"
40 #include <boost/tokenizer.hpp>
43 using namespace lyx::support;
47 namespace Alert = frontend::Alert;
48 namespace os = support::os;
51 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
52 : InsetCommand(p, "bibtex")
56 CommandInfo const * InsetBibtex::findInfo(string const & /* cmdName */)
58 static const char * const paramnames[] =
59 {"options", "btprint", "bibfiles", ""};
60 static const bool isoptional[] = {true, true, false};
61 static const CommandInfo info = {3, paramnames, isoptional};
66 Inset * InsetBibtex::clone() const
68 return new InsetBibtex(*this);
72 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
76 case LFUN_INSET_MODIFY: {
77 InsetCommandParams p(BIBTEX_CODE);
79 if (!InsetCommandMailer::string2params("bibtex",
80 to_utf8(cmd.argument()), p)) {
84 } catch (ExceptionMessage const & message) {
85 if (message.type_ == WarningException) {
86 Alert::warning(message.title_, message.details_);
93 cur.buffer().updateBibfilesCache();
98 InsetCommand::doDispatch(cur, cmd);
104 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
106 return _("BibTeX Generated Bibliography");
112 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
113 string const & name, string const & ext)
115 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
116 if (absolutePath(name) || !FileName(fname + ext).isReadableFile())
122 return to_utf8(makeRelPath(from_utf8(fname),
123 from_utf8(buffer.masterBuffer()->filePath())));
129 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
130 OutputParams const & runparams) const
132 // the sequence of the commands:
133 // 1. \bibliographystyle{style}
134 // 2. \addcontentsline{...} - if option bibtotoc set
135 // 3. \bibliography{database}
136 // and with bibtopic:
137 // 1. \bibliographystyle{style}
138 // 2. \begin{btSect}{database}
139 // 3. \btPrint{Cited|NotCited|All}
143 // If we are processing the LaTeX file in a temp directory then
144 // copy the .bib databases to this temp directory, mangling their
145 // names in the process. Store this mangled name in the list of
147 // (We need to do all this because BibTeX *really*, *really*
148 // can't handle "files with spaces" and Windows users tend to
149 // use such filenames.)
150 // Otherwise, store the (maybe absolute) path to the original,
151 // unmangled database name.
152 typedef boost::char_separator<char_type> Separator;
153 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
155 Separator const separator(from_ascii(",").c_str());
156 // The tokenizer must not be called with temporary strings, since
157 // it does not make a copy and uses iterators of the string further
158 // down. getParam returns a reference, so this is OK.
159 Tokenizer const tokens(getParam("bibfiles"), separator);
160 Tokenizer::const_iterator const begin = tokens.begin();
161 Tokenizer::const_iterator const end = tokens.end();
163 odocstringstream dbs;
164 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
165 docstring const input = trim(*it);
167 string utf8input = to_utf8(input);
169 normalizeName(buffer, runparams, utf8input, ".bib");
170 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
171 bool const not_from_texmf = try_in_file.isReadableFile();
173 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
176 // mangledFilename() needs the extension
177 DocFileName const in_file = DocFileName(try_in_file);
178 database = removeExtension(in_file.mangledFilename());
179 FileName const out_file = makeAbsPath(database + ".bib",
180 buffer.masterBuffer()->temppath());
182 bool const success = in_file.copyTo(out_file);
184 lyxerr << "Failed to copy '" << in_file
185 << "' to '" << out_file << "'"
188 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
189 !isValidLaTeXFilename(database)) {
190 frontend::Alert::warning(_("Invalid filename"),
191 _("The following filename is likely to cause trouble "
192 "when running the exported file through LaTeX: ") +
193 from_utf8(database));
199 dbs << from_utf8(latex_path(database));
201 docstring const db_out = dbs.str();
203 // Post this warning only once.
204 static bool warned_about_spaces = false;
205 if (!warned_about_spaces &&
206 runparams.nice && db_out.find(' ') != docstring::npos) {
207 warned_about_spaces = true;
209 Alert::warning(_("Export Warning!"),
210 _("There are spaces in the paths to your BibTeX databases.\n"
211 "BibTeX will be unable to find them."));
215 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
217 if (prefixIs(style, "bibtotoc")) {
218 bibtotoc = "bibtotoc";
219 if (contains(style, ','))
220 style = split(style, bibtotoc, ',');
226 if (!style.empty()) {
227 string base = normalizeName(buffer, runparams, style, ".bst");
228 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
229 bool const not_from_texmf = try_in_file.isReadableFile();
230 // If this style does not come from texmf and we are not
231 // exporting to .tex copy it to the tmp directory.
232 // This prevents problems with spaces and 8bit charcaters
234 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
236 // use new style name
237 DocFileName const in_file = DocFileName(try_in_file);
238 base = removeExtension(in_file.mangledFilename());
239 FileName const out_file(makeAbsPath(base + ".bst",
240 buffer.masterBuffer()->temppath()));
241 bool const success = in_file.copyTo(out_file);
243 lyxerr << "Failed to copy '" << in_file
244 << "' to '" << out_file << "'"
249 os << "\\bibliographystyle{"
250 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
255 // Post this warning only once.
256 static bool warned_about_bst_spaces = false;
257 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
258 warned_about_bst_spaces = true;
259 Alert::warning(_("Export Warning!"),
260 _("There are spaces in the path to your BibTeX style file.\n"
261 "BibTeX will be unable to find it."));
264 if (!db_out.empty() && buffer.params().use_bibtopic){
265 os << "\\begin{btSect}{" << db_out << "}\n";
266 docstring btprint = getParam("btprint");
269 btprint = from_ascii("btPrintCited");
270 os << "\\" << btprint << "\n"
271 << "\\end{btSect}\n";
276 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
277 // maybe a problem when a textclass has no "art" as
278 // part of its name, because it's than book.
279 // For the "official" lyx-layouts it's no problem to support
281 if (!contains(buffer.params().getTextClass().name(),
283 if (buffer.params().sides == OneSide) {
288 os << "\\cleardoublepage";
292 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
296 os << "\\addcontentsline{toc}{section}{\\refname}";
300 if (!db_out.empty() && !buffer.params().use_bibtopic){
301 os << "\\bibliography{" << db_out << "}\n";
309 FileNameList const InsetBibtex::getFiles(Buffer const & buffer) const
311 FileName path(buffer.filePath());
318 string bibfiles = to_utf8(getParam("bibfiles"));
319 bibfiles = split(bibfiles, tmp, ',');
320 while (!tmp.empty()) {
321 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
322 LYXERR(Debug::LATEX, "Bibfile: " << file);
324 // If we didn't find a matching file name just fail silently
328 // Get next file name
329 bibfiles = split(bibfiles, tmp, ',');
337 // methods for parsing bibtex files
339 typedef map<docstring, docstring> VarMap;
341 /// remove whitespace characters, optionally a single comma,
342 /// and further whitespace characters from the stream.
343 /// @return true if a comma was found, false otherwise
345 bool removeWSAndComma(idocfstream & ifs) {
354 } while (ifs && isSpace(ch));
367 } while (ifs && isSpace(ch));
382 /// remove whitespace characters, read characer sequence
383 /// not containing whitespace characters or characters in
384 /// delimChars, and remove further whitespace characters.
386 /// @return true if a string of length > 0 could be read.
388 bool readTypeOrKey(docstring & val, idocfstream & ifs,
389 docstring const & delimChars, docstring const &illegalChars,
402 } while (ifs && isSpace(ch));
408 bool legalChar = true;
409 while (ifs && !isSpace(ch) &&
410 delimChars.find(ch) == docstring::npos &&
411 (legalChar = (illegalChars.find(ch) == docstring::npos))
414 if (chCase == makeLowerCase)
415 val += lowercase(ch);
427 while (ifs && isSpace(ch)) {
435 return val.length() > 0;
438 /// read subsequent bibtex values that are delimited with a #-character.
439 /// Concatenate all parts and replace names with the associated string in
440 /// the variable strings.
441 /// @return true if reading was successfull (all single parts were delimited
443 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
456 } while (ifs && isSpace(ch));
461 // check for field type
464 // read integer value
468 } while (ifs && isDigit(ch));
473 } else if (ch == '"' || ch == '{') {
475 char_type delim = ch == '"' ? '"': '}';
480 } while (ifs && isSpace(ch));
485 //We now have the first non-whitespace character
486 //We'll collapse adjacent whitespace.
487 bool lastWasWhiteSpace = false;
489 // inside this delimited text braces must match.
490 // Thus we can have a closing delimiter only
491 // when nestLevel == 0
494 while (ifs && (nestLevel > 0 || ch != delim)) {
496 lastWasWhiteSpace = true;
500 //We output the space only after we stop getting
501 //whitespace so as not to output any whitespace
502 //at the end of the value.
503 if (lastWasWhiteSpace) {
504 lastWasWhiteSpace = false;
510 // update nesting level
517 if (nestLevel < 0) return false;
534 // reading a string name
537 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
538 strName += lowercase(ch);
545 // replace the string with its assigned value or
546 // discard it if it's not assigned
547 if (strName.length()) {
548 VarMap::const_iterator pos = strings.find(strName);
549 if (pos != strings.end()) {
556 while (ifs && isSpace(ch)) {
563 // continue reading next value on concatenate with '#'
573 // This method returns a comma separated list of Bibtex entries
574 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
575 BiblioInfo & keylist, InsetIterator const & /*di*/) const
577 FileNameList const files = getFiles(buffer);
578 for (vector<FileName>::const_iterator it = files.begin();
579 it != files.end(); ++ it) {
580 // This bibtex parser is a first step to parse bibtex files
583 // - it reads the whole bibtex entry and does a syntax check
584 // (matching delimiters, missing commas,...
585 // - it recovers from errors starting with the next @-character
586 // - it reads @string definitions and replaces them in the
588 // - it accepts more characters in keys or value names than
591 // Officially bibtex does only support ASCII, but in practice
592 // you can use the encoding of the main document as long as
593 // some elements like keys and names are pure ASCII. Therefore
594 // we convert the file from the buffer encoding.
595 // We don't restrict keys to ASCII in LyX, since our own
596 // InsetBibitem can generate non-ASCII keys, and nonstandard
597 // 8bit clean bibtex forks exist.
599 idocfstream ifs(it->toFilesystemEncoding().c_str(),
601 buffer.params().encoding().iconvName());
617 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
618 docstring(), makeLowerCase) || !ifs)
621 if (entryType == from_ascii("comment")) {
623 ifs.ignore(numeric_limits<int>::max(), '\n');
631 if ((ch != '(') && (ch != '{')) {
632 // invalid entry delimiter
638 if (entryType == from_ascii("string")) {
640 // read string and add it to the strings map
641 // (or replace it's old value)
645 if (!readTypeOrKey(name, ifs, from_ascii("="),
646 from_ascii("#{}(),"), makeLowerCase) || !ifs)
649 // next char must be an equal sign
651 if (!ifs || ch != '=')
654 if (!readValue(value, ifs, strings))
657 strings[name] = value;
659 } else if (entryType == from_ascii("preamble")) {
661 // preamble definitions are discarded.
662 // can they be of any use in lyx?
665 if (!readValue(value, ifs, strings))
670 // Citation entry. Try to read the key.
673 if (!readTypeOrKey(key, ifs, from_ascii(","),
674 from_ascii("}"), keepCase) || !ifs)
677 /////////////////////////////////////////////
678 // now we have a key, so we will add an entry
679 // (even if it's empty, as bibtex does)
681 // we now read the field = value pairs.
682 // all items must be separated by a comma. If
683 // it is missing the scanning of this entry is
684 // stopped and the next is searched.
688 docstring commaNewline;
690 BibTeXInfo keyvalmap;
691 keyvalmap.entryType = entryType;
693 bool readNext = removeWSAndComma(ifs);
695 while (ifs && readNext) {
698 if (!readTypeOrKey(name, ifs, from_ascii("="),
699 from_ascii("{}(),"), makeLowerCase) || !ifs)
702 // next char must be an equal sign
712 if (!readValue(value, ifs, strings))
715 keyvalmap[name] = value;
716 data += "\n\n" + value;
717 keylist.fieldNames.insert(name);
718 readNext = removeWSAndComma(ifs);
722 keylist.entryTypes.insert(entryType);
723 keyvalmap.allData = data;
724 keyvalmap.isBibTeX = true;
725 keyvalmap.bibKey = key;
726 keylist[key] = keyvalmap;
729 } //< for loop over files
734 bool InsetBibtex::addDatabase(string const & db)
737 string bibfiles(to_utf8(getParam("bibfiles")));
738 if (tokenPos(bibfiles, ',', db) == -1) {
739 if (!bibfiles.empty())
741 setParam("bibfiles", from_utf8(bibfiles + db));
748 bool InsetBibtex::delDatabase(string const & db)
751 string bibfiles(to_utf8(getParam("bibfiles")));
752 if (contains(bibfiles, db)) {
753 int const n = tokenPos(bibfiles, ',', db);
756 // this is not the first database
757 string tmp = ',' + bd;
758 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
760 // this is the first (or only) database
761 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
769 void InsetBibtex::validate(LaTeXFeatures & features) const
771 if (features.bufferParams().use_bibtopic)
772 features.require("bibtopic");