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/os.h"
36 #include "support/Path.h"
37 #include "support/textutils.h"
39 #include <boost/tokenizer.hpp>
42 using namespace lyx::support;
46 namespace Alert = frontend::Alert;
47 namespace os = support::os;
50 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
51 : InsetCommand(p, "bibtex")
55 CommandInfo const * InsetBibtex::findInfo(string const & /* cmdName */)
57 static const char * const paramnames[] =
58 {"options", "btprint", "bibfiles", ""};
59 static const bool isoptional[] = {true, true, false};
60 static const CommandInfo info = {3, paramnames, isoptional};
65 Inset * InsetBibtex::clone() const
67 return new InsetBibtex(*this);
71 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
75 case LFUN_INSET_MODIFY: {
76 InsetCommandParams p(BIBTEX_CODE);
78 if (!InsetCommandMailer::string2params("bibtex",
79 to_utf8(cmd.argument()), p)) {
83 } catch (ExceptionMessage const & message) {
84 if (message.type_ == WarningException) {
85 Alert::warning(message.title_, message.details_);
92 cur.buffer().updateBibfilesCache();
97 InsetCommand::doDispatch(cur, cmd);
103 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
105 return _("BibTeX Generated Bibliography");
111 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
112 string const & name, string const & ext)
114 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
115 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
121 return to_utf8(makeRelPath(from_utf8(fname),
122 from_utf8(buffer.masterBuffer()->filePath())));
128 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
129 OutputParams const & runparams) const
131 // the sequence of the commands:
132 // 1. \bibliographystyle{style}
133 // 2. \addcontentsline{...} - if option bibtotoc set
134 // 3. \bibliography{database}
135 // and with bibtopic:
136 // 1. \bibliographystyle{style}
137 // 2. \begin{btSect}{database}
138 // 3. \btPrint{Cited|NotCited|All}
142 // If we are processing the LaTeX file in a temp directory then
143 // copy the .bib databases to this temp directory, mangling their
144 // names in the process. Store this mangled name in the list of
146 // (We need to do all this because BibTeX *really*, *really*
147 // can't handle "files with spaces" and Windows users tend to
148 // use such filenames.)
149 // Otherwise, store the (maybe absolute) path to the original,
150 // unmangled database name.
151 typedef boost::char_separator<char_type> Separator;
152 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
154 Separator const separator(from_ascii(",").c_str());
155 // The tokenizer must not be called with temporary strings, since
156 // it does not make a copy and uses iterators of the string further
157 // down. getParam returns a reference, so this is OK.
158 Tokenizer const tokens(getParam("bibfiles"), separator);
159 Tokenizer::const_iterator const begin = tokens.begin();
160 Tokenizer::const_iterator const end = tokens.end();
162 odocstringstream dbs;
163 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
164 docstring const input = trim(*it);
166 string utf8input = to_utf8(input);
168 normalizeName(buffer, runparams, utf8input, ".bib");
169 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
170 bool const not_from_texmf = try_in_file.isReadableFile();
172 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
175 // mangledFilename() needs the extension
176 DocFileName const in_file = DocFileName(try_in_file);
177 database = removeExtension(in_file.mangledFilename());
178 FileName const out_file = makeAbsPath(database + ".bib",
179 buffer.masterBuffer()->temppath());
181 bool const success = in_file.copyTo(out_file);
183 lyxerr << "Failed to copy '" << in_file
184 << "' to '" << out_file << "'"
187 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
188 !isValidLaTeXFilename(database)) {
189 frontend::Alert::warning(_("Invalid filename"),
190 _("The following filename is likely to cause trouble "
191 "when running the exported file through LaTeX: ") +
192 from_utf8(database));
198 dbs << from_utf8(latex_path(database));
200 docstring const db_out = dbs.str();
202 // Post this warning only once.
203 static bool warned_about_spaces = false;
204 if (!warned_about_spaces &&
205 runparams.nice && db_out.find(' ') != docstring::npos) {
206 warned_about_spaces = true;
208 Alert::warning(_("Export Warning!"),
209 _("There are spaces in the paths to your BibTeX databases.\n"
210 "BibTeX will be unable to find them."));
214 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
216 if (prefixIs(style, "bibtotoc")) {
217 bibtotoc = "bibtotoc";
218 if (contains(style, ','))
219 style = split(style, bibtotoc, ',');
225 if (!style.empty()) {
226 string base = normalizeName(buffer, runparams, style, ".bst");
227 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
228 bool const not_from_texmf = try_in_file.isReadableFile();
229 // If this style does not come from texmf and we are not
230 // exporting to .tex copy it to the tmp directory.
231 // This prevents problems with spaces and 8bit charcaters
233 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
235 // use new style name
236 DocFileName const in_file = DocFileName(try_in_file);
237 base = removeExtension(in_file.mangledFilename());
238 FileName const out_file(makeAbsPath(base + ".bst",
239 buffer.masterBuffer()->temppath()));
240 bool const success = in_file.copyTo(out_file);
242 lyxerr << "Failed to copy '" << in_file
243 << "' to '" << out_file << "'"
248 os << "\\bibliographystyle{"
249 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
254 // Post this warning only once.
255 static bool warned_about_bst_spaces = false;
256 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
257 warned_about_bst_spaces = true;
258 Alert::warning(_("Export Warning!"),
259 _("There are spaces in the path to your BibTeX style file.\n"
260 "BibTeX will be unable to find it."));
263 if (!db_out.empty() && buffer.params().use_bibtopic){
264 os << "\\begin{btSect}{" << db_out << "}\n";
265 docstring btprint = getParam("btprint");
268 btprint = from_ascii("btPrintCited");
269 os << "\\" << btprint << "\n"
270 << "\\end{btSect}\n";
275 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
276 // maybe a problem when a textclass has no "art" as
277 // part of its name, because it's than book.
278 // For the "official" lyx-layouts it's no problem to support
280 if (!contains(buffer.params().getTextClass().name(),
282 if (buffer.params().sides == OneSide) {
287 os << "\\cleardoublepage";
291 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
295 os << "\\addcontentsline{toc}{section}{\\refname}";
299 if (!db_out.empty() && !buffer.params().use_bibtopic){
300 os << "\\bibliography{" << db_out << "}\n";
308 FileNameList const InsetBibtex::getFiles(Buffer const & buffer) const
310 FileName path(buffer.filePath());
317 string bibfiles = to_utf8(getParam("bibfiles"));
318 bibfiles = split(bibfiles, tmp, ',');
319 while (!tmp.empty()) {
320 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
321 LYXERR(Debug::LATEX, "Bibfile: " << file);
323 // If we didn't find a matching file name just fail silently
327 // Get next file name
328 bibfiles = split(bibfiles, tmp, ',');
336 // methods for parsing bibtex files
338 typedef map<docstring, docstring> VarMap;
340 /// remove whitespace characters, optionally a single comma,
341 /// and further whitespace characters from the stream.
342 /// @return true if a comma was found, false otherwise
344 bool removeWSAndComma(idocfstream & ifs) {
353 } while (ifs && isSpace(ch));
366 } while (ifs && isSpace(ch));
381 /// remove whitespace characters, read characer sequence
382 /// not containing whitespace characters or characters in
383 /// delimChars, and remove further whitespace characters.
385 /// @return true if a string of length > 0 could be read.
387 bool readTypeOrKey(docstring & val, idocfstream & ifs,
388 docstring const & delimChars, docstring const &illegalChars,
401 } while (ifs && isSpace(ch));
407 bool legalChar = true;
408 while (ifs && !isSpace(ch) &&
409 delimChars.find(ch) == docstring::npos &&
410 (legalChar = (illegalChars.find(ch) == docstring::npos))
413 if (chCase == makeLowerCase)
414 val += lowercase(ch);
426 while (ifs && isSpace(ch)) {
434 return val.length() > 0;
437 /// read subsequent bibtex values that are delimited with a #-character.
438 /// Concatenate all parts and replace names with the associated string in
439 /// the variable strings.
440 /// @return true if reading was successfull (all single parts were delimited
442 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
455 } while (ifs && isSpace(ch));
460 // check for field type
463 // read integer value
467 } while (ifs && isDigit(ch));
472 } else if (ch == '"' || ch == '{') {
474 char_type delim = ch == '"' ? '"': '}';
479 } while (ifs && isSpace(ch));
484 //We now have the first non-whitespace character
485 //We'll collapse adjacent whitespace.
486 bool lastWasWhiteSpace = false;
488 // inside this delimited text braces must match.
489 // Thus we can have a closing delimiter only
490 // when nestLevel == 0
493 while (ifs && (nestLevel > 0 || ch != delim)) {
495 lastWasWhiteSpace = true;
499 //We output the space only after we stop getting
500 //whitespace so as not to output any whitespace
501 //at the end of the value.
502 if (lastWasWhiteSpace) {
503 lastWasWhiteSpace = false;
509 // update nesting level
516 if (nestLevel < 0) return false;
533 // reading a string name
536 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
537 strName += lowercase(ch);
544 // replace the string with its assigned value or
545 // discard it if it's not assigned
546 if (strName.length()) {
547 VarMap::const_iterator pos = strings.find(strName);
548 if (pos != strings.end()) {
555 while (ifs && isSpace(ch)) {
562 // continue reading next value on concatenate with '#'
572 // This method returns a comma separated list of Bibtex entries
573 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
574 BiblioInfo & keylist, InsetIterator const & /*di*/) const
576 FileNameList const files = getFiles(buffer);
577 for (vector<FileName>::const_iterator it = files.begin();
578 it != files.end(); ++ it) {
579 // This bibtex parser is a first step to parse bibtex files
582 // - it reads the whole bibtex entry and does a syntax check
583 // (matching delimiters, missing commas,...
584 // - it recovers from errors starting with the next @-character
585 // - it reads @string definitions and replaces them in the
587 // - it accepts more characters in keys or value names than
590 // Officially bibtex does only support ASCII, but in practice
591 // you can use the encoding of the main document as long as
592 // some elements like keys and names are pure ASCII. Therefore
593 // we convert the file from the buffer encoding.
594 // We don't restrict keys to ASCII in LyX, since our own
595 // InsetBibitem can generate non-ASCII keys, and nonstandard
596 // 8bit clean bibtex forks exist.
598 idocfstream ifs(it->toFilesystemEncoding().c_str(),
600 buffer.params().encoding().iconvName());
616 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
617 docstring(), makeLowerCase) || !ifs)
620 if (entryType == from_ascii("comment")) {
622 ifs.ignore(numeric_limits<int>::max(), '\n');
630 if ((ch != '(') && (ch != '{')) {
631 // invalid entry delimiter
637 if (entryType == from_ascii("string")) {
639 // read string and add it to the strings map
640 // (or replace it's old value)
644 if (!readTypeOrKey(name, ifs, from_ascii("="),
645 from_ascii("#{}(),"), makeLowerCase) || !ifs)
648 // next char must be an equal sign
650 if (!ifs || ch != '=')
653 if (!readValue(value, ifs, strings))
656 strings[name] = value;
658 } else if (entryType == from_ascii("preamble")) {
660 // preamble definitions are discarded.
661 // can they be of any use in lyx?
664 if (!readValue(value, ifs, strings))
669 // Citation entry. Try to read the key.
672 if (!readTypeOrKey(key, ifs, from_ascii(","),
673 from_ascii("}"), keepCase) || !ifs)
676 /////////////////////////////////////////////
677 // now we have a key, so we will add an entry
678 // (even if it's empty, as bibtex does)
680 // we now read the field = value pairs.
681 // all items must be separated by a comma. If
682 // it is missing the scanning of this entry is
683 // stopped and the next is searched.
687 docstring commaNewline;
689 BibTeXInfo keyvalmap;
690 keyvalmap.entryType = entryType;
692 bool readNext = removeWSAndComma(ifs);
694 while (ifs && readNext) {
697 if (!readTypeOrKey(name, ifs, from_ascii("="),
698 from_ascii("{}(),"), makeLowerCase) || !ifs)
701 // next char must be an equal sign
711 if (!readValue(value, ifs, strings))
714 keyvalmap[name] = value;
715 data += "\n\n" + value;
716 keylist.fieldNames.insert(name);
717 readNext = removeWSAndComma(ifs);
721 keylist.entryTypes.insert(entryType);
722 keyvalmap.allData = data;
723 keyvalmap.isBibTeX = true;
724 keyvalmap.bibKey = key;
725 keylist[key] = keyvalmap;
728 } //< for loop over files
733 bool InsetBibtex::addDatabase(string const & db)
736 string bibfiles(to_utf8(getParam("bibfiles")));
737 if (tokenPos(bibfiles, ',', db) == -1) {
738 if (!bibfiles.empty())
740 setParam("bibfiles", from_utf8(bibfiles + db));
747 bool InsetBibtex::delDatabase(string const & db)
750 string bibfiles(to_utf8(getParam("bibfiles")));
751 if (contains(bibfiles, db)) {
752 int const n = tokenPos(bibfiles, ',', db);
755 // this is not the first database
756 string tmp = ',' + bd;
757 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
759 // this is the first (or only) database
760 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
768 void InsetBibtex::validate(LaTeXFeatures & features) const
770 if (features.bufferParams().use_bibtopic)
771 features.require("bibtopic");