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"), 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
132 } catch (ExceptionMessage const & message) {
133 Alert::error(message.title_, message.details_);
134 // do not set parameter if an error happens
138 buffer().updateBibfilesCache();
143 InsetCommand::doDispatch(cur, cmd);
149 docstring InsetBibtex::screenLabel() const
151 return _("BibTeX Generated Bibliography");
155 static string normalizeName(Buffer const & buffer,
156 OutputParams const & runparams, 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())));
170 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
172 // the sequence of the commands:
173 // 1. \bibliographystyle{style}
174 // 2. \addcontentsline{...} - if option bibtotoc set
175 // 3. \bibliography{database}
176 // and with bibtopic:
177 // 1. \bibliographystyle{style}
178 // 2. \begin{btSect}{database}
179 // 3. \btPrint{Cited|NotCited|All}
183 // If we are processing the LaTeX file in a temp directory then
184 // copy the .bib databases to this temp directory, mangling their
185 // names in the process. Store this mangled name in the list of
187 // (We need to do all this because BibTeX *really*, *really*
188 // can't handle "files with spaces" and Windows users tend to
189 // use such filenames.)
190 // Otherwise, store the (maybe absolute) path to the original,
191 // unmangled database name.
192 EmbeddedFileList const bibs = embeddedFiles();
193 EmbeddedFileList::const_iterator it = bibs.begin();
194 EmbeddedFileList::const_iterator it_end = bibs.end();
195 odocstringstream dbs;
196 for (; it != it_end; ++it) {
197 string utf8input = removeExtension(it->availableFile().absFilename());
199 normalizeName(buffer(), runparams, utf8input, ".bib");
200 FileName const try_in_file =
201 makeAbsPath(database + ".bib", buffer().filePath());
202 bool const not_from_texmf = try_in_file.isReadableFile();
204 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
207 // mangledFilename() needs the extension
208 DocFileName const in_file = DocFileName(try_in_file);
209 database = removeExtension(in_file.mangledFilename());
210 FileName const out_file = makeAbsPath(database + ".bib",
211 buffer().masterBuffer()->temppath());
213 bool const success = in_file.copyTo(out_file);
215 lyxerr << "Failed to copy '" << in_file
216 << "' to '" << out_file << "'"
219 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
220 !isValidLaTeXFilename(database)) {
221 frontend::Alert::warning(_("Invalid filename"),
222 _("The following filename is likely to cause trouble "
223 "when running the exported file through LaTeX: ") +
224 from_utf8(database));
227 if (it != bibs.begin())
230 dbs << from_utf8(latex_path(database));
232 docstring const db_out = dbs.str();
234 // Post this warning only once.
235 static bool warned_about_spaces = false;
236 if (!warned_about_spaces &&
237 runparams.nice && db_out.find(' ') != docstring::npos) {
238 warned_about_spaces = true;
240 Alert::warning(_("Export Warning!"),
241 _("There are spaces in the paths to your BibTeX databases.\n"
242 "BibTeX will be unable to find them."));
246 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
248 if (prefixIs(style, "bibtotoc")) {
249 bibtotoc = "bibtotoc";
250 if (contains(style, ','))
251 style = split(style, bibtotoc, ',');
257 if (!style.empty()) {
258 string base = normalizeName(buffer(), runparams, style, ".bst");
259 FileName const try_in_file =
260 makeAbsPath(base + ".bst", buffer().filePath());
261 bool const not_from_texmf = try_in_file.isReadableFile();
262 // If this style does not come from texmf and we are not
263 // exporting to .tex copy it to the tmp directory.
264 // This prevents problems with spaces and 8bit charcaters
266 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
268 // use new style name
269 DocFileName const in_file = DocFileName(try_in_file);
270 base = removeExtension(in_file.mangledFilename());
271 FileName const out_file = makeAbsPath(base + ".bst",
272 buffer().masterBuffer()->temppath());
273 bool const success = in_file.copyTo(out_file);
275 lyxerr << "Failed to copy '" << in_file
276 << "' to '" << out_file << "'"
281 os << "\\bibliographystyle{"
282 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
287 // Post this warning only once.
288 static bool warned_about_bst_spaces = false;
289 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
290 warned_about_bst_spaces = true;
291 Alert::warning(_("Export Warning!"),
292 _("There are spaces in the path to your BibTeX style file.\n"
293 "BibTeX will be unable to find it."));
296 if (!db_out.empty() && buffer().params().use_bibtopic) {
297 os << "\\begin{btSect}{" << db_out << "}\n";
298 docstring btprint = getParam("btprint");
301 btprint = from_ascii("btPrintCited");
302 os << "\\" << btprint << "\n"
303 << "\\end{btSect}\n";
308 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
309 // maybe a problem when a textclass has no "art" as
310 // part of its name, because it's than book.
311 // For the "official" lyx-layouts it's no problem to support
313 if (!contains(buffer().params().documentClass().name(), "art")) {
314 if (buffer().params().sides == OneSide) {
319 os << "\\cleardoublepage";
323 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
327 os << "\\addcontentsline{toc}{section}{\\refname}";
331 if (!db_out.empty() && !buffer().params().use_bibtopic) {
332 docstring btprint = getParam("btprint");
333 if (btprint == "btPrintAll") {
334 os << "\\nocite{*}\n";
337 os << "\\bibliography{" << db_out << "}\n";
345 EmbeddedFileList InsetBibtex::embeddedFiles() const
347 FileName path(buffer().filePath());
350 EmbeddedFileList vec;
355 string bibfiles = to_utf8(getParam("bibfiles"));
356 string embedStatus = to_utf8(getParam("embed"));
357 bibfiles = split(bibfiles, tmp, ',');
358 embedStatus = split(embedStatus, emb, ',');
359 while (!tmp.empty()) {
361 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
362 // If the file structure is correct, this should not fail.
364 file.enable(buffer().embedded(), &buffer());
367 // this includes the cases when the embed parameter is empty
368 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
370 // If we didn't find a matching file name just fail silently
372 EmbeddedFile efile = EmbeddedFile(file.absFilename(), buffer().filePath());
373 efile.setEmbed(false);
374 efile.enable(buffer().embedded(), &buffer());
375 vec.push_back(efile);
379 // Get next file name
380 bibfiles = split(bibfiles, tmp, ',');
381 embedStatus = split(embedStatus, emb, ',');
389 // methods for parsing bibtex files
391 typedef map<docstring, docstring> VarMap;
393 /// remove whitespace characters, optionally a single comma,
394 /// and further whitespace characters from the stream.
395 /// @return true if a comma was found, false otherwise
397 bool removeWSAndComma(idocfstream & ifs) {
406 } while (ifs && isSpace(ch));
419 } while (ifs && isSpace(ch));
434 /// remove whitespace characters, read characer sequence
435 /// not containing whitespace characters or characters in
436 /// delimChars, and remove further whitespace characters.
438 /// @return true if a string of length > 0 could be read.
440 bool readTypeOrKey(docstring & val, idocfstream & ifs,
441 docstring const & delimChars, docstring const &illegalChars,
454 } while (ifs && isSpace(ch));
460 bool legalChar = true;
461 while (ifs && !isSpace(ch) &&
462 delimChars.find(ch) == docstring::npos &&
463 (legalChar = (illegalChars.find(ch) == docstring::npos))
466 if (chCase == makeLowerCase)
467 val += lowercase(ch);
479 while (ifs && isSpace(ch)) {
487 return val.length() > 0;
490 /// read subsequent bibtex values that are delimited with a #-character.
491 /// Concatenate all parts and replace names with the associated string in
492 /// the variable strings.
493 /// @return true if reading was successfull (all single parts were delimited
495 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
508 } while (ifs && isSpace(ch));
513 // check for field type
516 // read integer value
520 } while (ifs && isDigit(ch));
525 } else if (ch == '"' || ch == '{') {
527 char_type delim = ch == '"' ? '"': '}';
532 } while (ifs && isSpace(ch));
537 //We now have the first non-whitespace character
538 //We'll collapse adjacent whitespace.
539 bool lastWasWhiteSpace = false;
541 // inside this delimited text braces must match.
542 // Thus we can have a closing delimiter only
543 // when nestLevel == 0
546 while (ifs && (nestLevel > 0 || ch != delim)) {
548 lastWasWhiteSpace = true;
552 //We output the space only after we stop getting
553 //whitespace so as not to output any whitespace
554 //at the end of the value.
555 if (lastWasWhiteSpace) {
556 lastWasWhiteSpace = false;
562 // update nesting level
569 if (nestLevel < 0) return false;
586 // reading a string name
589 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
590 strName += lowercase(ch);
597 // replace the string with its assigned value or
598 // discard it if it's not assigned
599 if (strName.length()) {
600 VarMap::const_iterator pos = strings.find(strName);
601 if (pos != strings.end()) {
608 while (ifs && isSpace(ch)) {
615 // continue reading next value on concatenate with '#'
625 // This method returns a comma separated list of Bibtex entries
626 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
627 InsetIterator const & /*di*/) const
629 EmbeddedFileList const files = embeddedFiles();
630 for (vector<EmbeddedFile>::const_iterator it = files.begin();
631 it != files.end(); ++ it) {
632 // This bibtex parser is a first step to parse bibtex files
635 // - it reads the whole bibtex entry and does a syntax check
636 // (matching delimiters, missing commas,...
637 // - it recovers from errors starting with the next @-character
638 // - it reads @string definitions and replaces them in the
640 // - it accepts more characters in keys or value names than
643 // Officially bibtex does only support ASCII, but in practice
644 // you can use the encoding of the main document as long as
645 // some elements like keys and names are pure ASCII. Therefore
646 // we convert the file from the buffer encoding.
647 // We don't restrict keys to ASCII in LyX, since our own
648 // InsetBibitem can generate non-ASCII keys, and nonstandard
649 // 8bit clean bibtex forks exist.
651 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
652 ios_base::in, buffer().params().encoding().iconvName());
668 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
669 docstring(), makeLowerCase) || !ifs)
672 if (entryType == from_ascii("comment")) {
674 ifs.ignore(numeric_limits<int>::max(), '\n');
682 if ((ch != '(') && (ch != '{')) {
683 // invalid entry delimiter
689 if (entryType == from_ascii("string")) {
691 // read string and add it to the strings map
692 // (or replace it's old value)
696 if (!readTypeOrKey(name, ifs, from_ascii("="),
697 from_ascii("#{}(),"), makeLowerCase) || !ifs)
700 // next char must be an equal sign
702 if (!ifs || ch != '=')
705 if (!readValue(value, ifs, strings))
708 strings[name] = value;
710 } else if (entryType == from_ascii("preamble")) {
712 // preamble definitions are discarded.
713 // can they be of any use in lyx?
716 if (!readValue(value, ifs, strings))
721 // Citation entry. Try to read the key.
724 if (!readTypeOrKey(key, ifs, from_ascii(","),
725 from_ascii("}"), keepCase) || !ifs)
728 /////////////////////////////////////////////
729 // now we have a key, so we will add an entry
730 // (even if it's empty, as bibtex does)
732 // we now read the field = value pairs.
733 // all items must be separated by a comma. If
734 // it is missing the scanning of this entry is
735 // stopped and the next is searched.
739 docstring commaNewline;
741 BibTeXInfo keyvalmap(key, entryType);
743 bool readNext = removeWSAndComma(ifs);
745 while (ifs && readNext) {
748 if (!readTypeOrKey(name, ifs, from_ascii("="),
749 from_ascii("{}(),"), makeLowerCase) || !ifs)
752 // next char must be an equal sign
762 if (!readValue(value, ifs, strings))
765 keyvalmap[name] = value;
766 data += "\n\n" + value;
767 keylist.addFieldName(name);
768 readNext = removeWSAndComma(ifs);
772 keylist.addEntryType(entryType);
773 keyvalmap.setAllData(data);
774 keylist[key] = keyvalmap;
777 } //< for loop over files
782 bool InsetBibtex::addDatabase(string const & db)
785 string bibfiles(to_utf8(getParam("bibfiles")));
786 if (tokenPos(bibfiles, ',', db) == -1) {
787 if (!bibfiles.empty())
789 setParam("bibfiles", from_utf8(bibfiles + db));
796 bool InsetBibtex::delDatabase(string const & db)
799 string bibfiles(to_utf8(getParam("bibfiles")));
800 if (contains(bibfiles, db)) {
801 int const n = tokenPos(bibfiles, ',', db);
804 // this is not the first database
805 string tmp = ',' + bd;
806 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
808 // this is the first (or only) database
809 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
817 void InsetBibtex::validate(LaTeXFeatures & features) const
819 if (features.bufferParams().use_bibtopic)
820 features.require("bibtopic");
824 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
826 EmbeddedFileList const dbs = embeddedFiles();
827 for (vector<EmbeddedFile>::const_iterator it = dbs.begin();
828 it != dbs.end(); ++it)
829 files.registerFile(*it, this, buffer());
833 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
835 // look for the item and update status
840 EmbeddedFileList dbs = embeddedFiles();
841 for (EmbeddedFileList::iterator it = dbs.begin();
842 it != dbs.end(); ++it) {
844 if (it->absFilename() == file.absFilename())
845 it->setEmbed(file.embedded());
846 // write parameter string
853 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
855 embed += from_utf8(it->inzipName());
857 setParam("bibfiles", bibfiles);
858 setParam("embed", embed);