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 typedef boost::char_separator<char_type> Separator;
196 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
198 Separator const separator(from_ascii(",").c_str());
199 // The tokenizer must not be called with temporary strings, since
200 // it does not make a copy and uses iterators of the string further
201 // down. getParam returns a reference, so this is OK.
202 Tokenizer const tokens(getParam("bibfiles"), separator);
203 Tokenizer::const_iterator const begin = tokens.begin();
204 Tokenizer::const_iterator const end = tokens.end();
206 odocstringstream dbs;
207 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
208 docstring const input = trim(*it);
210 string utf8input = to_utf8(input);
212 normalizeName(buffer, runparams, utf8input, ".bib");
213 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
214 bool const not_from_texmf = try_in_file.isReadableFile();
216 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
219 // mangledFilename() needs the extension
220 DocFileName const in_file = DocFileName(try_in_file);
221 database = removeExtension(in_file.mangledFilename());
222 FileName const out_file = makeAbsPath(database + ".bib",
223 buffer.masterBuffer()->temppath());
225 bool const success = in_file.copyTo(out_file);
227 lyxerr << "Failed to copy '" << in_file
228 << "' to '" << out_file << "'"
231 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
232 !isValidLaTeXFilename(database)) {
233 frontend::Alert::warning(_("Invalid filename"),
234 _("The following filename is likely to cause trouble "
235 "when running the exported file through LaTeX: ") +
236 from_utf8(database));
242 dbs << from_utf8(latex_path(database));
244 docstring const db_out = dbs.str();
246 // Post this warning only once.
247 static bool warned_about_spaces = false;
248 if (!warned_about_spaces &&
249 runparams.nice && db_out.find(' ') != docstring::npos) {
250 warned_about_spaces = true;
252 Alert::warning(_("Export Warning!"),
253 _("There are spaces in the paths to your BibTeX databases.\n"
254 "BibTeX will be unable to find them."));
258 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
260 if (prefixIs(style, "bibtotoc")) {
261 bibtotoc = "bibtotoc";
262 if (contains(style, ','))
263 style = split(style, bibtotoc, ',');
269 if (!style.empty()) {
270 string base = normalizeName(buffer, runparams, style, ".bst");
271 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
272 bool const not_from_texmf = try_in_file.isReadableFile();
273 // If this style does not come from texmf and we are not
274 // exporting to .tex copy it to the tmp directory.
275 // This prevents problems with spaces and 8bit charcaters
277 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
279 // use new style name
280 DocFileName const in_file = DocFileName(try_in_file);
281 base = removeExtension(in_file.mangledFilename());
282 FileName const out_file(makeAbsPath(base + ".bst",
283 buffer.masterBuffer()->temppath()));
284 bool const success = in_file.copyTo(out_file);
286 lyxerr << "Failed to copy '" << in_file
287 << "' to '" << out_file << "'"
292 os << "\\bibliographystyle{"
293 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
298 // Post this warning only once.
299 static bool warned_about_bst_spaces = false;
300 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
301 warned_about_bst_spaces = true;
302 Alert::warning(_("Export Warning!"),
303 _("There are spaces in the path to your BibTeX style file.\n"
304 "BibTeX will be unable to find it."));
307 if (!db_out.empty() && buffer.params().use_bibtopic){
308 os << "\\begin{btSect}{" << db_out << "}\n";
309 docstring btprint = getParam("btprint");
312 btprint = from_ascii("btPrintCited");
313 os << "\\" << btprint << "\n"
314 << "\\end{btSect}\n";
319 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
320 // maybe a problem when a textclass has no "art" as
321 // part of its name, because it's than book.
322 // For the "official" lyx-layouts it's no problem to support
324 if (!contains(buffer.params().getTextClass().name(),
326 if (buffer.params().sides == OneSide) {
331 os << "\\cleardoublepage";
335 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
339 os << "\\addcontentsline{toc}{section}{\\refname}";
343 if (!db_out.empty() && !buffer.params().use_bibtopic){
344 docstring btprint = getParam("btprint");
345 if (btprint == "btPrintAll") {
346 os << "\\nocite{*}\n";
349 os << "\\bibliography{" << db_out << "}\n";
357 EmbeddedFileList const InsetBibtex::getFiles(Buffer const & buffer) const
359 FileName path(buffer.filePath());
362 EmbeddedFileList vec;
367 string bibfiles = to_utf8(getParam("bibfiles"));
368 string embedStatus = to_utf8(getParam("embed"));
369 bibfiles = split(bibfiles, tmp, ',');
370 embedStatus = split(embedStatus, emb, ',');
371 while (!tmp.empty()) {
373 EmbeddedFile file(changeExtension(tmp, "bib"), buffer.filePath());
374 // If the file structure is correct, this should not fail.
376 file.enable(buffer.embedded(), &buffer);
379 // this includes the cases when the embed parameter is empty
380 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
382 // If we didn't find a matching file name just fail silently
384 EmbeddedFile efile = EmbeddedFile(file.absFilename(), buffer.filePath());
385 efile.setEmbed(false);
386 efile.enable(buffer.embedded(), &buffer);
387 vec.push_back(efile);
391 // Get next file name
392 bibfiles = split(bibfiles, tmp, ',');
393 embedStatus = split(embedStatus, emb, ',');
401 // methods for parsing bibtex files
403 typedef map<docstring, docstring> VarMap;
405 /// remove whitespace characters, optionally a single comma,
406 /// and further whitespace characters from the stream.
407 /// @return true if a comma was found, false otherwise
409 bool removeWSAndComma(idocfstream & ifs) {
418 } while (ifs && isSpace(ch));
431 } while (ifs && isSpace(ch));
446 /// remove whitespace characters, read characer sequence
447 /// not containing whitespace characters or characters in
448 /// delimChars, and remove further whitespace characters.
450 /// @return true if a string of length > 0 could be read.
452 bool readTypeOrKey(docstring & val, idocfstream & ifs,
453 docstring const & delimChars, docstring const &illegalChars,
466 } while (ifs && isSpace(ch));
472 bool legalChar = true;
473 while (ifs && !isSpace(ch) &&
474 delimChars.find(ch) == docstring::npos &&
475 (legalChar = (illegalChars.find(ch) == docstring::npos))
478 if (chCase == makeLowerCase)
479 val += lowercase(ch);
491 while (ifs && isSpace(ch)) {
499 return val.length() > 0;
502 /// read subsequent bibtex values that are delimited with a #-character.
503 /// Concatenate all parts and replace names with the associated string in
504 /// the variable strings.
505 /// @return true if reading was successfull (all single parts were delimited
507 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
520 } while (ifs && isSpace(ch));
525 // check for field type
528 // read integer value
532 } while (ifs && isDigit(ch));
537 } else if (ch == '"' || ch == '{') {
539 char_type delim = ch == '"' ? '"': '}';
544 } while (ifs && isSpace(ch));
549 //We now have the first non-whitespace character
550 //We'll collapse adjacent whitespace.
551 bool lastWasWhiteSpace = false;
553 // inside this delimited text braces must match.
554 // Thus we can have a closing delimiter only
555 // when nestLevel == 0
558 while (ifs && (nestLevel > 0 || ch != delim)) {
560 lastWasWhiteSpace = true;
564 //We output the space only after we stop getting
565 //whitespace so as not to output any whitespace
566 //at the end of the value.
567 if (lastWasWhiteSpace) {
568 lastWasWhiteSpace = false;
574 // update nesting level
581 if (nestLevel < 0) return false;
598 // reading a string name
601 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
602 strName += lowercase(ch);
609 // replace the string with its assigned value or
610 // discard it if it's not assigned
611 if (strName.length()) {
612 VarMap::const_iterator pos = strings.find(strName);
613 if (pos != strings.end()) {
620 while (ifs && isSpace(ch)) {
627 // continue reading next value on concatenate with '#'
637 // This method returns a comma separated list of Bibtex entries
638 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
639 BiblioInfo & keylist, InsetIterator const & /*di*/) const
641 EmbeddedFileList const files = getFiles(buffer);
642 for (vector<EmbeddedFile>::const_iterator it = files.begin();
643 it != files.end(); ++ it) {
644 // This bibtex parser is a first step to parse bibtex files
647 // - it reads the whole bibtex entry and does a syntax check
648 // (matching delimiters, missing commas,...
649 // - it recovers from errors starting with the next @-character
650 // - it reads @string definitions and replaces them in the
652 // - it accepts more characters in keys or value names than
655 // Officially bibtex does only support ASCII, but in practice
656 // you can use the encoding of the main document as long as
657 // some elements like keys and names are pure ASCII. Therefore
658 // we convert the file from the buffer encoding.
659 // We don't restrict keys to ASCII in LyX, since our own
660 // InsetBibitem can generate non-ASCII keys, and nonstandard
661 // 8bit clean bibtex forks exist.
663 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
665 buffer.params().encoding().iconvName());
681 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
682 docstring(), makeLowerCase) || !ifs)
685 if (entryType == from_ascii("comment")) {
687 ifs.ignore(numeric_limits<int>::max(), '\n');
695 if ((ch != '(') && (ch != '{')) {
696 // invalid entry delimiter
702 if (entryType == from_ascii("string")) {
704 // read string and add it to the strings map
705 // (or replace it's old value)
709 if (!readTypeOrKey(name, ifs, from_ascii("="),
710 from_ascii("#{}(),"), makeLowerCase) || !ifs)
713 // next char must be an equal sign
715 if (!ifs || ch != '=')
718 if (!readValue(value, ifs, strings))
721 strings[name] = value;
723 } else if (entryType == from_ascii("preamble")) {
725 // preamble definitions are discarded.
726 // can they be of any use in lyx?
729 if (!readValue(value, ifs, strings))
734 // Citation entry. Try to read the key.
737 if (!readTypeOrKey(key, ifs, from_ascii(","),
738 from_ascii("}"), keepCase) || !ifs)
741 /////////////////////////////////////////////
742 // now we have a key, so we will add an entry
743 // (even if it's empty, as bibtex does)
745 // we now read the field = value pairs.
746 // all items must be separated by a comma. If
747 // it is missing the scanning of this entry is
748 // stopped and the next is searched.
752 docstring commaNewline;
754 BibTeXInfo keyvalmap;
755 keyvalmap.entryType = entryType;
757 bool readNext = removeWSAndComma(ifs);
759 while (ifs && readNext) {
762 if (!readTypeOrKey(name, ifs, from_ascii("="),
763 from_ascii("{}(),"), makeLowerCase) || !ifs)
766 // next char must be an equal sign
776 if (!readValue(value, ifs, strings))
779 keyvalmap[name] = value;
780 data += "\n\n" + value;
781 keylist.fieldNames.insert(name);
782 readNext = removeWSAndComma(ifs);
786 keylist.entryTypes.insert(entryType);
787 keyvalmap.allData = data;
788 keyvalmap.isBibTeX = true;
789 keyvalmap.bibKey = key;
790 keylist[key] = keyvalmap;
793 } //< for loop over files
798 bool InsetBibtex::addDatabase(string const & db)
801 string bibfiles(to_utf8(getParam("bibfiles")));
802 if (tokenPos(bibfiles, ',', db) == -1) {
803 if (!bibfiles.empty())
805 setParam("bibfiles", from_utf8(bibfiles + db));
812 bool InsetBibtex::delDatabase(string const & db)
815 string bibfiles(to_utf8(getParam("bibfiles")));
816 if (contains(bibfiles, db)) {
817 int const n = tokenPos(bibfiles, ',', db);
820 // this is not the first database
821 string tmp = ',' + bd;
822 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
824 // this is the first (or only) database
825 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
833 void InsetBibtex::validate(LaTeXFeatures & features) const
835 if (features.bufferParams().use_bibtopic)
836 features.require("bibtopic");
840 void InsetBibtex::registerEmbeddedFiles(Buffer const & buffer, EmbeddedFileList & files) const
842 EmbeddedFileList const dbs = getFiles(buffer);
843 for (vector<EmbeddedFile>::const_iterator it = dbs.begin();
844 it != dbs.end(); ++ it)
845 files.registerFile(*it, this, buffer);
849 void InsetBibtex::updateEmbeddedFile(Buffer const & buf, EmbeddedFile const & file)
851 // look for the item and update status
856 EmbeddedFileList dbs = getFiles(buf);
857 for (EmbeddedFileList::iterator it = dbs.begin();
858 it != dbs.end(); ++ it) {
860 if (it->absFilename() == file.absFilename())
861 it->setEmbed(file.embedded());
862 // write parameter string
868 bibfiles += from_utf8(it->outputFilename(buf.filePath()));
870 embed += from_utf8(it->inzipName());
872 setParam("bibfiles", bibfiles);
873 setParam("embed", embed);