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
106 return _("BibTeX Generated Bibliography");
112 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
113 string const & name, string const & ext)
115 string const fname = makeAbsPath(name, buffer.filePath());
116 if (absolutePath(name) || !isFileReadable(fname + ext))
118 else if (!runparams.nice)
121 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
127 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
128 OutputParams const & runparams) const
130 // the sequence of the commands:
131 // 1. \bibliographystyle{style}
132 // 2. \addcontentsline{...} - if option bibtotoc set
133 // 3. \bibliography{database}
134 // and with bibtopic:
135 // 1. \bibliographystyle{style}
136 // 2. \begin{btSect}{database}
137 // 3. \btPrint{Cited|NotCited|All}
141 // If we are processing the LaTeX file in a temp directory then
142 // copy the .bib databases to this temp directory, mangling their
143 // names in the process. Store this mangled name in the list of
145 // (We need to do all this because BibTeX *really*, *really*
146 // can't handle "files with spaces" and Windows users tend to
147 // use such filenames.)
148 // Otherwise, store the (maybe absolute) path to the original,
149 // unmangled database name.
150 typedef boost::char_separator<char> Separator;
151 typedef boost::tokenizer<Separator> Tokenizer;
153 Separator const separator(",");
154 Tokenizer const tokens(getContents(), separator);
155 Tokenizer::const_iterator const begin = tokens.begin();
156 Tokenizer::const_iterator const end = tokens.end();
158 std::ostringstream dbs;
159 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
160 string const input = trim(*it);
162 normalize_name(buffer, runparams, input, ".bib");
163 string const in_file = database + ".bib";
165 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
166 isFileReadable(in_file)) {
168 // mangledFilename() needs the extension
169 database = removeExtension(FileName(in_file).mangledFilename());
170 string const out_file = makeAbsPath(database + ".bib",
171 buffer.getMasterBuffer()->temppath());
173 bool const success = copy(in_file, out_file);
175 lyxerr << "Failed to copy '" << in_file
176 << "' to '" << out_file << "'"
183 dbs << latex_path(database);
185 string const db_out = dbs.str();
187 // Post this warning only once.
188 static bool warned_about_spaces = false;
189 if (!warned_about_spaces &&
190 runparams.nice && db_out.find(' ') != string::npos) {
191 warned_about_spaces = true;
193 Alert::warning(_("Export Warning!"),
194 _("There are spaces in the paths to your BibTeX databases.\n"
195 "BibTeX will be unable to find them."));
200 string style = getOptions(); // maybe empty! and with bibtotoc
202 if (prefixIs(style, "bibtotoc")) {
203 bibtotoc = "bibtotoc";
204 if (contains(style, ',')) {
205 style = split(style, bibtotoc, ',');
212 if (!style.empty()) {
214 normalize_name(buffer, runparams, style, ".bst");
215 string const in_file = base + ".bst";
216 // If this style does not come from texmf and we are not
217 // exporting to .tex copy it to the tmp directory.
218 // This prevents problems with spaces and 8bit charcaters
220 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
221 isFileReadable(in_file)) {
222 // use new style name
223 base = removeExtension(
224 FileName(in_file).mangledFilename());
225 string const out_file = makeAbsPath(base + ".bst",
226 buffer.getMasterBuffer()->temppath());
227 bool const success = copy(in_file, out_file);
229 lyxerr << "Failed to copy '" << in_file
230 << "' to '" << out_file << "'"
234 os << "\\bibliographystyle{"
235 << latex_path(normalize_name(buffer, runparams, base, ".bst"))
240 // Post this warning only once.
241 static bool warned_about_bst_spaces = false;
242 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
243 warned_about_bst_spaces = true;
244 Alert::warning(_("Export Warning!"),
245 _("There are spaces in the path to your BibTeX style file.\n"
246 "BibTeX will be unable to find it."));
249 if (!db_out.empty() && buffer.params().use_bibtopic){
250 os << "\\begin{btSect}{" << db_out << "}\n";
251 string btprint = getSecOptions();
254 btprint = "btPrintCited";
255 os << "\\" << btprint << "\n"
256 << "\\end{btSect}\n";
261 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
262 // maybe a problem when a textclass has no "art" as
263 // part of its name, because it's than book.
264 // For the "official" lyx-layouts it's no problem to support
266 if (!contains(buffer.params().getLyXTextClass().name(),
268 if (buffer.params().sides == LyXTextClass::OneSide) {
273 os << "\\cleardoublepage";
277 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
281 os << "\\addcontentsline{toc}{section}{\\refname}";
285 if (!db_out.empty() && !buffer.params().use_bibtopic){
286 os << "\\bibliography{" << db_out << "}\n";
294 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
296 Path p(buffer.filePath());
301 string bibfiles = getContents();
302 bibfiles = split(bibfiles, tmp, ',');
303 while (!tmp.empty()) {
304 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
305 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
307 // If we didn't find a matching file name just fail silently
311 // Get next file name
312 bibfiles = split(bibfiles, tmp, ',');
319 // This method returns a comma separated list of Bibtex entries
320 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
321 std::vector<std::pair<string, string> > & keys) const
323 vector<string> const files = getFiles(buffer);
324 for (vector<string>::const_iterator it = files.begin();
325 it != files.end(); ++ it) {
326 // This is a _very_ simple parser for Bibtex database
327 // files. All it does is to look for lines starting
328 // in @ and not being @preamble and @string entries.
329 // It does NOT do any syntax checking!
330 ifstream ifs(it->c_str());
332 while (getline(ifs, linebuf0)) {
333 string linebuf = trim(linebuf0);
334 if (linebuf.empty()) continue;
335 if (prefixIs(linebuf, "@")) {
336 linebuf = subst(linebuf, '{', '(');
338 linebuf = split(linebuf, tmp, '(');
339 tmp = ascii_lowercase(tmp);
340 if (!prefixIs(tmp, "@string")
341 && !prefixIs(tmp, "@preamble")) {
342 linebuf = split(linebuf, tmp, ',');
343 tmp = ltrim(tmp, " \t");
345 keys.push_back(pair<string,string>(tmp,string()));
348 } else if (!keys.empty()) {
349 keys.back().second += linebuf + "\n";
356 bool InsetBibtex::addDatabase(string const & db)
358 string contents(getContents());
359 if (tokenPos(contents, ',', db) == -1) {
360 if (!contents.empty())
362 setContents(contents + db);
369 bool InsetBibtex::delDatabase(string const & db)
371 string contents(getContents());
372 if (contains(contents, db)) {
373 int const n = tokenPos(contents, ',', db);
376 // this is not the first database
377 string tmp = ',' + bd;
378 setContents(subst(contents, tmp, ""));
380 // this is the first (or only) database
381 setContents(split(contents, bd, ','));
389 void InsetBibtex::validate(LaTeXFeatures & features) const
391 if (features.bufferParams().use_bibtopic)
392 features.require("bibtopic");