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/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxlib.h"
35 #include "support/os.h"
36 #include "support/Path.h"
37 #include "support/textutils.h"
39 #include <boost/tokenizer.hpp>
44 using support::absolutePath;
45 using support::ascii_lowercase;
46 using support::changeExtension;
47 using support::contains;
49 using support::DocFileName;
50 using support::FileName;
51 using support::findtexfile;
52 using support::isValidLaTeXFilename;
53 using support::latex_path;
55 using support::makeAbsPath;
56 using support::makeRelPath;
57 using support::prefixIs;
58 using support::removeExtension;
62 using support::tokenPos;
64 using support::lowercase;
66 namespace Alert = frontend::Alert;
67 namespace os = support::os;
78 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
79 : InsetCommand(p, "bibtex")
83 CommandInfo const * InsetBibtex::findInfo(std::string const & /* cmdName */)
85 static const char * const paramnames[] =
86 {"options", "btprint", "bibfiles", ""};
87 static const bool isoptional[] = {true, true, false};
88 static const CommandInfo info = {3, paramnames, isoptional};
93 Inset * InsetBibtex::clone() const
95 return new InsetBibtex(*this);
99 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
101 switch (cmd.action) {
103 case LFUN_INSET_MODIFY: {
104 InsetCommandParams p(BIBTEX_CODE);
106 if (!InsetCommandMailer::string2params("bibtex",
107 to_utf8(cmd.argument()), p)) {
111 } catch (support::ExceptionMessage const & message) {
112 if (message.type_ == support::WarningException) {
113 Alert::warning(message.title_, message.details_);
120 cur.buffer().updateBibfilesCache();
125 InsetCommand::doDispatch(cur, cmd);
131 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
133 return _("BibTeX Generated Bibliography");
139 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
140 string const & name, string const & ext)
142 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
143 if (absolutePath(name) || !FileName(fname + ext).isReadableFile())
149 return to_utf8(makeRelPath(from_utf8(fname),
150 from_utf8(buffer.masterBuffer()->filePath())));
156 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
157 OutputParams const & runparams) const
159 // the sequence of the commands:
160 // 1. \bibliographystyle{style}
161 // 2. \addcontentsline{...} - if option bibtotoc set
162 // 3. \bibliography{database}
163 // and with bibtopic:
164 // 1. \bibliographystyle{style}
165 // 2. \begin{btSect}{database}
166 // 3. \btPrint{Cited|NotCited|All}
170 // If we are processing the LaTeX file in a temp directory then
171 // copy the .bib databases to this temp directory, mangling their
172 // names in the process. Store this mangled name in the list of
174 // (We need to do all this because BibTeX *really*, *really*
175 // can't handle "files with spaces" and Windows users tend to
176 // use such filenames.)
177 // Otherwise, store the (maybe absolute) path to the original,
178 // unmangled database name.
179 typedef boost::char_separator<char_type> Separator;
180 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
182 Separator const separator(from_ascii(",").c_str());
183 // The tokenizer must not be called with temporary strings, since
184 // it does not make a copy and uses iterators of the string further
185 // down. getParam returns a reference, so this is OK.
186 Tokenizer const tokens(getParam("bibfiles"), separator);
187 Tokenizer::const_iterator const begin = tokens.begin();
188 Tokenizer::const_iterator const end = tokens.end();
190 odocstringstream dbs;
191 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
192 docstring const input = trim(*it);
194 string utf8input = to_utf8(input);
196 normalizeName(buffer, runparams, utf8input, ".bib");
197 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
198 bool const not_from_texmf = try_in_file.isReadableFile();
200 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
203 // mangledFilename() needs the extension
204 DocFileName const in_file = DocFileName(try_in_file);
205 database = removeExtension(in_file.mangledFilename());
206 FileName const out_file = makeAbsPath(database + ".bib",
207 buffer.masterBuffer()->temppath());
209 bool const success = copy(in_file, out_file);
211 lyxerr << "Failed to copy '" << in_file
212 << "' to '" << out_file << "'"
215 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
216 !isValidLaTeXFilename(database)) {
217 frontend::Alert::warning(_("Invalid filename"),
218 _("The following filename is likely to cause trouble "
219 "when running the exported file through LaTeX: ") +
220 from_utf8(database));
226 dbs << from_utf8(latex_path(database));
228 docstring const db_out = dbs.str();
230 // Post this warning only once.
231 static bool warned_about_spaces = false;
232 if (!warned_about_spaces &&
233 runparams.nice && db_out.find(' ') != docstring::npos) {
234 warned_about_spaces = true;
236 Alert::warning(_("Export Warning!"),
237 _("There are spaces in the paths to your BibTeX databases.\n"
238 "BibTeX will be unable to find them."));
242 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
244 if (prefixIs(style, "bibtotoc")) {
245 bibtotoc = "bibtotoc";
246 if (contains(style, ','))
247 style = split(style, bibtotoc, ',');
253 if (!style.empty()) {
254 string base = normalizeName(buffer, runparams, style, ".bst");
255 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
256 bool const not_from_texmf = try_in_file.isReadableFile();
257 // If this style does not come from texmf and we are not
258 // exporting to .tex copy it to the tmp directory.
259 // This prevents problems with spaces and 8bit charcaters
261 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
263 // use new style name
264 DocFileName const in_file = DocFileName(try_in_file);
265 base = removeExtension(in_file.mangledFilename());
266 FileName const out_file(makeAbsPath(base + ".bst",
267 buffer.masterBuffer()->temppath()));
268 bool const success = copy(in_file, out_file);
270 lyxerr << "Failed to copy '" << in_file
271 << "' to '" << out_file << "'"
276 os << "\\bibliographystyle{"
277 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
282 // Post this warning only once.
283 static bool warned_about_bst_spaces = false;
284 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
285 warned_about_bst_spaces = true;
286 Alert::warning(_("Export Warning!"),
287 _("There are spaces in the path to your BibTeX style file.\n"
288 "BibTeX will be unable to find it."));
291 if (!db_out.empty() && buffer.params().use_bibtopic){
292 os << "\\begin{btSect}{" << db_out << "}\n";
293 docstring btprint = getParam("btprint");
296 btprint = from_ascii("btPrintCited");
297 os << "\\" << btprint << "\n"
298 << "\\end{btSect}\n";
303 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
304 // maybe a problem when a textclass has no "art" as
305 // part of its name, because it's than book.
306 // For the "official" lyx-layouts it's no problem to support
308 if (!contains(buffer.params().getTextClass().name(),
310 if (buffer.params().sides == OneSide) {
315 os << "\\cleardoublepage";
319 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
323 os << "\\addcontentsline{toc}{section}{\\refname}";
327 if (!db_out.empty() && !buffer.params().use_bibtopic){
328 os << "\\bibliography{" << db_out << "}\n";
336 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
338 FileName path(buffer.filePath());
339 support::PathChanger p(path);
341 vector<FileName> vec;
345 string bibfiles = to_utf8(getParam("bibfiles"));
346 bibfiles = split(bibfiles, tmp, ',');
347 while (!tmp.empty()) {
348 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
349 LYXERR(Debug::LATEX, "Bibfile: " << file);
351 // If we didn't find a matching file name just fail silently
355 // Get next file name
356 bibfiles = split(bibfiles, tmp, ',');
364 // methods for parsing bibtex files
366 typedef map<docstring, docstring> VarMap;
368 /// remove whitespace characters, optionally a single comma,
369 /// and further whitespace characters from the stream.
370 /// @return true if a comma was found, false otherwise
372 bool removeWSAndComma(idocfstream & ifs) {
381 } while (ifs && isSpace(ch));
394 } while (ifs && isSpace(ch));
409 /// remove whitespace characters, read characer sequence
410 /// not containing whitespace characters or characters in
411 /// delimChars, and remove further whitespace characters.
413 /// @return true if a string of length > 0 could be read.
415 bool readTypeOrKey(docstring & val, idocfstream & ifs,
416 docstring const & delimChars, docstring const &illegalChars,
429 } while (ifs && isSpace(ch));
435 bool legalChar = true;
436 while (ifs && !isSpace(ch) &&
437 delimChars.find(ch) == docstring::npos &&
438 (legalChar = (illegalChars.find(ch) == docstring::npos))
441 if (chCase == makeLowerCase)
442 val += lowercase(ch);
454 while (ifs && isSpace(ch)) {
462 return val.length() > 0;
465 /// read subsequent bibtex values that are delimited with a #-character.
466 /// Concatenate all parts and replace names with the associated string in
467 /// the variable strings.
468 /// @return true if reading was successfull (all single parts were delimited
470 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
483 } while (ifs && isSpace(ch));
488 // check for field type
491 // read integer value
495 } while (ifs && isDigit(ch));
500 } else if (ch == '"' || ch == '{') {
502 char_type delim = ch == '"' ? '"': '}';
507 } while (ifs && isSpace(ch));
512 //We now have the first non-whitespace character
513 //We'll collapse adjacent whitespace.
514 bool lastWasWhiteSpace = false;
516 // inside this delimited text braces must match.
517 // Thus we can have a closing delimiter only
518 // when nestLevel == 0
521 while (ifs && (nestLevel > 0 || ch != delim)) {
523 lastWasWhiteSpace = true;
527 //We output the space only after we stop getting
528 //whitespace so as not to output any whitespace
529 //at the end of the value.
530 if (lastWasWhiteSpace) {
531 lastWasWhiteSpace = false;
537 // update nesting level
544 if (nestLevel < 0) return false;
561 // reading a string name
564 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
565 strName += lowercase(ch);
572 // replace the string with its assigned value or
573 // discard it if it's not assigned
574 if (strName.length()) {
575 VarMap::const_iterator pos = strings.find(strName);
576 if (pos != strings.end()) {
583 while (ifs && isSpace(ch)) {
590 // continue reading next value on concatenate with '#'
600 // This method returns a comma separated list of Bibtex entries
601 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
602 BiblioInfo & keylist, InsetIterator const & /*di*/) const
604 vector<FileName> const files = getFiles(buffer);
605 for (vector<FileName>::const_iterator it = files.begin();
606 it != files.end(); ++ it) {
607 // This bibtex parser is a first step to parse bibtex files
610 // - it reads the whole bibtex entry and does a syntax check
611 // (matching delimiters, missing commas,...
612 // - it recovers from errors starting with the next @-character
613 // - it reads @string definitions and replaces them in the
615 // - it accepts more characters in keys or value names than
618 // Officially bibtex does only support ASCII, but in practice
619 // you can use the encoding of the main document as long as
620 // some elements like keys and names are pure ASCII. Therefore
621 // we convert the file from the buffer encoding.
622 // We don't restrict keys to ASCII in LyX, since our own
623 // InsetBibitem can generate non-ASCII keys, and nonstandard
624 // 8bit clean bibtex forks exist.
626 idocfstream ifs(it->toFilesystemEncoding().c_str(),
628 buffer.params().encoding().iconvName());
644 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
645 docstring(), makeLowerCase) || !ifs)
648 if (entryType == from_ascii("comment")) {
650 ifs.ignore(std::numeric_limits<int>::max(), '\n');
658 if ((ch != '(') && (ch != '{')) {
659 // invalid entry delimiter
665 if (entryType == from_ascii("string")) {
667 // read string and add it to the strings map
668 // (or replace it's old value)
672 if (!readTypeOrKey(name, ifs, from_ascii("="),
673 from_ascii("#{}(),"), makeLowerCase) || !ifs)
676 // next char must be an equal sign
678 if (!ifs || ch != '=')
681 if (!readValue(value, ifs, strings))
684 strings[name] = value;
686 } else if (entryType == from_ascii("preamble")) {
688 // preamble definitions are discarded.
689 // can they be of any use in lyx?
692 if (!readValue(value, ifs, strings))
697 // Citation entry. Try to read the key.
700 if (!readTypeOrKey(key, ifs, from_ascii(","),
701 from_ascii("}"), keepCase) || !ifs)
704 /////////////////////////////////////////////
705 // now we have a key, so we will add an entry
706 // (even if it's empty, as bibtex does)
708 // we now read the field = value pairs.
709 // all items must be separated by a comma. If
710 // it is missing the scanning of this entry is
711 // stopped and the next is searched.
715 docstring commaNewline;
717 BibTeXInfo keyvalmap;
718 keyvalmap.entryType = entryType;
720 bool readNext = removeWSAndComma(ifs);
722 while (ifs && readNext) {
725 if (!readTypeOrKey(name, ifs, from_ascii("="),
726 from_ascii("{}(),"), makeLowerCase) || !ifs)
729 // next char must be an equal sign
739 if (!readValue(value, ifs, strings))
742 keyvalmap[name] = value;
743 data += "\n\n" + value;
744 keylist.fieldNames.insert(name);
745 readNext = removeWSAndComma(ifs);
749 keylist.entryTypes.insert(entryType);
750 keyvalmap.allData = data;
751 keyvalmap.isBibTeX = true;
752 keyvalmap.bibKey = key;
753 keylist[key] = keyvalmap;
756 } //< for loop over files
761 bool InsetBibtex::addDatabase(string const & db)
764 string bibfiles(to_utf8(getParam("bibfiles")));
765 if (tokenPos(bibfiles, ',', db) == -1) {
766 if (!bibfiles.empty())
768 setParam("bibfiles", from_utf8(bibfiles + db));
775 bool InsetBibtex::delDatabase(string const & db)
778 string bibfiles(to_utf8(getParam("bibfiles")));
779 if (contains(bibfiles, db)) {
780 int const n = tokenPos(bibfiles, ',', db);
783 // this is not the first database
784 string tmp = ',' + bd;
785 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
787 // this is the first (or only) database
788 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
796 void InsetBibtex::validate(LaTeXFeatures & features) const
798 if (features.bufferParams().use_bibtopic)
799 features.require("bibtopic");