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>
39 using lyx::support::absolutePath;
40 using lyx::support::ascii_lowercase;
41 using lyx::support::changeExtension;
42 using lyx::support::contains;
43 using lyx::support::copy;
44 using lyx::support::FileName;
45 using lyx::support::findtexfile;
46 using lyx::support::isFileReadable;
47 using lyx::support::latex_path;
48 using lyx::support::ltrim;
49 using lyx::support::makeAbsPath;
50 using lyx::support::makeRelPath;
51 using lyx::support::Path;
52 using lyx::support::prefixIs;
53 using lyx::support::removeExtension;
54 using lyx::support::rtrim;
55 using lyx::support::split;
56 using lyx::support::subst;
57 using lyx::support::tokenPos;
58 using lyx::support::trim;
60 namespace os = lyx::support::os;
71 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
72 : InsetCommand(p, "bibtex")
76 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
78 return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
82 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
86 case LFUN_INSET_MODIFY: {
88 InsetCommandMailer::string2params("bibtex", cmd.argument, p);
89 if (!p.getCmdName().empty())
97 InsetCommand::doDispatch(cur, cmd);
103 string const InsetBibtex::getScreenLabel(Buffer const &) const
105 return _("BibTeX Generated Bibliography");
111 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
112 string const & name, string const & ext)
114 string const fname = makeAbsPath(name, buffer.filePath());
115 if (absolutePath(name) || !isFileReadable(fname + ext))
117 else if (!runparams.nice)
120 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
126 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
127 OutputParams const & runparams) const
129 // the sequence of the commands:
130 // 1. \bibliographystyle{style}
131 // 2. \addcontentsline{...} - if option bibtotoc set
132 // 3. \bibliography{database}
133 // and with bibtopic:
134 // 1. \bibliographystyle{style}
135 // 2. \begin{btSect}{database}
136 // 3. \btPrint{Cited|NotCited|All}
140 // If we are processing the LaTeX file in a temp directory then
141 // copy the .bib databases to this temp directory, mangling their
142 // names in the process. Store this mangled name in the list of
144 // (We need to do all this because BibTeX *really*, *really*
145 // can't handle "files with spaces" and Windows users tend to
146 // use such filenames.)
147 // Otherwise, store the (maybe absolute) path to the original,
148 // unmangled database name.
149 typedef boost::char_separator<char> Separator;
150 typedef boost::tokenizer<Separator> Tokenizer;
152 Separator const separator(",");
153 Tokenizer const tokens(getContents(), separator);
154 Tokenizer::const_iterator const begin = tokens.begin();
155 Tokenizer::const_iterator const end = tokens.end();
157 std::ostringstream dbs;
158 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
159 string const input = trim(*it);
161 normalize_name(buffer, runparams, input, ".bib");
162 string const in_file = database + ".bib";
164 if (!runparams.inComment && !runparams.nice &&
165 isFileReadable(in_file)) {
167 // mangledFilename() needs the extension
168 database = removeExtension(FileName(in_file).mangledFilename());
169 string const out_file = makeAbsPath(database + ".bib",
170 buffer.getMasterBuffer()->temppath());
172 bool const success = copy(in_file, out_file);
174 lyxerr << "Failed to copy '" << in_file
175 << "' to '" << out_file << "'"
182 dbs << latex_path(database);
184 string const db_out = dbs.str();
186 // Post this warning only once.
187 static bool warned_about_spaces = false;
188 if (!warned_about_spaces &&
189 runparams.nice && db_out.find(' ') != string::npos) {
190 warned_about_spaces = true;
192 Alert::warning(_("Export Warning!"),
193 _("There are spaces in the paths to your BibTeX databases.\n"
194 "BibTeX will be unable to find them."));
199 string style = getOptions(); // maybe empty! and with bibtotoc
201 if (prefixIs(style, "bibtotoc")) {
202 bibtotoc = "bibtotoc";
203 if (contains(style, ',')) {
204 style = split(style, bibtotoc, ',');
211 if (!style.empty()) {
213 normalize_name(buffer, runparams, style, ".bst");
214 string const in_file = base + ".bst";
215 // If this style does not come from texmf and we are not
216 // exporting to .tex copy it to the tmp directory.
217 // This prevents problems with spaces and 8bit charcaters
219 if (!runparams.inComment && !runparams.nice &&
220 isFileReadable(in_file)) {
221 // use new style name
222 base = removeExtension(
223 FileName(in_file).mangledFilename());
224 string const out_file = makeAbsPath(base + ".bst",
225 buffer.getMasterBuffer()->temppath());
226 bool const success = copy(in_file, out_file);
228 lyxerr << "Failed to copy '" << in_file
229 << "' to '" << out_file << "'"
233 os << "\\bibliographystyle{"
234 << latex_path(normalize_name(buffer, runparams, base, ".bst"))
239 // Post this warning only once.
240 static bool warned_about_bst_spaces = false;
241 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
242 warned_about_bst_spaces = true;
243 Alert::warning(_("Export Warning!"),
244 _("There are spaces in the path to your BibTeX style file.\n"
245 "BibTeX will be unable to find it."));
248 if (!db_out.empty() && buffer.params().use_bibtopic){
249 os << "\\begin{btSect}{" << db_out << "}\n";
250 string btprint = getSecOptions();
253 btprint = "btPrintCited";
254 os << "\\" << btprint << "\n"
255 << "\\end{btSect}\n";
260 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
261 // maybe a problem when a textclass has no "art" as
262 // part of its name, because it's than book.
263 // For the "official" lyx-layouts it's no problem to support
265 if (!contains(buffer.params().getLyXTextClass().name(),
267 if (buffer.params().sides == LyXTextClass::OneSide) {
272 os << "\\cleardoublepage";
276 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
280 os << "\\addcontentsline{toc}{section}{\\refname}";
284 if (!db_out.empty() && !buffer.params().use_bibtopic){
285 os << "\\bibliography{" << db_out << "}\n";
293 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
295 Path p(buffer.filePath());
300 string bibfiles = getContents();
301 bibfiles = split(bibfiles, tmp, ',');
302 while (!tmp.empty()) {
303 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
304 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
306 // If we didn't find a matching file name just fail silently
310 // Get next file name
311 bibfiles = split(bibfiles, tmp, ',');
318 // This method returns a comma separated list of Bibtex entries
319 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
320 std::vector<std::pair<string, string> > & keys) const
322 vector<string> const files = getFiles(buffer);
323 for (vector<string>::const_iterator it = files.begin();
324 it != files.end(); ++ it) {
325 // This is a _very_ simple parser for Bibtex database
326 // files. All it does is to look for lines starting
327 // in @ and not being @preamble and @string entries.
328 // It does NOT do any syntax checking!
329 ifstream ifs(it->c_str());
331 while (getline(ifs, linebuf0)) {
332 string linebuf = trim(linebuf0);
333 if (linebuf.empty()) continue;
334 if (prefixIs(linebuf, "@")) {
335 linebuf = subst(linebuf, '{', '(');
337 linebuf = split(linebuf, tmp, '(');
338 tmp = ascii_lowercase(tmp);
339 if (!prefixIs(tmp, "@string")
340 && !prefixIs(tmp, "@preamble")) {
341 linebuf = split(linebuf, tmp, ',');
342 tmp = ltrim(tmp, " \t");
344 keys.push_back(pair<string,string>(tmp,string()));
347 } else if (!keys.empty()) {
348 keys.back().second += linebuf + "\n";
355 bool InsetBibtex::addDatabase(string const & db)
357 string contents(getContents());
358 if (tokenPos(contents, ',', db) == -1) {
359 if (!contents.empty())
361 setContents(contents + db);
368 bool InsetBibtex::delDatabase(string const & db)
370 string contents(getContents());
371 if (contains(contents, db)) {
372 int const n = tokenPos(contents, ',', db);
375 // this is not the first database
376 string tmp = ',' + bd;
377 setContents(subst(contents, tmp, ""));
379 // this is the first (or only) database
380 setContents(split(contents, bd, ','));
388 void InsetBibtex::validate(LaTeXFeatures & features) const
390 if (features.bufferParams().use_bibtopic)
391 features.require("bibtopic");