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 docstring btprint = getParam("btprint");
301 if (btprint == "btPrintAll") {
302 os << "\\nocite{*}\n";
305 os << "\\bibliography{" << db_out << "}\n";
313 FileNameList const InsetBibtex::getFiles(Buffer const & buffer) const
315 FileName path(buffer.filePath());
322 string bibfiles = to_utf8(getParam("bibfiles"));
323 bibfiles = split(bibfiles, tmp, ',');
324 while (!tmp.empty()) {
325 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
326 LYXERR(Debug::LATEX, "Bibfile: " << file);
328 // If we didn't find a matching file name just fail silently
332 // Get next file name
333 bibfiles = split(bibfiles, tmp, ',');
341 // methods for parsing bibtex files
343 typedef map<docstring, docstring> VarMap;
345 /// remove whitespace characters, optionally a single comma,
346 /// and further whitespace characters from the stream.
347 /// @return true if a comma was found, false otherwise
349 bool removeWSAndComma(idocfstream & ifs) {
358 } while (ifs && isSpace(ch));
371 } while (ifs && isSpace(ch));
386 /// remove whitespace characters, read characer sequence
387 /// not containing whitespace characters or characters in
388 /// delimChars, and remove further whitespace characters.
390 /// @return true if a string of length > 0 could be read.
392 bool readTypeOrKey(docstring & val, idocfstream & ifs,
393 docstring const & delimChars, docstring const &illegalChars,
406 } while (ifs && isSpace(ch));
412 bool legalChar = true;
413 while (ifs && !isSpace(ch) &&
414 delimChars.find(ch) == docstring::npos &&
415 (legalChar = (illegalChars.find(ch) == docstring::npos))
418 if (chCase == makeLowerCase)
419 val += lowercase(ch);
431 while (ifs && isSpace(ch)) {
439 return val.length() > 0;
442 /// read subsequent bibtex values that are delimited with a #-character.
443 /// Concatenate all parts and replace names with the associated string in
444 /// the variable strings.
445 /// @return true if reading was successfull (all single parts were delimited
447 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
460 } while (ifs && isSpace(ch));
465 // check for field type
468 // read integer value
472 } while (ifs && isDigit(ch));
477 } else if (ch == '"' || ch == '{') {
479 char_type delim = ch == '"' ? '"': '}';
484 } while (ifs && isSpace(ch));
489 //We now have the first non-whitespace character
490 //We'll collapse adjacent whitespace.
491 bool lastWasWhiteSpace = false;
493 // inside this delimited text braces must match.
494 // Thus we can have a closing delimiter only
495 // when nestLevel == 0
498 while (ifs && (nestLevel > 0 || ch != delim)) {
500 lastWasWhiteSpace = true;
504 //We output the space only after we stop getting
505 //whitespace so as not to output any whitespace
506 //at the end of the value.
507 if (lastWasWhiteSpace) {
508 lastWasWhiteSpace = false;
514 // update nesting level
521 if (nestLevel < 0) return false;
538 // reading a string name
541 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
542 strName += lowercase(ch);
549 // replace the string with its assigned value or
550 // discard it if it's not assigned
551 if (strName.length()) {
552 VarMap::const_iterator pos = strings.find(strName);
553 if (pos != strings.end()) {
560 while (ifs && isSpace(ch)) {
567 // continue reading next value on concatenate with '#'
577 // This method returns a comma separated list of Bibtex entries
578 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
579 BiblioInfo & keylist, InsetIterator const & /*di*/) const
581 FileNameList const files = getFiles(buffer);
582 for (vector<FileName>::const_iterator it = files.begin();
583 it != files.end(); ++ it) {
584 // This bibtex parser is a first step to parse bibtex files
587 // - it reads the whole bibtex entry and does a syntax check
588 // (matching delimiters, missing commas,...
589 // - it recovers from errors starting with the next @-character
590 // - it reads @string definitions and replaces them in the
592 // - it accepts more characters in keys or value names than
595 // Officially bibtex does only support ASCII, but in practice
596 // you can use the encoding of the main document as long as
597 // some elements like keys and names are pure ASCII. Therefore
598 // we convert the file from the buffer encoding.
599 // We don't restrict keys to ASCII in LyX, since our own
600 // InsetBibitem can generate non-ASCII keys, and nonstandard
601 // 8bit clean bibtex forks exist.
603 idocfstream ifs(it->toFilesystemEncoding().c_str(),
605 buffer.params().encoding().iconvName());
621 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
622 docstring(), makeLowerCase) || !ifs)
625 if (entryType == from_ascii("comment")) {
627 ifs.ignore(numeric_limits<int>::max(), '\n');
635 if ((ch != '(') && (ch != '{')) {
636 // invalid entry delimiter
642 if (entryType == from_ascii("string")) {
644 // read string and add it to the strings map
645 // (or replace it's old value)
649 if (!readTypeOrKey(name, ifs, from_ascii("="),
650 from_ascii("#{}(),"), makeLowerCase) || !ifs)
653 // next char must be an equal sign
655 if (!ifs || ch != '=')
658 if (!readValue(value, ifs, strings))
661 strings[name] = value;
663 } else if (entryType == from_ascii("preamble")) {
665 // preamble definitions are discarded.
666 // can they be of any use in lyx?
669 if (!readValue(value, ifs, strings))
674 // Citation entry. Try to read the key.
677 if (!readTypeOrKey(key, ifs, from_ascii(","),
678 from_ascii("}"), keepCase) || !ifs)
681 /////////////////////////////////////////////
682 // now we have a key, so we will add an entry
683 // (even if it's empty, as bibtex does)
685 // we now read the field = value pairs.
686 // all items must be separated by a comma. If
687 // it is missing the scanning of this entry is
688 // stopped and the next is searched.
692 docstring commaNewline;
694 BibTeXInfo keyvalmap;
695 keyvalmap.entryType = entryType;
697 bool readNext = removeWSAndComma(ifs);
699 while (ifs && readNext) {
702 if (!readTypeOrKey(name, ifs, from_ascii("="),
703 from_ascii("{}(),"), makeLowerCase) || !ifs)
706 // next char must be an equal sign
716 if (!readValue(value, ifs, strings))
719 keyvalmap[name] = value;
720 data += "\n\n" + value;
721 keylist.fieldNames.insert(name);
722 readNext = removeWSAndComma(ifs);
726 keylist.entryTypes.insert(entryType);
727 keyvalmap.allData = data;
728 keyvalmap.isBibTeX = true;
729 keyvalmap.bibKey = key;
730 keylist[key] = keyvalmap;
733 } //< for loop over files
738 bool InsetBibtex::addDatabase(string const & db)
741 string bibfiles(to_utf8(getParam("bibfiles")));
742 if (tokenPos(bibfiles, ',', db) == -1) {
743 if (!bibfiles.empty())
745 setParam("bibfiles", from_utf8(bibfiles + db));
752 bool InsetBibtex::delDatabase(string const & db)
755 string bibfiles(to_utf8(getParam("bibfiles")));
756 if (contains(bibfiles, db)) {
757 int const n = tokenPos(bibfiles, ',', db);
760 // this is not the first database
761 string tmp = ',' + bd;
762 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
764 // this is the first (or only) database
765 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
773 void InsetBibtex::validate(LaTeXFeatures & features) const
775 if (features.bufferParams().use_bibtopic)
776 features.require("bibtopic");