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"
20 #include "EmbeddedFiles.h"
22 #include "FuncRequest.h"
23 #include "support/gettext.h"
24 #include "LaTeXFeatures.h"
25 #include "MetricsInfo.h"
26 #include "OutputParams.h"
27 #include "TextClass.h"
29 #include "frontends/alert.h"
31 #include "support/ExceptionMessage.h"
32 #include "support/docstream.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", "embed", ""};
59 static const bool isoptional[] = {true, true, false, false};
60 static const CommandInfo info = {4, 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 InsetCommandParams orig = params();
94 // test parameter and copy files
96 // enable() in getFiles will try to copy files
97 getFiles(cur.buffer());
98 } catch (ExceptionMessage const & message) {
99 Alert::error(message.title_, message.details_);
100 // do not set parameter if an error happens
104 cur.buffer().updateBibfilesCache();
109 InsetCommand::doDispatch(cur, cmd);
115 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
117 return _("BibTeX Generated Bibliography");
123 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
124 string const & name, string const & ext)
126 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
127 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
133 return to_utf8(makeRelPath(from_utf8(fname),
134 from_utf8(buffer.masterBuffer()->filePath())));
140 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
141 OutputParams const & runparams) const
143 // the sequence of the commands:
144 // 1. \bibliographystyle{style}
145 // 2. \addcontentsline{...} - if option bibtotoc set
146 // 3. \bibliography{database}
147 // and with bibtopic:
148 // 1. \bibliographystyle{style}
149 // 2. \begin{btSect}{database}
150 // 3. \btPrint{Cited|NotCited|All}
154 // If we are processing the LaTeX file in a temp directory then
155 // copy the .bib databases to this temp directory, mangling their
156 // names in the process. Store this mangled name in the list of
158 // (We need to do all this because BibTeX *really*, *really*
159 // can't handle "files with spaces" and Windows users tend to
160 // use such filenames.)
161 // Otherwise, store the (maybe absolute) path to the original,
162 // unmangled database name.
163 typedef boost::char_separator<char_type> Separator;
164 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
166 Separator const separator(from_ascii(",").c_str());
167 // The tokenizer must not be called with temporary strings, since
168 // it does not make a copy and uses iterators of the string further
169 // down. getParam returns a reference, so this is OK.
170 Tokenizer const tokens(getParam("bibfiles"), separator);
171 Tokenizer::const_iterator const begin = tokens.begin();
172 Tokenizer::const_iterator const end = tokens.end();
174 odocstringstream dbs;
175 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
176 docstring const input = trim(*it);
178 string utf8input = to_utf8(input);
180 normalizeName(buffer, runparams, utf8input, ".bib");
181 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
182 bool const not_from_texmf = try_in_file.isReadableFile();
184 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
187 // mangledFilename() needs the extension
188 DocFileName const in_file = DocFileName(try_in_file);
189 database = removeExtension(in_file.mangledFilename());
190 FileName const out_file = makeAbsPath(database + ".bib",
191 buffer.masterBuffer()->temppath());
193 bool const success = in_file.copyTo(out_file);
195 lyxerr << "Failed to copy '" << in_file
196 << "' to '" << out_file << "'"
199 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
200 !isValidLaTeXFilename(database)) {
201 frontend::Alert::warning(_("Invalid filename"),
202 _("The following filename is likely to cause trouble "
203 "when running the exported file through LaTeX: ") +
204 from_utf8(database));
210 dbs << from_utf8(latex_path(database));
212 docstring const db_out = dbs.str();
214 // Post this warning only once.
215 static bool warned_about_spaces = false;
216 if (!warned_about_spaces &&
217 runparams.nice && db_out.find(' ') != docstring::npos) {
218 warned_about_spaces = true;
220 Alert::warning(_("Export Warning!"),
221 _("There are spaces in the paths to your BibTeX databases.\n"
222 "BibTeX will be unable to find them."));
226 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
228 if (prefixIs(style, "bibtotoc")) {
229 bibtotoc = "bibtotoc";
230 if (contains(style, ','))
231 style = split(style, bibtotoc, ',');
237 if (!style.empty()) {
238 string base = normalizeName(buffer, runparams, style, ".bst");
239 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
240 bool const not_from_texmf = try_in_file.isReadableFile();
241 // If this style does not come from texmf and we are not
242 // exporting to .tex copy it to the tmp directory.
243 // This prevents problems with spaces and 8bit charcaters
245 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
247 // use new style name
248 DocFileName const in_file = DocFileName(try_in_file);
249 base = removeExtension(in_file.mangledFilename());
250 FileName const out_file(makeAbsPath(base + ".bst",
251 buffer.masterBuffer()->temppath()));
252 bool const success = in_file.copyTo(out_file);
254 lyxerr << "Failed to copy '" << in_file
255 << "' to '" << out_file << "'"
260 os << "\\bibliographystyle{"
261 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
266 // Post this warning only once.
267 static bool warned_about_bst_spaces = false;
268 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
269 warned_about_bst_spaces = true;
270 Alert::warning(_("Export Warning!"),
271 _("There are spaces in the path to your BibTeX style file.\n"
272 "BibTeX will be unable to find it."));
275 if (!db_out.empty() && buffer.params().use_bibtopic){
276 os << "\\begin{btSect}{" << db_out << "}\n";
277 docstring btprint = getParam("btprint");
280 btprint = from_ascii("btPrintCited");
281 os << "\\" << btprint << "\n"
282 << "\\end{btSect}\n";
287 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
288 // maybe a problem when a textclass has no "art" as
289 // part of its name, because it's than book.
290 // For the "official" lyx-layouts it's no problem to support
292 if (!contains(buffer.params().getTextClass().name(),
294 if (buffer.params().sides == OneSide) {
299 os << "\\cleardoublepage";
303 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
307 os << "\\addcontentsline{toc}{section}{\\refname}";
311 if (!db_out.empty() && !buffer.params().use_bibtopic){
312 docstring btprint = getParam("btprint");
313 if (btprint == "btPrintAll") {
314 os << "\\nocite{*}\n";
317 os << "\\bibliography{" << db_out << "}\n";
325 EmbeddedFileList const InsetBibtex::getFiles(Buffer const & buffer) const
327 FileName path(buffer.filePath());
330 EmbeddedFileList vec;
335 string bibfiles = to_utf8(getParam("bibfiles"));
336 string embedStatus = to_utf8(getParam("embed"));
337 bibfiles = split(bibfiles, tmp, ',');
338 embedStatus = split(embedStatus, emb, ',');
339 while (!tmp.empty()) {
341 EmbeddedFile file(changeExtension(tmp, "bib"), buffer.filePath());
342 // If the file structure is correct, this should not fail.
344 file.enable(buffer.embedded(), &buffer);
347 // this includes the cases when the embed parameter is empty
348 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
350 // If we didn't find a matching file name just fail silently
352 EmbeddedFile efile = EmbeddedFile(file.absFilename(), buffer.filePath());
353 efile.setEmbed(false);
354 efile.enable(buffer.embedded(), &buffer);
355 vec.push_back(efile);
359 // Get next file name
360 bibfiles = split(bibfiles, tmp, ',');
361 embedStatus = split(embedStatus, emb, ',');
369 // methods for parsing bibtex files
371 typedef map<docstring, docstring> VarMap;
373 /// remove whitespace characters, optionally a single comma,
374 /// and further whitespace characters from the stream.
375 /// @return true if a comma was found, false otherwise
377 bool removeWSAndComma(idocfstream & ifs) {
386 } while (ifs && isSpace(ch));
399 } while (ifs && isSpace(ch));
414 /// remove whitespace characters, read characer sequence
415 /// not containing whitespace characters or characters in
416 /// delimChars, and remove further whitespace characters.
418 /// @return true if a string of length > 0 could be read.
420 bool readTypeOrKey(docstring & val, idocfstream & ifs,
421 docstring const & delimChars, docstring const &illegalChars,
434 } while (ifs && isSpace(ch));
440 bool legalChar = true;
441 while (ifs && !isSpace(ch) &&
442 delimChars.find(ch) == docstring::npos &&
443 (legalChar = (illegalChars.find(ch) == docstring::npos))
446 if (chCase == makeLowerCase)
447 val += lowercase(ch);
459 while (ifs && isSpace(ch)) {
467 return val.length() > 0;
470 /// read subsequent bibtex values that are delimited with a #-character.
471 /// Concatenate all parts and replace names with the associated string in
472 /// the variable strings.
473 /// @return true if reading was successfull (all single parts were delimited
475 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
488 } while (ifs && isSpace(ch));
493 // check for field type
496 // read integer value
500 } while (ifs && isDigit(ch));
505 } else if (ch == '"' || ch == '{') {
507 char_type delim = ch == '"' ? '"': '}';
512 } while (ifs && isSpace(ch));
517 //We now have the first non-whitespace character
518 //We'll collapse adjacent whitespace.
519 bool lastWasWhiteSpace = false;
521 // inside this delimited text braces must match.
522 // Thus we can have a closing delimiter only
523 // when nestLevel == 0
526 while (ifs && (nestLevel > 0 || ch != delim)) {
528 lastWasWhiteSpace = true;
532 //We output the space only after we stop getting
533 //whitespace so as not to output any whitespace
534 //at the end of the value.
535 if (lastWasWhiteSpace) {
536 lastWasWhiteSpace = false;
542 // update nesting level
549 if (nestLevel < 0) return false;
566 // reading a string name
569 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
570 strName += lowercase(ch);
577 // replace the string with its assigned value or
578 // discard it if it's not assigned
579 if (strName.length()) {
580 VarMap::const_iterator pos = strings.find(strName);
581 if (pos != strings.end()) {
588 while (ifs && isSpace(ch)) {
595 // continue reading next value on concatenate with '#'
605 // This method returns a comma separated list of Bibtex entries
606 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
607 BiblioInfo & keylist, InsetIterator const & /*di*/) const
609 EmbeddedFileList const files = getFiles(buffer);
610 for (vector<EmbeddedFile>::const_iterator it = files.begin();
611 it != files.end(); ++ it) {
612 // This bibtex parser is a first step to parse bibtex files
615 // - it reads the whole bibtex entry and does a syntax check
616 // (matching delimiters, missing commas,...
617 // - it recovers from errors starting with the next @-character
618 // - it reads @string definitions and replaces them in the
620 // - it accepts more characters in keys or value names than
623 // Officially bibtex does only support ASCII, but in practice
624 // you can use the encoding of the main document as long as
625 // some elements like keys and names are pure ASCII. Therefore
626 // we convert the file from the buffer encoding.
627 // We don't restrict keys to ASCII in LyX, since our own
628 // InsetBibitem can generate non-ASCII keys, and nonstandard
629 // 8bit clean bibtex forks exist.
631 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
633 buffer.params().encoding().iconvName());
649 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
650 docstring(), makeLowerCase) || !ifs)
653 if (entryType == from_ascii("comment")) {
655 ifs.ignore(numeric_limits<int>::max(), '\n');
663 if ((ch != '(') && (ch != '{')) {
664 // invalid entry delimiter
670 if (entryType == from_ascii("string")) {
672 // read string and add it to the strings map
673 // (or replace it's old value)
677 if (!readTypeOrKey(name, ifs, from_ascii("="),
678 from_ascii("#{}(),"), makeLowerCase) || !ifs)
681 // next char must be an equal sign
683 if (!ifs || ch != '=')
686 if (!readValue(value, ifs, strings))
689 strings[name] = value;
691 } else if (entryType == from_ascii("preamble")) {
693 // preamble definitions are discarded.
694 // can they be of any use in lyx?
697 if (!readValue(value, ifs, strings))
702 // Citation entry. Try to read the key.
705 if (!readTypeOrKey(key, ifs, from_ascii(","),
706 from_ascii("}"), keepCase) || !ifs)
709 /////////////////////////////////////////////
710 // now we have a key, so we will add an entry
711 // (even if it's empty, as bibtex does)
713 // we now read the field = value pairs.
714 // all items must be separated by a comma. If
715 // it is missing the scanning of this entry is
716 // stopped and the next is searched.
720 docstring commaNewline;
722 BibTeXInfo keyvalmap;
723 keyvalmap.entryType = entryType;
725 bool readNext = removeWSAndComma(ifs);
727 while (ifs && readNext) {
730 if (!readTypeOrKey(name, ifs, from_ascii("="),
731 from_ascii("{}(),"), makeLowerCase) || !ifs)
734 // next char must be an equal sign
744 if (!readValue(value, ifs, strings))
747 keyvalmap[name] = value;
748 data += "\n\n" + value;
749 keylist.fieldNames.insert(name);
750 readNext = removeWSAndComma(ifs);
754 keylist.entryTypes.insert(entryType);
755 keyvalmap.allData = data;
756 keyvalmap.isBibTeX = true;
757 keyvalmap.bibKey = key;
758 keylist[key] = keyvalmap;
761 } //< for loop over files
766 bool InsetBibtex::addDatabase(string const & db)
769 string bibfiles(to_utf8(getParam("bibfiles")));
770 if (tokenPos(bibfiles, ',', db) == -1) {
771 if (!bibfiles.empty())
773 setParam("bibfiles", from_utf8(bibfiles + db));
780 bool InsetBibtex::delDatabase(string const & db)
783 string bibfiles(to_utf8(getParam("bibfiles")));
784 if (contains(bibfiles, db)) {
785 int const n = tokenPos(bibfiles, ',', db);
788 // this is not the first database
789 string tmp = ',' + bd;
790 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
792 // this is the first (or only) database
793 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
801 void InsetBibtex::validate(LaTeXFeatures & features) const
803 if (features.bufferParams().use_bibtopic)
804 features.require("bibtopic");
808 void InsetBibtex::registerEmbeddedFiles(Buffer const & buffer, EmbeddedFileList & files) const
810 EmbeddedFileList const dbs = getFiles(buffer);
811 for (vector<EmbeddedFile>::const_iterator it = dbs.begin();
812 it != dbs.end(); ++ it)
813 files.registerFile(*it, this, buffer);
817 void InsetBibtex::updateEmbeddedFile(Buffer const & buf, EmbeddedFile const & file)
819 // look for the item and update status
824 EmbeddedFileList dbs = getFiles(buf);
825 for (EmbeddedFileList::iterator it = dbs.begin();
826 it != dbs.end(); ++ it) {
828 if (it->absFilename() == file.absFilename())
829 it->setEmbed(file.embedded());
830 // write parameter string
836 bibfiles += from_utf8(it->outputFilename(buf.filePath()));
837 embed += it->embedded() ? _("true") : _("false");
839 setParam("bibfiles", bibfiles);
840 setParam("embed", embed);