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::rtrim;
54 using lyx::support::split;
55 using lyx::support::subst;
56 using lyx::support::tokenPos;
57 using lyx::support::trim;
59 namespace os = lyx::support::os;
70 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
71 : InsetCommand(p, "bibtex")
75 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
77 return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
81 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
85 case LFUN_INSET_MODIFY: {
87 InsetCommandMailer::string2params("bibtex", cmd.argument, p);
88 if (!p.getCmdName().empty())
96 InsetCommand::doDispatch(cur, cmd);
102 string const InsetBibtex::getScreenLabel(Buffer const &) const
104 return _("BibTeX Generated Bibliography");
110 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
111 string const & name, string const & ext)
113 string const fname = MakeAbsPath(name, buffer.filePath());
114 if (AbsolutePath(name) || !IsFileReadable(fname + ext))
116 else if (!runparams.nice)
119 return MakeRelPath(fname, buffer.getMasterBuffer()->filePath());
125 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
126 OutputParams const & runparams) const
128 // the sequence of the commands:
129 // 1. \bibliographystyle{style}
130 // 2. \addcontentsline{...} - if option bibtotoc set
131 // 3. \bibliography{database}
132 // and with bibtopic:
133 // 1. \bibliographystyle{style}
134 // 2. \begin{btSect}{database}
135 // 3. \btPrint{Cited|NotCited|All}
139 // If we are processing the LaTeX file in a temp directory then
140 // copy the .bib databases to this temp directory, mangling their
141 // names in the process. Store this mangled name in the list of
143 // (We need to do all this because BibTeX *really*, *really*
144 // can't handle "files with spaces" and Windows users tend to
145 // use such filenames.)
146 // Otherwise, store the (maybe absolute) path to the original,
147 // unmangled database name.
148 typedef boost::char_separator<char> Separator;
149 typedef boost::tokenizer<Separator> Tokenizer;
151 Separator const separator(",");
152 Tokenizer const tokens(getContents(), separator);
153 Tokenizer::const_iterator const begin = tokens.begin();
154 Tokenizer::const_iterator const end = tokens.end();
156 std::ostringstream dbs;
157 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
158 string const input = trim(*it);
160 normalize_name(buffer, runparams, input, ".bib");
161 string const in_file = database + ".bib";
163 if (!runparams.nice && IsFileReadable(in_file)) {
165 database = FileName(database).mangledFilename();
166 string const out_file = MakeAbsPath(database + ".bib",
169 bool const success = copy(in_file, out_file);
171 lyxerr << "Failed to copy '" << in_file
172 << "' to '" << out_file << "'"
179 dbs << latex_path(database);
181 string const db_out = dbs.str();
183 // Post this warning only once.
184 static bool warned_about_spaces = false;
185 if (!warned_about_spaces &&
186 runparams.nice && db_out.find(' ') != string::npos) {
187 warned_about_spaces = true;
189 Alert::warning(_("Export Warning!"),
190 _("There are spaces in the paths to your BibTeX databases.\n"
191 "BibTeX will be unable to find them."));
196 string style = getOptions(); // maybe empty! and with bibtotoc
198 if (prefixIs(style, "bibtotoc")) {
199 bibtotoc = "bibtotoc";
200 if (contains(style, ',')) {
201 style = split(style, bibtotoc, ',');
208 if (!style.empty()) {
209 os << "\\bibliographystyle{"
210 << latex_path(normalize_name(buffer, runparams, style, ".bst"))
215 if (!db_out.empty() && buffer.params().use_bibtopic){
216 os << "\\begin{btSect}{" << db_out << "}\n";
217 string btprint = getSecOptions();
220 btprint = "btPrintCited";
221 os << "\\" << btprint << "\n"
222 << "\\end{btSect}\n";
227 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
228 // maybe a problem when a textclass has no "art" as
229 // part of its name, because it's than book.
230 // For the "official" lyx-layouts it's no problem to support
232 if (!contains(buffer.params().getLyXTextClass().name(),
234 if (buffer.params().sides == LyXTextClass::OneSide) {
239 os << "\\cleardoublepage";
243 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
247 os << "\\addcontentsline{toc}{section}{\\refname}";
251 if (!db_out.empty() && !buffer.params().use_bibtopic){
252 os << "\\bibliography{" << db_out << "}\n";
260 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
262 Path p(buffer.filePath());
267 string bibfiles = getContents();
268 bibfiles = split(bibfiles, tmp, ',');
269 while (!tmp.empty()) {
270 string file = findtexfile(ChangeExtension(tmp, "bib"), "bib");
271 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
273 // If we didn't find a matching file name just fail silently
277 // Get next file name
278 bibfiles = split(bibfiles, tmp, ',');
285 // This method returns a comma separated list of Bibtex entries
286 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
287 std::vector<std::pair<string, string> > & keys) const
289 vector<string> const files = getFiles(buffer);
290 for (vector<string>::const_iterator it = files.begin();
291 it != files.end(); ++ it) {
292 // This is a _very_ simple parser for Bibtex database
293 // files. All it does is to look for lines starting
294 // in @ and not being @preamble and @string entries.
295 // It does NOT do any syntax checking!
296 ifstream ifs(it->c_str());
298 while (getline(ifs, linebuf0)) {
299 string linebuf = trim(linebuf0);
300 if (linebuf.empty()) continue;
301 if (prefixIs(linebuf, "@")) {
302 linebuf = subst(linebuf, '{', '(');
304 linebuf = split(linebuf, tmp, '(');
305 tmp = ascii_lowercase(tmp);
306 if (!prefixIs(tmp, "@string")
307 && !prefixIs(tmp, "@preamble")) {
308 linebuf = split(linebuf, tmp, ',');
309 tmp = ltrim(tmp, " \t");
311 keys.push_back(pair<string,string>(tmp,string()));
314 } else if (!keys.empty()) {
315 keys.back().second += linebuf + "\n";
322 bool InsetBibtex::addDatabase(string const & db)
324 string contents(getContents());
325 if (tokenPos(contents, ',', db) == -1) {
326 if (!contents.empty())
328 setContents(contents + db);
335 bool InsetBibtex::delDatabase(string const & db)
337 string contents(getContents());
338 if (contains(contents, db)) {
339 int const n = tokenPos(contents, ',', db);
342 // this is not the first database
343 string tmp = ',' + bd;
344 setContents(subst(contents, tmp, ""));
346 // this is the first (or only) database
347 setContents(split(contents, bd, ','));
355 void InsetBibtex::validate(LaTeXFeatures & features) const
357 if (features.bufferParams().use_bibtopic)
358 features.require("bibtopic");