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();
93 // returned "embed" is composed of "true" or "false", which needs to be adjusted
98 string newEmbedStatus;
100 string bibfiles = to_utf8(p["bibfiles"]);
101 string embedStatus = to_utf8(p["embed"]);
103 bibfiles = split(bibfiles, tmp, ',');
104 embedStatus = split(embedStatus, emb, ',');
105 while (!tmp.empty()) {
106 EmbeddedFile file(changeExtension(tmp, "bib"), cur.buffer().filePath());
109 if (!newBibfiles.empty())
112 if (!newEmbedStatus.empty())
113 newEmbedStatus += ",";
115 newEmbedStatus += file.inzipName();
116 // Get next file name
117 bibfiles = split(bibfiles, tmp, ',');
118 embedStatus = split(embedStatus, emb, ',');
120 LYXERR(Debug::FILES, "Update parameters from " << p["bibfiles"]
121 << " " << p["embed"] << " to " << newBibfiles << " "
123 p["bibfiles"] = from_utf8(newBibfiles);
124 p["embed"] = from_utf8(newEmbedStatus);
128 // test parameter and copy files
129 getFiles(cur.buffer());
130 } catch (ExceptionMessage const & message) {
131 Alert::error(message.title_, message.details_);
132 // do not set parameter if an error happens
136 cur.buffer().updateBibfilesCache();
141 InsetCommand::doDispatch(cur, cmd);
147 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
149 return _("BibTeX Generated Bibliography");
155 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
156 string const & name, string const & ext)
158 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
159 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
165 return to_utf8(makeRelPath(from_utf8(fname),
166 from_utf8(buffer.masterBuffer()->filePath())));
172 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
173 OutputParams const & runparams) const
175 // the sequence of the commands:
176 // 1. \bibliographystyle{style}
177 // 2. \addcontentsline{...} - if option bibtotoc set
178 // 3. \bibliography{database}
179 // and with bibtopic:
180 // 1. \bibliographystyle{style}
181 // 2. \begin{btSect}{database}
182 // 3. \btPrint{Cited|NotCited|All}
186 // If we are processing the LaTeX file in a temp directory then
187 // copy the .bib databases to this temp directory, mangling their
188 // names in the process. Store this mangled name in the list of
190 // (We need to do all this because BibTeX *really*, *really*
191 // can't handle "files with spaces" and Windows users tend to
192 // use such filenames.)
193 // Otherwise, store the (maybe absolute) path to the original,
194 // unmangled database name.
195 EmbeddedFileList const bibs = getFiles(buffer);
196 EmbeddedFileList::const_iterator it = bibs.begin();
197 EmbeddedFileList::const_iterator it_end = bibs.end();
198 odocstringstream dbs;
199 for (; it != it_end; ++it) {
200 string utf8input = removeExtension(it->availableFile().absFilename());
202 normalizeName(buffer, runparams, utf8input, ".bib");
203 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
204 bool const not_from_texmf = try_in_file.isReadableFile();
206 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
209 // mangledFilename() needs the extension
210 DocFileName const in_file = DocFileName(try_in_file);
211 database = removeExtension(in_file.mangledFilename());
212 FileName const out_file = makeAbsPath(database + ".bib",
213 buffer.masterBuffer()->temppath());
215 bool const success = in_file.copyTo(out_file);
217 lyxerr << "Failed to copy '" << in_file
218 << "' to '" << out_file << "'"
221 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
222 !isValidLaTeXFilename(database)) {
223 frontend::Alert::warning(_("Invalid filename"),
224 _("The following filename is likely to cause trouble "
225 "when running the exported file through LaTeX: ") +
226 from_utf8(database));
229 if (it != bibs.begin())
232 dbs << from_utf8(latex_path(database));
234 docstring const db_out = dbs.str();
236 // Post this warning only once.
237 static bool warned_about_spaces = false;
238 if (!warned_about_spaces &&
239 runparams.nice && db_out.find(' ') != docstring::npos) {
240 warned_about_spaces = true;
242 Alert::warning(_("Export Warning!"),
243 _("There are spaces in the paths to your BibTeX databases.\n"
244 "BibTeX will be unable to find them."));
248 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
250 if (prefixIs(style, "bibtotoc")) {
251 bibtotoc = "bibtotoc";
252 if (contains(style, ','))
253 style = split(style, bibtotoc, ',');
259 if (!style.empty()) {
260 string base = normalizeName(buffer, runparams, style, ".bst");
261 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
262 bool const not_from_texmf = try_in_file.isReadableFile();
263 // If this style does not come from texmf and we are not
264 // exporting to .tex copy it to the tmp directory.
265 // This prevents problems with spaces and 8bit charcaters
267 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
269 // use new style name
270 DocFileName const in_file = DocFileName(try_in_file);
271 base = removeExtension(in_file.mangledFilename());
272 FileName const out_file(makeAbsPath(base + ".bst",
273 buffer.masterBuffer()->temppath()));
274 bool const success = in_file.copyTo(out_file);
276 lyxerr << "Failed to copy '" << in_file
277 << "' to '" << out_file << "'"
282 os << "\\bibliographystyle{"
283 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
288 // Post this warning only once.
289 static bool warned_about_bst_spaces = false;
290 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
291 warned_about_bst_spaces = true;
292 Alert::warning(_("Export Warning!"),
293 _("There are spaces in the path to your BibTeX style file.\n"
294 "BibTeX will be unable to find it."));
297 if (!db_out.empty() && buffer.params().use_bibtopic){
298 os << "\\begin{btSect}{" << db_out << "}\n";
299 docstring btprint = getParam("btprint");
302 btprint = from_ascii("btPrintCited");
303 os << "\\" << btprint << "\n"
304 << "\\end{btSect}\n";
309 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
310 // maybe a problem when a textclass has no "art" as
311 // part of its name, because it's than book.
312 // For the "official" lyx-layouts it's no problem to support
314 if (!contains(buffer.params().getTextClass().name(),
316 if (buffer.params().sides == OneSide) {
321 os << "\\cleardoublepage";
325 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
329 os << "\\addcontentsline{toc}{section}{\\refname}";
333 if (!db_out.empty() && !buffer.params().use_bibtopic){
334 docstring btprint = getParam("btprint");
335 if (btprint == "btPrintAll") {
336 os << "\\nocite{*}\n";
339 os << "\\bibliography{" << db_out << "}\n";
347 EmbeddedFileList const InsetBibtex::getFiles(Buffer const & buffer) const
349 FileName path(buffer.filePath());
352 EmbeddedFileList vec;
357 string bibfiles = to_utf8(getParam("bibfiles"));
358 string embedStatus = to_utf8(getParam("embed"));
359 bibfiles = split(bibfiles, tmp, ',');
360 embedStatus = split(embedStatus, emb, ',');
361 while (!tmp.empty()) {
363 EmbeddedFile file(changeExtension(tmp, "bib"), buffer.filePath());
364 // If the file structure is correct, this should not fail.
366 file.enable(buffer.embedded(), &buffer);
369 // this includes the cases when the embed parameter is empty
370 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
372 // If we didn't find a matching file name just fail silently
374 EmbeddedFile efile = EmbeddedFile(file.absFilename(), buffer.filePath());
375 efile.setEmbed(false);
376 efile.enable(buffer.embedded(), &buffer);
377 vec.push_back(efile);
381 // Get next file name
382 bibfiles = split(bibfiles, tmp, ',');
383 embedStatus = split(embedStatus, emb, ',');
391 // methods for parsing bibtex files
393 typedef map<docstring, docstring> VarMap;
395 /// remove whitespace characters, optionally a single comma,
396 /// and further whitespace characters from the stream.
397 /// @return true if a comma was found, false otherwise
399 bool removeWSAndComma(idocfstream & ifs) {
408 } while (ifs && isSpace(ch));
421 } while (ifs && isSpace(ch));
436 /// remove whitespace characters, read characer sequence
437 /// not containing whitespace characters or characters in
438 /// delimChars, and remove further whitespace characters.
440 /// @return true if a string of length > 0 could be read.
442 bool readTypeOrKey(docstring & val, idocfstream & ifs,
443 docstring const & delimChars, docstring const &illegalChars,
456 } while (ifs && isSpace(ch));
462 bool legalChar = true;
463 while (ifs && !isSpace(ch) &&
464 delimChars.find(ch) == docstring::npos &&
465 (legalChar = (illegalChars.find(ch) == docstring::npos))
468 if (chCase == makeLowerCase)
469 val += lowercase(ch);
481 while (ifs && isSpace(ch)) {
489 return val.length() > 0;
492 /// read subsequent bibtex values that are delimited with a #-character.
493 /// Concatenate all parts and replace names with the associated string in
494 /// the variable strings.
495 /// @return true if reading was successfull (all single parts were delimited
497 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
510 } while (ifs && isSpace(ch));
515 // check for field type
518 // read integer value
522 } while (ifs && isDigit(ch));
527 } else if (ch == '"' || ch == '{') {
529 char_type delim = ch == '"' ? '"': '}';
534 } while (ifs && isSpace(ch));
539 //We now have the first non-whitespace character
540 //We'll collapse adjacent whitespace.
541 bool lastWasWhiteSpace = false;
543 // inside this delimited text braces must match.
544 // Thus we can have a closing delimiter only
545 // when nestLevel == 0
548 while (ifs && (nestLevel > 0 || ch != delim)) {
550 lastWasWhiteSpace = true;
554 //We output the space only after we stop getting
555 //whitespace so as not to output any whitespace
556 //at the end of the value.
557 if (lastWasWhiteSpace) {
558 lastWasWhiteSpace = false;
564 // update nesting level
571 if (nestLevel < 0) return false;
588 // reading a string name
591 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
592 strName += lowercase(ch);
599 // replace the string with its assigned value or
600 // discard it if it's not assigned
601 if (strName.length()) {
602 VarMap::const_iterator pos = strings.find(strName);
603 if (pos != strings.end()) {
610 while (ifs && isSpace(ch)) {
617 // continue reading next value on concatenate with '#'
627 // This method returns a comma separated list of Bibtex entries
628 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
629 BiblioInfo & keylist, InsetIterator const & /*di*/) const
631 EmbeddedFileList const files = getFiles(buffer);
632 for (vector<EmbeddedFile>::const_iterator it = files.begin();
633 it != files.end(); ++ it) {
634 // This bibtex parser is a first step to parse bibtex files
637 // - it reads the whole bibtex entry and does a syntax check
638 // (matching delimiters, missing commas,...
639 // - it recovers from errors starting with the next @-character
640 // - it reads @string definitions and replaces them in the
642 // - it accepts more characters in keys or value names than
645 // Officially bibtex does only support ASCII, but in practice
646 // you can use the encoding of the main document as long as
647 // some elements like keys and names are pure ASCII. Therefore
648 // we convert the file from the buffer encoding.
649 // We don't restrict keys to ASCII in LyX, since our own
650 // InsetBibitem can generate non-ASCII keys, and nonstandard
651 // 8bit clean bibtex forks exist.
653 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
655 buffer.params().encoding().iconvName());
671 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
672 docstring(), makeLowerCase) || !ifs)
675 if (entryType == from_ascii("comment")) {
677 ifs.ignore(numeric_limits<int>::max(), '\n');
685 if ((ch != '(') && (ch != '{')) {
686 // invalid entry delimiter
692 if (entryType == from_ascii("string")) {
694 // read string and add it to the strings map
695 // (or replace it's old value)
699 if (!readTypeOrKey(name, ifs, from_ascii("="),
700 from_ascii("#{}(),"), makeLowerCase) || !ifs)
703 // next char must be an equal sign
705 if (!ifs || ch != '=')
708 if (!readValue(value, ifs, strings))
711 strings[name] = value;
713 } else if (entryType == from_ascii("preamble")) {
715 // preamble definitions are discarded.
716 // can they be of any use in lyx?
719 if (!readValue(value, ifs, strings))
724 // Citation entry. Try to read the key.
727 if (!readTypeOrKey(key, ifs, from_ascii(","),
728 from_ascii("}"), keepCase) || !ifs)
731 /////////////////////////////////////////////
732 // now we have a key, so we will add an entry
733 // (even if it's empty, as bibtex does)
735 // we now read the field = value pairs.
736 // all items must be separated by a comma. If
737 // it is missing the scanning of this entry is
738 // stopped and the next is searched.
742 docstring commaNewline;
744 BibTeXInfo keyvalmap;
745 keyvalmap.entryType = entryType;
747 bool readNext = removeWSAndComma(ifs);
749 while (ifs && readNext) {
752 if (!readTypeOrKey(name, ifs, from_ascii("="),
753 from_ascii("{}(),"), makeLowerCase) || !ifs)
756 // next char must be an equal sign
766 if (!readValue(value, ifs, strings))
769 keyvalmap[name] = value;
770 data += "\n\n" + value;
771 keylist.fieldNames.insert(name);
772 readNext = removeWSAndComma(ifs);
776 keylist.entryTypes.insert(entryType);
777 keyvalmap.allData = data;
778 keyvalmap.isBibTeX = true;
779 keyvalmap.bibKey = key;
780 keylist[key] = keyvalmap;
783 } //< for loop over files
788 bool InsetBibtex::addDatabase(string const & db)
791 string bibfiles(to_utf8(getParam("bibfiles")));
792 if (tokenPos(bibfiles, ',', db) == -1) {
793 if (!bibfiles.empty())
795 setParam("bibfiles", from_utf8(bibfiles + db));
802 bool InsetBibtex::delDatabase(string const & db)
805 string bibfiles(to_utf8(getParam("bibfiles")));
806 if (contains(bibfiles, db)) {
807 int const n = tokenPos(bibfiles, ',', db);
810 // this is not the first database
811 string tmp = ',' + bd;
812 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
814 // this is the first (or only) database
815 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
823 void InsetBibtex::validate(LaTeXFeatures & features) const
825 if (features.bufferParams().use_bibtopic)
826 features.require("bibtopic");
830 void InsetBibtex::registerEmbeddedFiles(Buffer const & buffer, EmbeddedFileList & files) const
832 EmbeddedFileList const dbs = getFiles(buffer);
833 for (vector<EmbeddedFile>::const_iterator it = dbs.begin();
834 it != dbs.end(); ++ it)
835 files.registerFile(*it, this, buffer);
839 void InsetBibtex::updateEmbeddedFile(Buffer const & buf, EmbeddedFile const & file)
841 // look for the item and update status
846 EmbeddedFileList dbs = getFiles(buf);
847 for (EmbeddedFileList::iterator it = dbs.begin();
848 it != dbs.end(); ++ it) {
850 if (it->absFilename() == file.absFilename())
851 it->setEmbed(file.embedded());
852 // write parameter string
858 bibfiles += from_utf8(it->outputFilename(buf.filePath()));
860 embed += from_utf8(it->inzipName());
862 setParam("bibfiles", bibfiles);
863 setParam("embed", embed);