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>
45 using support::absolutePath;
46 using support::ascii_lowercase;
47 using support::changeExtension;
48 using support::contains;
50 using support::DocFileName;
51 using support::FileName;
52 using support::FileNameList;
53 using support::findtexfile;
54 using support::isValidLaTeXFilename;
55 using support::latex_path;
57 using support::makeAbsPath;
58 using support::makeRelPath;
59 using support::prefixIs;
60 using support::removeExtension;
64 using support::tokenPos;
66 using support::lowercase;
68 namespace Alert = frontend::Alert;
69 namespace os = support::os;
80 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
81 : InsetCommand(p, "bibtex")
85 CommandInfo const * InsetBibtex::findInfo(std::string const & /* cmdName */)
87 static const char * const paramnames[] =
88 {"options", "btprint", "bibfiles", ""};
89 static const bool isoptional[] = {true, true, false};
90 static const CommandInfo info = {3, paramnames, isoptional};
95 Inset * InsetBibtex::clone() const
97 return new InsetBibtex(*this);
101 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
103 switch (cmd.action) {
105 case LFUN_INSET_MODIFY: {
106 InsetCommandParams p(BIBTEX_CODE);
108 if (!InsetCommandMailer::string2params("bibtex",
109 to_utf8(cmd.argument()), p)) {
113 } catch (support::ExceptionMessage const & message) {
114 if (message.type_ == support::WarningException) {
115 Alert::warning(message.title_, message.details_);
122 cur.buffer().updateBibfilesCache();
127 InsetCommand::doDispatch(cur, cmd);
133 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
135 return _("BibTeX Generated Bibliography");
141 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
142 string const & name, string const & ext)
144 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
145 if (absolutePath(name) || !FileName(fname + ext).isReadableFile())
151 return to_utf8(makeRelPath(from_utf8(fname),
152 from_utf8(buffer.masterBuffer()->filePath())));
158 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
159 OutputParams const & runparams) const
161 // the sequence of the commands:
162 // 1. \bibliographystyle{style}
163 // 2. \addcontentsline{...} - if option bibtotoc set
164 // 3. \bibliography{database}
165 // and with bibtopic:
166 // 1. \bibliographystyle{style}
167 // 2. \begin{btSect}{database}
168 // 3. \btPrint{Cited|NotCited|All}
172 // If we are processing the LaTeX file in a temp directory then
173 // copy the .bib databases to this temp directory, mangling their
174 // names in the process. Store this mangled name in the list of
176 // (We need to do all this because BibTeX *really*, *really*
177 // can't handle "files with spaces" and Windows users tend to
178 // use such filenames.)
179 // Otherwise, store the (maybe absolute) path to the original,
180 // unmangled database name.
181 typedef boost::char_separator<char_type> Separator;
182 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
184 Separator const separator(from_ascii(",").c_str());
185 // The tokenizer must not be called with temporary strings, since
186 // it does not make a copy and uses iterators of the string further
187 // down. getParam returns a reference, so this is OK.
188 Tokenizer const tokens(getParam("bibfiles"), separator);
189 Tokenizer::const_iterator const begin = tokens.begin();
190 Tokenizer::const_iterator const end = tokens.end();
192 odocstringstream dbs;
193 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
194 docstring const input = trim(*it);
196 string utf8input = to_utf8(input);
198 normalizeName(buffer, runparams, utf8input, ".bib");
199 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
200 bool const not_from_texmf = try_in_file.isReadableFile();
202 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
205 // mangledFilename() needs the extension
206 DocFileName const in_file = DocFileName(try_in_file);
207 database = removeExtension(in_file.mangledFilename());
208 FileName const out_file = makeAbsPath(database + ".bib",
209 buffer.masterBuffer()->temppath());
211 bool const success = copy(in_file, out_file);
213 lyxerr << "Failed to copy '" << in_file
214 << "' to '" << out_file << "'"
217 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
218 !isValidLaTeXFilename(database)) {
219 frontend::Alert::warning(_("Invalid filename"),
220 _("The following filename is likely to cause trouble "
221 "when running the exported file through LaTeX: ") +
222 from_utf8(database));
228 dbs << from_utf8(latex_path(database));
230 docstring const db_out = dbs.str();
232 // Post this warning only once.
233 static bool warned_about_spaces = false;
234 if (!warned_about_spaces &&
235 runparams.nice && db_out.find(' ') != docstring::npos) {
236 warned_about_spaces = true;
238 Alert::warning(_("Export Warning!"),
239 _("There are spaces in the paths to your BibTeX databases.\n"
240 "BibTeX will be unable to find them."));
244 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
246 if (prefixIs(style, "bibtotoc")) {
247 bibtotoc = "bibtotoc";
248 if (contains(style, ','))
249 style = split(style, bibtotoc, ',');
255 if (!style.empty()) {
256 string base = normalizeName(buffer, runparams, style, ".bst");
257 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
258 bool const not_from_texmf = try_in_file.isReadableFile();
259 // If this style does not come from texmf and we are not
260 // exporting to .tex copy it to the tmp directory.
261 // This prevents problems with spaces and 8bit charcaters
263 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
265 // use new style name
266 DocFileName const in_file = DocFileName(try_in_file);
267 base = removeExtension(in_file.mangledFilename());
268 FileName const out_file(makeAbsPath(base + ".bst",
269 buffer.masterBuffer()->temppath()));
270 bool const success = copy(in_file, out_file);
272 lyxerr << "Failed to copy '" << in_file
273 << "' to '" << out_file << "'"
278 os << "\\bibliographystyle{"
279 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
284 // Post this warning only once.
285 static bool warned_about_bst_spaces = false;
286 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
287 warned_about_bst_spaces = true;
288 Alert::warning(_("Export Warning!"),
289 _("There are spaces in the path to your BibTeX style file.\n"
290 "BibTeX will be unable to find it."));
293 if (!db_out.empty() && buffer.params().use_bibtopic){
294 os << "\\begin{btSect}{" << db_out << "}\n";
295 docstring btprint = getParam("btprint");
298 btprint = from_ascii("btPrintCited");
299 os << "\\" << btprint << "\n"
300 << "\\end{btSect}\n";
305 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
306 // maybe a problem when a textclass has no "art" as
307 // part of its name, because it's than book.
308 // For the "official" lyx-layouts it's no problem to support
310 if (!contains(buffer.params().getTextClass().name(),
312 if (buffer.params().sides == OneSide) {
317 os << "\\cleardoublepage";
321 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
325 os << "\\addcontentsline{toc}{section}{\\refname}";
329 if (!db_out.empty() && !buffer.params().use_bibtopic){
330 os << "\\bibliography{" << db_out << "}\n";
338 FileNameList const InsetBibtex::getFiles(Buffer const & buffer) const
340 FileName path(buffer.filePath());
341 support::PathChanger p(path);
347 string bibfiles = to_utf8(getParam("bibfiles"));
348 bibfiles = split(bibfiles, tmp, ',');
349 while (!tmp.empty()) {
350 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
351 LYXERR(Debug::LATEX, "Bibfile: " << file);
353 // If we didn't find a matching file name just fail silently
357 // Get next file name
358 bibfiles = split(bibfiles, tmp, ',');
366 // methods for parsing bibtex files
368 typedef map<docstring, docstring> VarMap;
370 /// remove whitespace characters, optionally a single comma,
371 /// and further whitespace characters from the stream.
372 /// @return true if a comma was found, false otherwise
374 bool removeWSAndComma(idocfstream & ifs) {
383 } while (ifs && isSpace(ch));
396 } while (ifs && isSpace(ch));
411 /// remove whitespace characters, read characer sequence
412 /// not containing whitespace characters or characters in
413 /// delimChars, and remove further whitespace characters.
415 /// @return true if a string of length > 0 could be read.
417 bool readTypeOrKey(docstring & val, idocfstream & ifs,
418 docstring const & delimChars, docstring const &illegalChars,
431 } while (ifs && isSpace(ch));
437 bool legalChar = true;
438 while (ifs && !isSpace(ch) &&
439 delimChars.find(ch) == docstring::npos &&
440 (legalChar = (illegalChars.find(ch) == docstring::npos))
443 if (chCase == makeLowerCase)
444 val += lowercase(ch);
456 while (ifs && isSpace(ch)) {
464 return val.length() > 0;
467 /// read subsequent bibtex values that are delimited with a #-character.
468 /// Concatenate all parts and replace names with the associated string in
469 /// the variable strings.
470 /// @return true if reading was successfull (all single parts were delimited
472 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
485 } while (ifs && isSpace(ch));
490 // check for field type
493 // read integer value
497 } while (ifs && isDigit(ch));
502 } else if (ch == '"' || ch == '{') {
504 char_type delim = ch == '"' ? '"': '}';
509 } while (ifs && isSpace(ch));
514 //We now have the first non-whitespace character
515 //We'll collapse adjacent whitespace.
516 bool lastWasWhiteSpace = false;
518 // inside this delimited text braces must match.
519 // Thus we can have a closing delimiter only
520 // when nestLevel == 0
523 while (ifs && (nestLevel > 0 || ch != delim)) {
525 lastWasWhiteSpace = true;
529 //We output the space only after we stop getting
530 //whitespace so as not to output any whitespace
531 //at the end of the value.
532 if (lastWasWhiteSpace) {
533 lastWasWhiteSpace = false;
539 // update nesting level
546 if (nestLevel < 0) return false;
563 // reading a string name
566 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
567 strName += lowercase(ch);
574 // replace the string with its assigned value or
575 // discard it if it's not assigned
576 if (strName.length()) {
577 VarMap::const_iterator pos = strings.find(strName);
578 if (pos != strings.end()) {
585 while (ifs && isSpace(ch)) {
592 // continue reading next value on concatenate with '#'
602 // This method returns a comma separated list of Bibtex entries
603 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
604 BiblioInfo & keylist, InsetIterator const & /*di*/) const
606 FileNameList const files = getFiles(buffer);
607 for (vector<FileName>::const_iterator it = files.begin();
608 it != files.end(); ++ it) {
609 // This bibtex parser is a first step to parse bibtex files
612 // - it reads the whole bibtex entry and does a syntax check
613 // (matching delimiters, missing commas,...
614 // - it recovers from errors starting with the next @-character
615 // - it reads @string definitions and replaces them in the
617 // - it accepts more characters in keys or value names than
620 // Officially bibtex does only support ASCII, but in practice
621 // you can use the encoding of the main document as long as
622 // some elements like keys and names are pure ASCII. Therefore
623 // we convert the file from the buffer encoding.
624 // We don't restrict keys to ASCII in LyX, since our own
625 // InsetBibitem can generate non-ASCII keys, and nonstandard
626 // 8bit clean bibtex forks exist.
628 idocfstream ifs(it->toFilesystemEncoding().c_str(),
630 buffer.params().encoding().iconvName());
646 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
647 docstring(), makeLowerCase) || !ifs)
650 if (entryType == from_ascii("comment")) {
652 ifs.ignore(std::numeric_limits<int>::max(), '\n');
660 if ((ch != '(') && (ch != '{')) {
661 // invalid entry delimiter
667 if (entryType == from_ascii("string")) {
669 // read string and add it to the strings map
670 // (or replace it's old value)
674 if (!readTypeOrKey(name, ifs, from_ascii("="),
675 from_ascii("#{}(),"), makeLowerCase) || !ifs)
678 // next char must be an equal sign
680 if (!ifs || ch != '=')
683 if (!readValue(value, ifs, strings))
686 strings[name] = value;
688 } else if (entryType == from_ascii("preamble")) {
690 // preamble definitions are discarded.
691 // can they be of any use in lyx?
694 if (!readValue(value, ifs, strings))
699 // Citation entry. Try to read the key.
702 if (!readTypeOrKey(key, ifs, from_ascii(","),
703 from_ascii("}"), keepCase) || !ifs)
706 /////////////////////////////////////////////
707 // now we have a key, so we will add an entry
708 // (even if it's empty, as bibtex does)
710 // we now read the field = value pairs.
711 // all items must be separated by a comma. If
712 // it is missing the scanning of this entry is
713 // stopped and the next is searched.
717 docstring commaNewline;
719 BibTeXInfo keyvalmap;
720 keyvalmap.entryType = 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.fieldNames.insert(name);
747 readNext = removeWSAndComma(ifs);
751 keylist.entryTypes.insert(entryType);
752 keyvalmap.allData = data;
753 keyvalmap.isBibTeX = true;
754 keyvalmap.bibKey = key;
755 keylist[key] = keyvalmap;
758 } //< for loop over files
763 bool InsetBibtex::addDatabase(string const & db)
766 string bibfiles(to_utf8(getParam("bibfiles")));
767 if (tokenPos(bibfiles, ',', db) == -1) {
768 if (!bibfiles.empty())
770 setParam("bibfiles", from_utf8(bibfiles + db));
777 bool InsetBibtex::delDatabase(string const & db)
780 string bibfiles(to_utf8(getParam("bibfiles")));
781 if (contains(bibfiles, db)) {
782 int const n = tokenPos(bibfiles, ',', db);
785 // this is not the first database
786 string tmp = ',' + bd;
787 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
789 // this is the first (or only) database
790 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
798 void InsetBibtex::validate(LaTeXFeatures & features) const
800 if (features.bufferParams().use_bibtopic)
801 features.require("bibtopic");