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::odocstream;
41 using lyx::support::absolutePath;
42 using lyx::support::ascii_lowercase;
43 using lyx::support::changeExtension;
44 using lyx::support::contains;
45 using lyx::support::copy;
46 using lyx::support::FileName;
47 using lyx::support::findtexfile;
48 using lyx::support::isFileReadable;
49 using lyx::support::latex_path;
50 using lyx::support::ltrim;
51 using lyx::support::makeAbsPath;
52 using lyx::support::makeRelPath;
53 using lyx::support::Path;
54 using lyx::support::prefixIs;
55 using lyx::support::removeExtension;
56 using lyx::support::rtrim;
57 using lyx::support::split;
58 using lyx::support::subst;
59 using lyx::support::tokenPos;
60 using lyx::support::trim;
62 namespace Alert = lyx::frontend::Alert;
63 namespace os = lyx::support::os;
74 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
75 : InsetCommand(p, "bibtex")
79 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
81 return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
85 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
89 case LFUN_INSET_MODIFY: {
90 InsetCommandParams p("bibtex");
91 InsetCommandMailer::string2params("bibtex", lyx::to_utf8(cmd.argument()), p);
92 if (!p.getCmdName().empty()) {
94 cur.buffer().updateBibfilesCache();
101 InsetCommand::doDispatch(cur, cmd);
107 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
109 return _("BibTeX Generated Bibliography");
115 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
116 string const & name, string const & ext)
118 string const fname = makeAbsPath(name, buffer.filePath());
119 if (absolutePath(name) || !isFileReadable(fname + ext))
121 else if (!runparams.nice)
124 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
130 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
131 OutputParams const & runparams) const
133 // the sequence of the commands:
134 // 1. \bibliographystyle{style}
135 // 2. \addcontentsline{...} - if option bibtotoc set
136 // 3. \bibliography{database}
137 // and with bibtopic:
138 // 1. \bibliographystyle{style}
139 // 2. \begin{btSect}{database}
140 // 3. \btPrint{Cited|NotCited|All}
144 // If we are processing the LaTeX file in a temp directory then
145 // copy the .bib databases to this temp directory, mangling their
146 // names in the process. Store this mangled name in the list of
148 // (We need to do all this because BibTeX *really*, *really*
149 // can't handle "files with spaces" and Windows users tend to
150 // use such filenames.)
151 // Otherwise, store the (maybe absolute) path to the original,
152 // unmangled database name.
153 typedef boost::char_separator<char> Separator;
154 typedef boost::tokenizer<Separator> Tokenizer;
156 Separator const separator(",");
157 Tokenizer const tokens(getContents(), separator);
158 Tokenizer::const_iterator const begin = tokens.begin();
159 Tokenizer::const_iterator const end = tokens.end();
161 std::ostringstream dbs;
162 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
163 string const input = trim(*it);
165 normalize_name(buffer, runparams, input, ".bib");
166 string const in_file = database + ".bib";
168 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
169 isFileReadable(in_file)) {
171 // mangledFilename() needs the extension
172 database = removeExtension(FileName(in_file).mangledFilename());
173 string const out_file = makeAbsPath(database + ".bib",
174 buffer.getMasterBuffer()->temppath());
176 bool const success = copy(in_file, out_file);
178 lyxerr << "Failed to copy '" << in_file
179 << "' to '" << out_file << "'"
186 dbs << latex_path(database);
188 string const db_out = dbs.str();
190 // Post this warning only once.
191 static bool warned_about_spaces = false;
192 if (!warned_about_spaces &&
193 runparams.nice && db_out.find(' ') != string::npos) {
194 warned_about_spaces = true;
197 Alert::warning(_("Export Warning!"),
198 _("There are spaces in the paths to your BibTeX databases.\n"
199 "BibTeX will be unable to find them."));
204 string style = getOptions(); // maybe empty! and with bibtotoc
206 if (prefixIs(style, "bibtotoc")) {
207 bibtotoc = "bibtotoc";
208 if (contains(style, ',')) {
209 style = split(style, bibtotoc, ',');
216 if (!style.empty()) {
218 normalize_name(buffer, runparams, style, ".bst");
219 string const in_file = base + ".bst";
220 // If this style does not come from texmf and we are not
221 // exporting to .tex copy it to the tmp directory.
222 // This prevents problems with spaces and 8bit charcaters
224 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
225 isFileReadable(in_file)) {
226 // use new style name
227 base = removeExtension(
228 FileName(in_file).mangledFilename());
229 string const out_file = makeAbsPath(base + ".bst",
230 buffer.getMasterBuffer()->temppath());
231 bool const success = copy(in_file, out_file);
233 lyxerr << "Failed to copy '" << in_file
234 << "' to '" << out_file << "'"
239 os << "\\bibliographystyle{"
240 << lyx::from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
245 // Post this warning only once.
246 static bool warned_about_bst_spaces = false;
247 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
248 warned_about_bst_spaces = true;
249 Alert::warning(_("Export Warning!"),
250 _("There are spaces in the path to your BibTeX style file.\n"
251 "BibTeX will be unable to find it."));
254 if (!db_out.empty() && buffer.params().use_bibtopic){
256 os << "\\begin{btSect}{" << lyx::from_utf8(db_out) << "}\n";
257 docstring btprint = getParam("btprint");
260 btprint = lyx::from_ascii("btPrintCited");
261 os << "\\" << btprint << "\n"
262 << "\\end{btSect}\n";
267 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
268 // maybe a problem when a textclass has no "art" as
269 // part of its name, because it's than book.
270 // For the "official" lyx-layouts it's no problem to support
272 if (!contains(buffer.params().getLyXTextClass().name(),
274 if (buffer.params().sides == LyXTextClass::OneSide) {
279 os << "\\cleardoublepage";
283 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
287 os << "\\addcontentsline{toc}{section}{\\refname}";
291 if (!db_out.empty() && !buffer.params().use_bibtopic){
293 os << "\\bibliography{" << lyx::from_utf8(db_out) << "}\n";
301 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
303 Path p(buffer.filePath());
308 string bibfiles = getContents();
309 bibfiles = split(bibfiles, tmp, ',');
310 while (!tmp.empty()) {
311 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
312 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
314 // If we didn't find a matching file name just fail silently
318 // Get next file name
319 bibfiles = split(bibfiles, tmp, ',');
326 // This method returns a comma separated list of Bibtex entries
327 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
328 std::vector<std::pair<string, string> > & keys) const
330 vector<string> const files = getFiles(buffer);
331 for (vector<string>::const_iterator it = files.begin();
332 it != files.end(); ++ it) {
333 // This is a _very_ simple parser for Bibtex database
334 // files. All it does is to look for lines starting
335 // in @ and not being @preamble and @string entries.
336 // It does NOT do any syntax checking!
337 ifstream ifs(it->c_str());
339 while (getline(ifs, linebuf0)) {
340 string linebuf = trim(linebuf0);
341 if (linebuf.empty()) continue;
342 if (prefixIs(linebuf, "@")) {
343 linebuf = subst(linebuf, '{', '(');
345 linebuf = split(linebuf, tmp, '(');
346 tmp = ascii_lowercase(tmp);
347 if (!prefixIs(tmp, "@string")
348 && !prefixIs(tmp, "@preamble")) {
349 linebuf = split(linebuf, tmp, ',');
350 tmp = ltrim(tmp, " \t");
352 keys.push_back(pair<string,string>(tmp,string()));
355 } else if (!keys.empty()) {
356 keys.back().second += linebuf + "\n";
363 bool InsetBibtex::addDatabase(string const & db)
365 string contents(getContents());
366 if (tokenPos(contents, ',', db) == -1) {
367 if (!contents.empty())
369 setContents(contents + db);
376 bool InsetBibtex::delDatabase(string const & db)
378 string contents(getContents());
379 if (contains(contents, db)) {
380 int const n = tokenPos(contents, ',', db);
383 // this is not the first database
384 string tmp = ',' + bd;
385 setContents(subst(contents, tmp, ""));
387 // this is the first (or only) database
388 setContents(split(contents, bd, ','));
396 void InsetBibtex::validate(LaTeXFeatures & features) const
398 if (features.bufferParams().use_bibtopic)
399 features.require("bibtopic");