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
8 * Full author contact details are available in file CREDITS.
13 #include "insetbibtex.h"
16 #include "bufferparams.h"
17 #include "dispatchresult.h"
19 #include "funcrequest.h"
21 #include "LaTeXFeatures.h"
22 #include "metricsinfo.h"
23 #include "outputparams.h"
25 #include "frontends/Alert.h"
27 #include "support/filename.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/path.h"
34 #include <boost/tokenizer.hpp>
40 using lyx::support::absolutePath;
41 using lyx::support::ascii_lowercase;
42 using lyx::support::changeExtension;
43 using lyx::support::contains;
44 using lyx::support::copy;
45 using lyx::support::FileName;
46 using lyx::support::findtexfile;
47 using lyx::support::isFileReadable;
48 using lyx::support::latex_path;
49 using lyx::support::ltrim;
50 using lyx::support::makeAbsPath;
51 using lyx::support::makeRelPath;
52 using lyx::support::Path;
53 using lyx::support::prefixIs;
54 using lyx::support::removeExtension;
55 using lyx::support::rtrim;
56 using lyx::support::split;
57 using lyx::support::subst;
58 using lyx::support::tokenPos;
59 using lyx::support::trim;
61 namespace Alert = lyx::frontend::Alert;
62 namespace os = lyx::support::os;
73 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
74 : InsetCommand(p, "bibtex")
78 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
80 return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
84 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
88 case LFUN_INSET_MODIFY: {
90 InsetCommandMailer::string2params("bibtex", lyx::to_utf8(cmd.argument()), p);
91 if (!p.getCmdName().empty()) {
93 cur.buffer().updateBibfilesCache();
100 InsetCommand::doDispatch(cur, cmd);
106 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
108 return _("BibTeX Generated Bibliography");
114 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
115 string const & name, string const & ext)
117 string const fname = makeAbsPath(name, buffer.filePath());
118 if (absolutePath(name) || !isFileReadable(fname + ext))
120 else if (!runparams.nice)
123 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
129 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
130 OutputParams const & runparams) const
132 // the sequence of the commands:
133 // 1. \bibliographystyle{style}
134 // 2. \addcontentsline{...} - if option bibtotoc set
135 // 3. \bibliography{database}
136 // and with bibtopic:
137 // 1. \bibliographystyle{style}
138 // 2. \begin{btSect}{database}
139 // 3. \btPrint{Cited|NotCited|All}
143 // If we are processing the LaTeX file in a temp directory then
144 // copy the .bib databases to this temp directory, mangling their
145 // names in the process. Store this mangled name in the list of
147 // (We need to do all this because BibTeX *really*, *really*
148 // can't handle "files with spaces" and Windows users tend to
149 // use such filenames.)
150 // Otherwise, store the (maybe absolute) path to the original,
151 // unmangled database name.
152 typedef boost::char_separator<char> Separator;
153 typedef boost::tokenizer<Separator> Tokenizer;
155 Separator const separator(",");
156 Tokenizer const tokens(getContents(), separator);
157 Tokenizer::const_iterator const begin = tokens.begin();
158 Tokenizer::const_iterator const end = tokens.end();
160 std::ostringstream dbs;
161 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
162 string const input = trim(*it);
164 normalize_name(buffer, runparams, input, ".bib");
165 string const in_file = database + ".bib";
167 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
168 isFileReadable(in_file)) {
170 // mangledFilename() needs the extension
171 database = removeExtension(FileName(in_file).mangledFilename());
172 string const out_file = makeAbsPath(database + ".bib",
173 buffer.getMasterBuffer()->temppath());
175 bool const success = copy(in_file, out_file);
177 lyxerr << "Failed to copy '" << in_file
178 << "' to '" << out_file << "'"
185 dbs << latex_path(database);
187 string const db_out = dbs.str();
189 // Post this warning only once.
190 static bool warned_about_spaces = false;
191 if (!warned_about_spaces &&
192 runparams.nice && db_out.find(' ') != string::npos) {
193 warned_about_spaces = true;
196 Alert::warning(_("Export Warning!"),
197 _("There are spaces in the paths to your BibTeX databases.\n"
198 "BibTeX will be unable to find them."));
203 string style = getOptions(); // maybe empty! and with bibtotoc
205 if (prefixIs(style, "bibtotoc")) {
206 bibtotoc = "bibtotoc";
207 if (contains(style, ',')) {
208 style = split(style, bibtotoc, ',');
215 if (!style.empty()) {
217 normalize_name(buffer, runparams, style, ".bst");
218 string const in_file = base + ".bst";
219 // If this style does not come from texmf and we are not
220 // exporting to .tex copy it to the tmp directory.
221 // This prevents problems with spaces and 8bit charcaters
223 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
224 isFileReadable(in_file)) {
225 // use new style name
226 base = removeExtension(
227 FileName(in_file).mangledFilename());
228 string const out_file = makeAbsPath(base + ".bst",
229 buffer.getMasterBuffer()->temppath());
230 bool const success = copy(in_file, out_file);
232 lyxerr << "Failed to copy '" << in_file
233 << "' to '" << out_file << "'"
237 os << "\\bibliographystyle{"
238 << latex_path(normalize_name(buffer, runparams, base, ".bst"))
243 // Post this warning only once.
244 static bool warned_about_bst_spaces = false;
245 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
246 warned_about_bst_spaces = true;
248 Alert::warning(_("Export Warning!"),
249 _("There are spaces in the path to your BibTeX style file.\n"
250 "BibTeX will be unable to find it."));
253 if (!db_out.empty() && buffer.params().use_bibtopic){
254 os << "\\begin{btSect}{" << db_out << "}\n";
255 string btprint = getSecOptions();
258 btprint = "btPrintCited";
259 os << "\\" << btprint << "\n"
260 << "\\end{btSect}\n";
265 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
266 // maybe a problem when a textclass has no "art" as
267 // part of its name, because it's than book.
268 // For the "official" lyx-layouts it's no problem to support
270 if (!contains(buffer.params().getLyXTextClass().name(),
272 if (buffer.params().sides == LyXTextClass::OneSide) {
277 os << "\\cleardoublepage";
281 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
285 os << "\\addcontentsline{toc}{section}{\\refname}";
289 if (!db_out.empty() && !buffer.params().use_bibtopic){
290 os << "\\bibliography{" << db_out << "}\n";
298 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
300 Path p(buffer.filePath());
305 string bibfiles = getContents();
306 bibfiles = split(bibfiles, tmp, ',');
307 while (!tmp.empty()) {
308 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
309 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
311 // If we didn't find a matching file name just fail silently
315 // Get next file name
316 bibfiles = split(bibfiles, tmp, ',');
323 // This method returns a comma separated list of Bibtex entries
324 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
325 std::vector<std::pair<string, string> > & keys) const
327 vector<string> const files = getFiles(buffer);
328 for (vector<string>::const_iterator it = files.begin();
329 it != files.end(); ++ it) {
330 // This is a _very_ simple parser for Bibtex database
331 // files. All it does is to look for lines starting
332 // in @ and not being @preamble and @string entries.
333 // It does NOT do any syntax checking!
334 ifstream ifs(it->c_str());
336 while (getline(ifs, linebuf0)) {
337 string linebuf = trim(linebuf0);
338 if (linebuf.empty()) continue;
339 if (prefixIs(linebuf, "@")) {
340 linebuf = subst(linebuf, '{', '(');
342 linebuf = split(linebuf, tmp, '(');
343 tmp = ascii_lowercase(tmp);
344 if (!prefixIs(tmp, "@string")
345 && !prefixIs(tmp, "@preamble")) {
346 linebuf = split(linebuf, tmp, ',');
347 tmp = ltrim(tmp, " \t");
349 keys.push_back(pair<string,string>(tmp,string()));
352 } else if (!keys.empty()) {
353 keys.back().second += linebuf + "\n";
360 bool InsetBibtex::addDatabase(string const & db)
362 string contents(getContents());
363 if (tokenPos(contents, ',', db) == -1) {
364 if (!contents.empty())
366 setContents(contents + db);
373 bool InsetBibtex::delDatabase(string const & db)
375 string contents(getContents());
376 if (contains(contents, db)) {
377 int const n = tokenPos(contents, ',', db);
380 // this is not the first database
381 string tmp = ',' + bd;
382 setContents(subst(contents, tmp, ""));
384 // this is the first (or only) database
385 setContents(split(contents, bd, ','));
393 void InsetBibtex::validate(LaTeXFeatures & features) const
395 if (features.bufferParams().use_bibtopic)
396 features.require("bibtopic");