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"
21 #include "FuncRequest.h"
23 #include "LaTeXFeatures.h"
24 #include "MetricsInfo.h"
25 #include "OutputParams.h"
27 #include "frontends/alert.h"
29 #include "support/filetools.h"
30 #include "support/lstrings.h"
31 #include "support/lyxlib.h"
32 #include "support/os.h"
33 #include "support/Path.h"
34 #include "support/textutils.h"
36 #include <boost/tokenizer.hpp>
41 using support::absolutePath;
42 using support::ascii_lowercase;
43 using support::changeExtension;
44 using support::contains;
46 using support::DocFileName;
47 using support::FileName;
48 using support::findtexfile;
49 using support::isFileReadable;
50 using support::isValidLaTeXFilename;
51 using support::latex_path;
53 using support::makeAbsPath;
54 using support::makeRelPath;
55 using support::prefixIs;
56 using support::removeExtension;
60 using support::tokenPos;
62 using support::lowercase;
64 namespace Alert = frontend::Alert;
65 namespace os = support::os;
76 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
77 : InsetCommand(p, "bibtex")
81 std::auto_ptr<Inset> InsetBibtex::doClone() const
83 return std::auto_ptr<Inset>(new InsetBibtex(*this));
87 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
91 case LFUN_INSET_MODIFY: {
92 InsetCommandParams p("bibtex");
93 InsetCommandMailer::string2params("bibtex", to_utf8(cmd.argument()), p);
94 if (!p.getCmdName().empty()) {
96 cur.buffer().updateBibfilesCache();
103 InsetCommand::doDispatch(cur, cmd);
109 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
111 return _("BibTeX Generated Bibliography");
117 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
118 string const & name, string const & ext)
120 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
121 if (absolutePath(name) || !isFileReadable(FileName(fname + ext)))
123 else if (!runparams.nice)
127 return to_utf8(makeRelPath(from_utf8(fname),
128 from_utf8(buffer.getMasterBuffer()->filePath())));
134 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
135 OutputParams const & runparams) const
137 // the sequence of the commands:
138 // 1. \bibliographystyle{style}
139 // 2. \addcontentsline{...} - if option bibtotoc set
140 // 3. \bibliography{database}
141 // and with bibtopic:
142 // 1. \bibliographystyle{style}
143 // 2. \begin{btSect}{database}
144 // 3. \btPrint{Cited|NotCited|All}
148 // If we are processing the LaTeX file in a temp directory then
149 // copy the .bib databases to this temp directory, mangling their
150 // names in the process. Store this mangled name in the list of
152 // (We need to do all this because BibTeX *really*, *really*
153 // can't handle "files with spaces" and Windows users tend to
154 // use such filenames.)
155 // Otherwise, store the (maybe absolute) path to the original,
156 // unmangled database name.
157 typedef boost::char_separator<char_type> Separator;
158 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
160 Separator const separator(from_ascii(",").c_str());
161 // The tokenizer must not be called with temporary strings, since
162 // it does not make a copy and uses iterators of the string further
163 // down. getParam returns a reference, so this is OK.
164 Tokenizer const tokens(getParam("bibfiles"), separator);
165 Tokenizer::const_iterator const begin = tokens.begin();
166 Tokenizer::const_iterator const end = tokens.end();
168 odocstringstream dbs;
169 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
170 docstring const input = trim(*it);
172 string utf8input(to_utf8(input));
174 normalize_name(buffer, runparams, utf8input, ".bib");
175 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
176 bool const not_from_texmf = isFileReadable(try_in_file);
178 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
181 // mangledFilename() needs the extension
182 DocFileName const in_file = DocFileName(try_in_file);
183 database = removeExtension(in_file.mangledFilename());
184 FileName const out_file(makeAbsPath(database + ".bib",
185 buffer.getMasterBuffer()->temppath()));
187 bool const success = copy(in_file, out_file);
189 lyxerr << "Failed to copy '" << in_file
190 << "' to '" << out_file << "'"
193 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
194 !isValidLaTeXFilename(database)) {
195 frontend::Alert::warning(_("Invalid filename"),
196 _("The following filename is likely to cause trouble "
197 "when running the exported file through LaTeX: ") +
198 from_utf8(database));
204 dbs << from_utf8(latex_path(database));
206 docstring const db_out = dbs.str();
208 // Post this warning only once.
209 static bool warned_about_spaces = false;
210 if (!warned_about_spaces &&
211 runparams.nice && db_out.find(' ') != docstring::npos) {
212 warned_about_spaces = true;
214 Alert::warning(_("Export Warning!"),
215 _("There are spaces in the paths to your BibTeX databases.\n"
216 "BibTeX will be unable to find them."));
221 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
223 if (prefixIs(style, "bibtotoc")) {
224 bibtotoc = "bibtotoc";
225 if (contains(style, ',')) {
226 style = split(style, bibtotoc, ',');
233 if (!style.empty()) {
235 normalize_name(buffer, runparams, style, ".bst");
236 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
237 bool const not_from_texmf = isFileReadable(try_in_file);
238 // If this style does not come from texmf and we are not
239 // exporting to .tex copy it to the tmp directory.
240 // This prevents problems with spaces and 8bit charcaters
242 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
244 // use new style name
245 DocFileName const in_file = DocFileName(try_in_file);
246 base = removeExtension(in_file.mangledFilename());
247 FileName const out_file(makeAbsPath(base + ".bst",
248 buffer.getMasterBuffer()->temppath()));
249 bool const success = copy(in_file, out_file);
251 lyxerr << "Failed to copy '" << in_file
252 << "' to '" << out_file << "'"
257 os << "\\bibliographystyle{"
258 << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
263 // Post this warning only once.
264 static bool warned_about_bst_spaces = false;
265 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
266 warned_about_bst_spaces = true;
267 Alert::warning(_("Export Warning!"),
268 _("There are spaces in the path to your BibTeX style file.\n"
269 "BibTeX will be unable to find it."));
272 if (!db_out.empty() && buffer.params().use_bibtopic){
273 os << "\\begin{btSect}{" << db_out << "}\n";
274 docstring btprint = getParam("btprint");
277 btprint = from_ascii("btPrintCited");
278 os << "\\" << btprint << "\n"
279 << "\\end{btSect}\n";
284 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
285 // maybe a problem when a textclass has no "art" as
286 // part of its name, because it's than book.
287 // For the "official" lyx-layouts it's no problem to support
289 if (!contains(buffer.params().getTextClass().name(),
291 if (buffer.params().sides == TextClass::OneSide) {
296 os << "\\cleardoublepage";
300 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
304 os << "\\addcontentsline{toc}{section}{\\refname}";
308 if (!db_out.empty() && !buffer.params().use_bibtopic){
309 os << "\\bibliography{" << db_out << "}\n";
317 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
319 FileName path(buffer.filePath());
320 support::Path p(path);
322 vector<FileName> vec;
326 string bibfiles = to_utf8(getParam("bibfiles"));
327 bibfiles = split(bibfiles, tmp, ',');
328 while (!tmp.empty()) {
329 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
330 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
332 // If we didn't find a matching file name just fail silently
336 // Get next file name
337 bibfiles = split(bibfiles, tmp, ',');
345 // methods for parsing bibtex files
347 typedef map<docstring, docstring> VarMap;
349 /// remove whitespace characters, optionally a single comma,
350 /// and further whitespace characters from the stream.
351 /// @return true if a comma was found, false otherwise
353 bool removeWSAndComma(idocfstream & ifs) {
362 } while (ifs && isSpace(ch));
375 } while (ifs && isSpace(ch));
390 /// remove whitespace characters, read characer sequence
391 /// not containing whitespace characters or characters in
392 /// delimChars, and remove further whitespace characters.
394 /// @return true if a string of length > 0 could be read.
396 bool readTypeOrKey(docstring & val, idocfstream & ifs,
397 docstring const & delimChars, docstring const &illegalChars,
410 } while (ifs && isSpace(ch));
416 bool legalChar = true;
417 while (ifs && !isSpace(ch) &&
418 delimChars.find(ch) == docstring::npos &&
419 (legalChar = (illegalChars.find(ch) == docstring::npos))
422 if (chCase == makeLowerCase)
423 val += lowercase(ch);
435 while (ifs && isSpace(ch)) {
443 return val.length() > 0;
446 /// read subsequent bibtex values that are delimited with a #-character.
447 /// Concatenate all parts and replace names with the associated string in
448 /// the variable strings.
449 /// @return true if reading was successfull (all single parts were delimited
451 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
464 } while (ifs && isSpace(ch));
469 // check for field type
472 // read integer value
476 } while (ifs && isDigit(ch));
481 } else if (ch == '"' || ch == '{') {
483 char_type delim = ch == '"' ? '"': '}';
488 } while (ifs && isSpace(ch));
493 //We now have the first non-whitespace character
494 //We'll collapse adjacent whitespace.
495 bool lastWasWhiteSpace = false;
497 // inside this delimited text braces must match.
498 // Thus we can have a closing delimiter only
499 // when nestLevel == 0
502 while (ifs && (nestLevel > 0 || ch != delim)) {
504 lastWasWhiteSpace = true;
508 //We output the space only after we stop getting
509 //whitespace so as not to output any whitespace
510 //at the end of the value.
511 if (lastWasWhiteSpace) {
512 lastWasWhiteSpace = false;
518 // update nesting level
525 if (nestLevel < 0) return false;
542 // reading a string name
545 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
546 strName += lowercase(ch);
553 // replace the string with its assigned value or
554 // discard it if it's not assigned
555 if (strName.length()) {
556 VarMap::const_iterator pos = strings.find(strName);
557 if (pos != strings.end()) {
564 while (ifs && isSpace(ch)) {
571 // continue reading next value on concatenate with '#'
581 // This method returns a comma separated list of Bibtex entries
582 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
583 BiblioInfo & keylist, InsetIterator const & /*di*/) const
585 vector<FileName> const files = getFiles(buffer);
586 for (vector<FileName>::const_iterator it = files.begin();
587 it != files.end(); ++ it) {
588 // This bibtex parser is a first step to parse bibtex files
591 // - it reads the whole bibtex entry and does a syntax check
592 // (matching delimiters, missing commas,...
593 // - it recovers from errors starting with the next @-character
594 // - it reads @string definitions and replaces them in the
596 // - it accepts more characters in keys or value names than
599 // Officially bibtex does only support ASCII, but in practice
600 // you can use the encoding of the main document as long as
601 // some elements like keys and names are pure ASCII. Therefore
602 // we convert the file from the buffer encoding.
603 // We don't restrict keys to ASCII in LyX, since our own
604 // InsetBibitem can generate non-ASCII keys, and nonstandard
605 // 8bit clean bibtex forks exist.
607 idocfstream ifs(it->toFilesystemEncoding().c_str(),
609 buffer.params().encoding().iconvName());
625 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
626 docstring(), makeLowerCase) || !ifs)
629 if (entryType == from_ascii("comment")) {
631 ifs.ignore(std::numeric_limits<int>::max(), '\n');
639 if ((ch != '(') && (ch != '{')) {
640 // invalid entry delimiter
646 if (entryType == from_ascii("string")) {
648 // read string and add it to the strings map
649 // (or replace it's old value)
653 if (!readTypeOrKey(name, ifs, from_ascii("="),
654 from_ascii("#{}(),"), makeLowerCase) || !ifs)
657 // next char must be an equal sign
659 if (!ifs || ch != '=')
662 if (!readValue(value, ifs, strings))
665 strings[name] = value;
667 } else if (entryType == from_ascii("preamble")) {
669 // preamble definitions are discarded.
670 // can they be of any use in lyx?
673 if (!readValue(value, ifs, strings))
678 // Citation entry. Try to read the key.
681 if (!readTypeOrKey(key, ifs, from_ascii(","),
682 from_ascii("}"), keepCase) || !ifs)
685 /////////////////////////////////////////////
686 // now we have a key, so we will add an entry
687 // (even if it's empty, as bibtex does)
689 // we now read the field = value pairs.
690 // all items must be separated by a comma. If
691 // it is missing the scanning of this entry is
692 // stopped and the next is searched.
696 docstring commaNewline;
698 BibTeXInfo keyvalmap;
699 keyvalmap.entryType = entryType;
701 bool readNext = removeWSAndComma(ifs);
703 while (ifs && readNext) {
706 if (!readTypeOrKey(name, ifs, from_ascii("="),
707 from_ascii("{}(),"), makeLowerCase) || !ifs)
710 // next char must be an equal sign
720 if (!readValue(value, ifs, strings))
723 keyvalmap[name] = value;
724 data += "\n\n" + value;
725 keylist.fieldNames.insert(name);
726 readNext = removeWSAndComma(ifs);
730 keylist.entryTypes.insert(entryType);
731 keyvalmap.allData = data;
732 keyvalmap.isBibTeX = true;
733 keyvalmap.bibKey = key;
734 keylist[key] = keyvalmap;
737 } //< for loop over files
742 bool InsetBibtex::addDatabase(string const & db)
745 string bibfiles(to_utf8(getParam("bibfiles")));
746 if (tokenPos(bibfiles, ',', db) == -1) {
747 if (!bibfiles.empty())
749 setParam("bibfiles", from_utf8(bibfiles + db));
756 bool InsetBibtex::delDatabase(string const & db)
759 string bibfiles(to_utf8(getParam("bibfiles")));
760 if (contains(bibfiles, db)) {
761 int const n = tokenPos(bibfiles, ',', db);
764 // this is not the first database
765 string tmp = ',' + bd;
766 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
768 // this is the first (or only) database
769 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
777 void InsetBibtex::validate(LaTeXFeatures & features) const
779 if (features.bufferParams().use_bibtopic)
780 features.require("bibtopic");