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 "EmbeddedFiles.h"
21 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
23 #include "MetricsInfo.h"
24 #include "OutputParams.h"
25 #include "TextClass.h"
27 #include "frontends/alert.h"
29 #include "support/debug.h"
30 #include "support/ExceptionMessage.h"
31 #include "support/docstream.h"
32 #include "support/filetools.h"
33 #include "support/gettext.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>
43 using namespace lyx::support;
47 namespace Alert = frontend::Alert;
48 namespace os = support::os;
51 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
52 : InsetCommand(p, "bibtex")
56 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
58 static ParamInfo param_info_;
59 if (param_info_.empty()) {
60 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
61 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
62 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
63 param_info_.add("options", ParamInfo::LYX_INTERNAL);
69 Inset * InsetBibtex::clone() const
71 return new InsetBibtex(*this);
75 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
79 case LFUN_INSET_MODIFY: {
80 InsetCommandParams p(BIBTEX_CODE);
82 if (!InsetCommandMailer::string2params("bibtex",
83 to_utf8(cmd.argument()), p)) {
87 } catch (ExceptionMessage const & message) {
88 if (message.type_ == WarningException) {
89 Alert::warning(message.title_, message.details_);
96 InsetCommandParams orig = params();
97 // returned "embed" is composed of "true" or "false", which needs to be adjusted
102 string newEmbedStatus;
104 string bibfiles = to_utf8(p["bibfiles"]);
105 string embedStatus = to_utf8(p["embed"]);
107 bibfiles = split(bibfiles, tmp, ',');
108 embedStatus = split(embedStatus, emb, ',');
109 while (!tmp.empty()) {
110 EmbeddedFile file(changeExtension(tmp, "bib"), cur.buffer().filePath());
111 if (!newBibfiles.empty())
114 if (!newEmbedStatus.empty())
115 newEmbedStatus += ",";
117 newEmbedStatus += file.inzipName();
118 // Get next file name
119 bibfiles = split(bibfiles, tmp, ',');
120 embedStatus = split(embedStatus, emb, ',');
122 LYXERR(Debug::FILES, "Update parameters from " << p["bibfiles"]
123 << " " << p["embed"] << " to " << newBibfiles << " "
125 p["bibfiles"] = from_utf8(newBibfiles);
126 p["embed"] = from_utf8(newEmbedStatus);
130 // test parameter and copy files
131 getFiles(cur.buffer());
132 } catch (ExceptionMessage const & message) {
133 Alert::error(message.title_, message.details_);
134 // do not set parameter if an error happens
138 cur.buffer().updateBibfilesCache();
143 InsetCommand::doDispatch(cur, cmd);
149 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
151 return _("BibTeX Generated Bibliography");
157 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
158 string const & name, string const & ext)
160 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
161 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
167 return to_utf8(makeRelPath(from_utf8(fname),
168 from_utf8(buffer.masterBuffer()->filePath())));
174 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
175 OutputParams const & runparams) const
177 // the sequence of the commands:
178 // 1. \bibliographystyle{style}
179 // 2. \addcontentsline{...} - if option bibtotoc set
180 // 3. \bibliography{database}
181 // and with bibtopic:
182 // 1. \bibliographystyle{style}
183 // 2. \begin{btSect}{database}
184 // 3. \btPrint{Cited|NotCited|All}
188 // If we are processing the LaTeX file in a temp directory then
189 // copy the .bib databases to this temp directory, mangling their
190 // names in the process. Store this mangled name in the list of
192 // (We need to do all this because BibTeX *really*, *really*
193 // can't handle "files with spaces" and Windows users tend to
194 // use such filenames.)
195 // Otherwise, store the (maybe absolute) path to the original,
196 // unmangled database name.
197 EmbeddedFileList const bibs = getFiles(buffer);
198 EmbeddedFileList::const_iterator it = bibs.begin();
199 EmbeddedFileList::const_iterator it_end = bibs.end();
200 odocstringstream dbs;
201 for (; it != it_end; ++it) {
202 string utf8input = removeExtension(it->availableFile().absFilename());
204 normalizeName(buffer, runparams, utf8input, ".bib");
205 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
206 bool const not_from_texmf = try_in_file.isReadableFile();
208 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
211 // mangledFilename() needs the extension
212 DocFileName const in_file = DocFileName(try_in_file);
213 database = removeExtension(in_file.mangledFilename());
214 FileName const out_file = makeAbsPath(database + ".bib",
215 buffer.masterBuffer()->temppath());
217 bool const success = in_file.copyTo(out_file);
219 lyxerr << "Failed to copy '" << in_file
220 << "' to '" << out_file << "'"
223 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
224 !isValidLaTeXFilename(database)) {
225 frontend::Alert::warning(_("Invalid filename"),
226 _("The following filename is likely to cause trouble "
227 "when running the exported file through LaTeX: ") +
228 from_utf8(database));
231 if (it != bibs.begin())
234 dbs << from_utf8(latex_path(database));
236 docstring const db_out = dbs.str();
238 // Post this warning only once.
239 static bool warned_about_spaces = false;
240 if (!warned_about_spaces &&
241 runparams.nice && db_out.find(' ') != docstring::npos) {
242 warned_about_spaces = true;
244 Alert::warning(_("Export Warning!"),
245 _("There are spaces in the paths to your BibTeX databases.\n"
246 "BibTeX will be unable to find them."));
250 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
252 if (prefixIs(style, "bibtotoc")) {
253 bibtotoc = "bibtotoc";
254 if (contains(style, ','))
255 style = split(style, bibtotoc, ',');
261 if (!style.empty()) {
262 string base = normalizeName(buffer, runparams, style, ".bst");
263 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
264 bool const not_from_texmf = try_in_file.isReadableFile();
265 // If this style does not come from texmf and we are not
266 // exporting to .tex copy it to the tmp directory.
267 // This prevents problems with spaces and 8bit charcaters
269 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
271 // use new style name
272 DocFileName const in_file = DocFileName(try_in_file);
273 base = removeExtension(in_file.mangledFilename());
274 FileName const out_file(makeAbsPath(base + ".bst",
275 buffer.masterBuffer()->temppath()));
276 bool const success = in_file.copyTo(out_file);
278 lyxerr << "Failed to copy '" << in_file
279 << "' to '" << out_file << "'"
284 os << "\\bibliographystyle{"
285 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
290 // Post this warning only once.
291 static bool warned_about_bst_spaces = false;
292 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
293 warned_about_bst_spaces = true;
294 Alert::warning(_("Export Warning!"),
295 _("There are spaces in the path to your BibTeX style file.\n"
296 "BibTeX will be unable to find it."));
299 if (!db_out.empty() && buffer.params().use_bibtopic){
300 os << "\\begin{btSect}{" << db_out << "}\n";
301 docstring btprint = getParam("btprint");
304 btprint = from_ascii("btPrintCited");
305 os << "\\" << btprint << "\n"
306 << "\\end{btSect}\n";
311 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
312 // maybe a problem when a textclass has no "art" as
313 // part of its name, because it's than book.
314 // For the "official" lyx-layouts it's no problem to support
316 if (!contains(buffer.params().textClass().name(),
318 if (buffer.params().sides == OneSide) {
323 os << "\\cleardoublepage";
327 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
331 os << "\\addcontentsline{toc}{section}{\\refname}";
335 if (!db_out.empty() && !buffer.params().use_bibtopic){
336 docstring btprint = getParam("btprint");
337 if (btprint == "btPrintAll") {
338 os << "\\nocite{*}\n";
341 os << "\\bibliography{" << db_out << "}\n";
349 EmbeddedFileList const InsetBibtex::getFiles(Buffer const & buffer) const
351 FileName path(buffer.filePath());
354 EmbeddedFileList vec;
359 string bibfiles = to_utf8(getParam("bibfiles"));
360 string embedStatus = to_utf8(getParam("embed"));
361 bibfiles = split(bibfiles, tmp, ',');
362 embedStatus = split(embedStatus, emb, ',');
363 while (!tmp.empty()) {
365 EmbeddedFile file(changeExtension(tmp, "bib"), buffer.filePath());
366 // If the file structure is correct, this should not fail.
368 file.enable(buffer.embedded(), &buffer);
371 // this includes the cases when the embed parameter is empty
372 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
374 // If we didn't find a matching file name just fail silently
376 EmbeddedFile efile = EmbeddedFile(file.absFilename(), buffer.filePath());
377 efile.setEmbed(false);
378 efile.enable(buffer.embedded(), &buffer);
379 vec.push_back(efile);
383 // Get next file name
384 bibfiles = split(bibfiles, tmp, ',');
385 embedStatus = split(embedStatus, emb, ',');
393 // methods for parsing bibtex files
395 typedef map<docstring, docstring> VarMap;
397 /// remove whitespace characters, optionally a single comma,
398 /// and further whitespace characters from the stream.
399 /// @return true if a comma was found, false otherwise
401 bool removeWSAndComma(idocfstream & ifs) {
410 } while (ifs && isSpace(ch));
423 } while (ifs && isSpace(ch));
438 /// remove whitespace characters, read characer sequence
439 /// not containing whitespace characters or characters in
440 /// delimChars, and remove further whitespace characters.
442 /// @return true if a string of length > 0 could be read.
444 bool readTypeOrKey(docstring & val, idocfstream & ifs,
445 docstring const & delimChars, docstring const &illegalChars,
458 } while (ifs && isSpace(ch));
464 bool legalChar = true;
465 while (ifs && !isSpace(ch) &&
466 delimChars.find(ch) == docstring::npos &&
467 (legalChar = (illegalChars.find(ch) == docstring::npos))
470 if (chCase == makeLowerCase)
471 val += lowercase(ch);
483 while (ifs && isSpace(ch)) {
491 return val.length() > 0;
494 /// read subsequent bibtex values that are delimited with a #-character.
495 /// Concatenate all parts and replace names with the associated string in
496 /// the variable strings.
497 /// @return true if reading was successfull (all single parts were delimited
499 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
512 } while (ifs && isSpace(ch));
517 // check for field type
520 // read integer value
524 } while (ifs && isDigit(ch));
529 } else if (ch == '"' || ch == '{') {
531 char_type delim = ch == '"' ? '"': '}';
536 } while (ifs && isSpace(ch));
541 //We now have the first non-whitespace character
542 //We'll collapse adjacent whitespace.
543 bool lastWasWhiteSpace = false;
545 // inside this delimited text braces must match.
546 // Thus we can have a closing delimiter only
547 // when nestLevel == 0
550 while (ifs && (nestLevel > 0 || ch != delim)) {
552 lastWasWhiteSpace = true;
556 //We output the space only after we stop getting
557 //whitespace so as not to output any whitespace
558 //at the end of the value.
559 if (lastWasWhiteSpace) {
560 lastWasWhiteSpace = false;
566 // update nesting level
573 if (nestLevel < 0) return false;
590 // reading a string name
593 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
594 strName += lowercase(ch);
601 // replace the string with its assigned value or
602 // discard it if it's not assigned
603 if (strName.length()) {
604 VarMap::const_iterator pos = strings.find(strName);
605 if (pos != strings.end()) {
612 while (ifs && isSpace(ch)) {
619 // continue reading next value on concatenate with '#'
629 // This method returns a comma separated list of Bibtex entries
630 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
631 BiblioInfo & keylist, InsetIterator const & /*di*/) const
633 EmbeddedFileList const files = getFiles(buffer);
634 for (vector<EmbeddedFile>::const_iterator it = files.begin();
635 it != files.end(); ++ it) {
636 // This bibtex parser is a first step to parse bibtex files
639 // - it reads the whole bibtex entry and does a syntax check
640 // (matching delimiters, missing commas,...
641 // - it recovers from errors starting with the next @-character
642 // - it reads @string definitions and replaces them in the
644 // - it accepts more characters in keys or value names than
647 // Officially bibtex does only support ASCII, but in practice
648 // you can use the encoding of the main document as long as
649 // some elements like keys and names are pure ASCII. Therefore
650 // we convert the file from the buffer encoding.
651 // We don't restrict keys to ASCII in LyX, since our own
652 // InsetBibitem can generate non-ASCII keys, and nonstandard
653 // 8bit clean bibtex forks exist.
655 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
657 buffer.params().encoding().iconvName());
673 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
674 docstring(), makeLowerCase) || !ifs)
677 if (entryType == from_ascii("comment")) {
679 ifs.ignore(numeric_limits<int>::max(), '\n');
687 if ((ch != '(') && (ch != '{')) {
688 // invalid entry delimiter
694 if (entryType == from_ascii("string")) {
696 // read string and add it to the strings map
697 // (or replace it's old value)
701 if (!readTypeOrKey(name, ifs, from_ascii("="),
702 from_ascii("#{}(),"), makeLowerCase) || !ifs)
705 // next char must be an equal sign
707 if (!ifs || ch != '=')
710 if (!readValue(value, ifs, strings))
713 strings[name] = value;
715 } else if (entryType == from_ascii("preamble")) {
717 // preamble definitions are discarded.
718 // can they be of any use in lyx?
721 if (!readValue(value, ifs, strings))
726 // Citation entry. Try to read the key.
729 if (!readTypeOrKey(key, ifs, from_ascii(","),
730 from_ascii("}"), keepCase) || !ifs)
733 /////////////////////////////////////////////
734 // now we have a key, so we will add an entry
735 // (even if it's empty, as bibtex does)
737 // we now read the field = value pairs.
738 // all items must be separated by a comma. If
739 // it is missing the scanning of this entry is
740 // stopped and the next is searched.
744 docstring commaNewline;
746 BibTeXInfo keyvalmap(key, entryType);
748 bool readNext = removeWSAndComma(ifs);
750 while (ifs && readNext) {
753 if (!readTypeOrKey(name, ifs, from_ascii("="),
754 from_ascii("{}(),"), makeLowerCase) || !ifs)
757 // next char must be an equal sign
767 if (!readValue(value, ifs, strings))
770 keyvalmap[name] = value;
771 data += "\n\n" + value;
772 keylist.addFieldName(name);
773 readNext = removeWSAndComma(ifs);
777 keylist.addEntryType(entryType);
778 keyvalmap.setAllData(data);
779 keylist[key] = keyvalmap;
782 } //< for loop over files
787 bool InsetBibtex::addDatabase(string const & db)
790 string bibfiles(to_utf8(getParam("bibfiles")));
791 if (tokenPos(bibfiles, ',', db) == -1) {
792 if (!bibfiles.empty())
794 setParam("bibfiles", from_utf8(bibfiles + db));
801 bool InsetBibtex::delDatabase(string const & db)
804 string bibfiles(to_utf8(getParam("bibfiles")));
805 if (contains(bibfiles, db)) {
806 int const n = tokenPos(bibfiles, ',', db);
809 // this is not the first database
810 string tmp = ',' + bd;
811 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
813 // this is the first (or only) database
814 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
822 void InsetBibtex::validate(LaTeXFeatures & features) const
824 if (features.bufferParams().use_bibtopic)
825 features.require("bibtopic");
829 void InsetBibtex::registerEmbeddedFiles(Buffer const & buffer, EmbeddedFileList & files) const
831 EmbeddedFileList const dbs = getFiles(buffer);
832 for (vector<EmbeddedFile>::const_iterator it = dbs.begin();
833 it != dbs.end(); ++ it)
834 files.registerFile(*it, this, buffer);
838 void InsetBibtex::updateEmbeddedFile(Buffer const & buf, EmbeddedFile const & file)
840 // look for the item and update status
845 EmbeddedFileList dbs = getFiles(buf);
846 for (EmbeddedFileList::iterator it = dbs.begin();
847 it != dbs.end(); ++ it) {
849 if (it->absFilename() == file.absFilename())
850 it->setEmbed(file.embedded());
851 // write parameter string
857 bibfiles += from_utf8(it->outputFilename(buf.filePath()));
859 embed += from_utf8(it->inzipName());
861 setParam("bibfiles", bibfiles);
862 setParam("embed", embed);