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", lyx::to_utf8(cmd.argument()), p);
89 if (!p.getCmdName().empty()) {
91 cur.buffer().updateBibfilesCache();
98 InsetCommand::doDispatch(cur, cmd);
104 string const InsetBibtex::getScreenLabel(Buffer const &) const
107 return lyx::to_utf8(_("BibTeX Generated Bibliography"));
113 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
114 string const & name, string const & ext)
116 string const fname = makeAbsPath(name, buffer.filePath());
117 if (absolutePath(name) || !isFileReadable(fname + ext))
119 else if (!runparams.nice)
122 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
128 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
129 OutputParams const & runparams) const
131 // the sequence of the commands:
132 // 1. \bibliographystyle{style}
133 // 2. \addcontentsline{...} - if option bibtotoc set
134 // 3. \bibliography{database}
135 // and with bibtopic:
136 // 1. \bibliographystyle{style}
137 // 2. \begin{btSect}{database}
138 // 3. \btPrint{Cited|NotCited|All}
142 // If we are processing the LaTeX file in a temp directory then
143 // copy the .bib databases to this temp directory, mangling their
144 // names in the process. Store this mangled name in the list of
146 // (We need to do all this because BibTeX *really*, *really*
147 // can't handle "files with spaces" and Windows users tend to
148 // use such filenames.)
149 // Otherwise, store the (maybe absolute) path to the original,
150 // unmangled database name.
151 typedef boost::char_separator<char> Separator;
152 typedef boost::tokenizer<Separator> Tokenizer;
154 Separator const separator(",");
155 Tokenizer const tokens(getContents(), separator);
156 Tokenizer::const_iterator const begin = tokens.begin();
157 Tokenizer::const_iterator const end = tokens.end();
159 std::ostringstream dbs;
160 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
161 string const input = trim(*it);
163 normalize_name(buffer, runparams, input, ".bib");
164 string const in_file = database + ".bib";
166 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
167 isFileReadable(in_file)) {
169 // mangledFilename() needs the extension
170 database = removeExtension(FileName(in_file).mangledFilename());
171 string const out_file = makeAbsPath(database + ".bib",
172 buffer.getMasterBuffer()->temppath());
174 bool const success = copy(in_file, out_file);
176 lyxerr << "Failed to copy '" << in_file
177 << "' to '" << out_file << "'"
184 dbs << latex_path(database);
186 string const db_out = dbs.str();
188 // Post this warning only once.
189 static bool warned_about_spaces = false;
190 if (!warned_about_spaces &&
191 runparams.nice && db_out.find(' ') != string::npos) {
192 warned_about_spaces = true;
195 Alert::warning(_("Export Warning!"),
196 _("There are spaces in the paths to your BibTeX databases.\n"
197 "BibTeX will be unable to find them."));
202 string style = getOptions(); // maybe empty! and with bibtotoc
204 if (prefixIs(style, "bibtotoc")) {
205 bibtotoc = "bibtotoc";
206 if (contains(style, ',')) {
207 style = split(style, bibtotoc, ',');
214 if (!style.empty()) {
216 normalize_name(buffer, runparams, style, ".bst");
217 string const in_file = base + ".bst";
218 // If this style does not come from texmf and we are not
219 // exporting to .tex copy it to the tmp directory.
220 // This prevents problems with spaces and 8bit charcaters
222 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
223 isFileReadable(in_file)) {
224 // use new style name
225 base = removeExtension(
226 FileName(in_file).mangledFilename());
227 string const out_file = makeAbsPath(base + ".bst",
228 buffer.getMasterBuffer()->temppath());
229 bool const success = copy(in_file, out_file);
231 lyxerr << "Failed to copy '" << in_file
232 << "' to '" << out_file << "'"
236 os << "\\bibliographystyle{"
237 << latex_path(normalize_name(buffer, runparams, base, ".bst"))
242 // Post this warning only once.
243 static bool warned_about_bst_spaces = false;
244 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
245 warned_about_bst_spaces = true;
247 Alert::warning(_("Export Warning!"),
248 _("There are spaces in the path to your BibTeX style file.\n"
249 "BibTeX will be unable to find it."));
252 if (!db_out.empty() && buffer.params().use_bibtopic){
253 os << "\\begin{btSect}{" << db_out << "}\n";
254 string btprint = getSecOptions();
257 btprint = "btPrintCited";
258 os << "\\" << btprint << "\n"
259 << "\\end{btSect}\n";
264 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
265 // maybe a problem when a textclass has no "art" as
266 // part of its name, because it's than book.
267 // For the "official" lyx-layouts it's no problem to support
269 if (!contains(buffer.params().getLyXTextClass().name(),
271 if (buffer.params().sides == LyXTextClass::OneSide) {
276 os << "\\cleardoublepage";
280 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
284 os << "\\addcontentsline{toc}{section}{\\refname}";
288 if (!db_out.empty() && !buffer.params().use_bibtopic){
289 os << "\\bibliography{" << db_out << "}\n";
297 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
299 Path p(buffer.filePath());
304 string bibfiles = getContents();
305 bibfiles = split(bibfiles, tmp, ',');
306 while (!tmp.empty()) {
307 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
308 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
310 // If we didn't find a matching file name just fail silently
314 // Get next file name
315 bibfiles = split(bibfiles, tmp, ',');
322 // This method returns a comma separated list of Bibtex entries
323 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
324 std::vector<std::pair<string, string> > & keys) const
326 vector<string> const files = getFiles(buffer);
327 for (vector<string>::const_iterator it = files.begin();
328 it != files.end(); ++ it) {
329 // This is a _very_ simple parser for Bibtex database
330 // files. All it does is to look for lines starting
331 // in @ and not being @preamble and @string entries.
332 // It does NOT do any syntax checking!
333 ifstream ifs(it->c_str());
335 while (getline(ifs, linebuf0)) {
336 string linebuf = trim(linebuf0);
337 if (linebuf.empty()) continue;
338 if (prefixIs(linebuf, "@")) {
339 linebuf = subst(linebuf, '{', '(');
341 linebuf = split(linebuf, tmp, '(');
342 tmp = ascii_lowercase(tmp);
343 if (!prefixIs(tmp, "@string")
344 && !prefixIs(tmp, "@preamble")) {
345 linebuf = split(linebuf, tmp, ',');
346 tmp = ltrim(tmp, " \t");
348 keys.push_back(pair<string,string>(tmp,string()));
351 } else if (!keys.empty()) {
352 keys.back().second += linebuf + "\n";
359 bool InsetBibtex::addDatabase(string const & db)
361 string contents(getContents());
362 if (tokenPos(contents, ',', db) == -1) {
363 if (!contents.empty())
365 setContents(contents + db);
372 bool InsetBibtex::delDatabase(string const & db)
374 string contents(getContents());
375 if (contains(contents, db)) {
376 int const n = tokenPos(contents, ',', db);
379 // this is not the first database
380 string tmp = ',' + bd;
381 setContents(subst(contents, tmp, ""));
383 // this is the first (or only) database
384 setContents(split(contents, bd, ','));
392 void InsetBibtex::validate(LaTeXFeatures & features) const
394 if (features.bufferParams().use_bibtopic)
395 features.require("bibtopic");