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>
42 using support::absolutePath;
43 using support::ascii_lowercase;
44 using support::changeExtension;
45 using support::contains;
47 using support::FileName;
48 using support::findtexfile;
49 using support::isFileReadable;
50 using support::latex_path;
52 using support::makeAbsPath;
53 using support::makeRelPath;
55 using support::prefixIs;
56 using support::removeExtension;
60 using support::tokenPos;
63 namespace Alert = frontend::Alert;
64 namespace os = support::os;
75 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
76 : InsetCommand(p, "bibtex")
80 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
82 return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
86 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
90 case LFUN_INSET_MODIFY: {
91 InsetCommandParams p("bibtex");
92 InsetCommandMailer::string2params("bibtex", to_utf8(cmd.argument()), p);
93 if (!p.getCmdName().empty()) {
95 cur.buffer().updateBibfilesCache();
102 InsetCommand::doDispatch(cur, cmd);
108 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
110 return _("BibTeX Generated Bibliography");
116 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
117 string const & name, string const & ext)
119 string const fname = makeAbsPath(name, buffer.filePath());
120 if (absolutePath(name) || !isFileReadable(fname + ext))
122 else if (!runparams.nice)
125 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
131 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
132 OutputParams const & runparams) const
134 // the sequence of the commands:
135 // 1. \bibliographystyle{style}
136 // 2. \addcontentsline{...} - if option bibtotoc set
137 // 3. \bibliography{database}
138 // and with bibtopic:
139 // 1. \bibliographystyle{style}
140 // 2. \begin{btSect}{database}
141 // 3. \btPrint{Cited|NotCited|All}
145 // If we are processing the LaTeX file in a temp directory then
146 // copy the .bib databases to this temp directory, mangling their
147 // names in the process. Store this mangled name in the list of
149 // (We need to do all this because BibTeX *really*, *really*
150 // can't handle "files with spaces" and Windows users tend to
151 // use such filenames.)
152 // Otherwise, store the (maybe absolute) path to the original,
153 // unmangled database name.
154 typedef boost::char_separator<char_type> Separator;
155 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
157 Separator const separator(from_ascii(",").c_str());
158 // The tokenizer must not be called with temporary strings, since
159 // it does not make a copy and uses iterators of the string further
160 // down. getParam returns a reference, so this is OK.
161 Tokenizer const tokens(getParam("bibfiles"), separator);
162 Tokenizer::const_iterator const begin = tokens.begin();
163 Tokenizer::const_iterator const end = tokens.end();
165 odocstringstream dbs;
166 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
167 docstring const input = trim(*it);
169 string utf8input(to_utf8(input));
171 normalize_name(buffer, runparams, utf8input, ".bib");
172 string const in_file = database + ".bib";
174 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
175 isFileReadable(in_file)) {
177 // mangledFilename() needs the extension
178 database = removeExtension(FileName(in_file).mangledFilename());
179 string const out_file = makeAbsPath(database + ".bib",
180 buffer.getMasterBuffer()->temppath());
182 bool const success = copy(in_file, out_file);
184 lyxerr << "Failed to copy '" << in_file
185 << "' to '" << out_file << "'"
193 dbs << from_utf8(latex_path(database));
195 docstring const db_out = dbs.str();
197 // Post this warning only once.
198 static bool warned_about_spaces = false;
199 if (!warned_about_spaces &&
200 runparams.nice && db_out.find(' ') != docstring::npos) {
201 warned_about_spaces = true;
203 Alert::warning(_("Export Warning!"),
204 _("There are spaces in the paths to your BibTeX databases.\n"
205 "BibTeX will be unable to find them."));
210 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
212 if (prefixIs(style, "bibtotoc")) {
213 bibtotoc = "bibtotoc";
214 if (contains(style, ',')) {
215 style = split(style, bibtotoc, ',');
222 if (!style.empty()) {
224 normalize_name(buffer, runparams, style, ".bst");
225 string const in_file = base + ".bst";
226 // If this style does not come from texmf and we are not
227 // exporting to .tex copy it to the tmp directory.
228 // This prevents problems with spaces and 8bit charcaters
230 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
231 isFileReadable(in_file)) {
232 // use new style name
233 base = removeExtension(
234 FileName(in_file).mangledFilename());
235 string const out_file = makeAbsPath(base + ".bst",
236 buffer.getMasterBuffer()->temppath());
237 bool const success = copy(in_file, out_file);
239 lyxerr << "Failed to copy '" << in_file
240 << "' to '" << out_file << "'"
245 os << "\\bibliographystyle{"
246 << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
251 // Post this warning only once.
252 static bool warned_about_bst_spaces = false;
253 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
254 warned_about_bst_spaces = true;
255 Alert::warning(_("Export Warning!"),
256 _("There are spaces in the path to your BibTeX style file.\n"
257 "BibTeX will be unable to find it."));
260 if (!db_out.empty() && buffer.params().use_bibtopic){
261 os << "\\begin{btSect}{" << db_out << "}\n";
262 docstring btprint = getParam("btprint");
265 btprint = from_ascii("btPrintCited");
266 os << "\\" << btprint << "\n"
267 << "\\end{btSect}\n";
272 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
273 // maybe a problem when a textclass has no "art" as
274 // part of its name, because it's than book.
275 // For the "official" lyx-layouts it's no problem to support
277 if (!contains(buffer.params().getLyXTextClass().name(),
279 if (buffer.params().sides == LyXTextClass::OneSide) {
284 os << "\\cleardoublepage";
288 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
292 os << "\\addcontentsline{toc}{section}{\\refname}";
296 if (!db_out.empty() && !buffer.params().use_bibtopic){
297 os << "\\bibliography{" << db_out << "}\n";
305 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
307 Path p(buffer.filePath());
313 string bibfiles = to_utf8(getParam("bibfiles"));
314 bibfiles = split(bibfiles, tmp, ',');
315 while (!tmp.empty()) {
316 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
317 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
319 // If we didn't find a matching file name just fail silently
323 // Get next file name
324 bibfiles = split(bibfiles, tmp, ',');
331 // This method returns a comma separated list of Bibtex entries
332 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
333 std::vector<std::pair<string, string> > & keys) const
335 vector<string> const files = getFiles(buffer);
336 for (vector<string>::const_iterator it = files.begin();
337 it != files.end(); ++ it) {
338 // This is a _very_ simple parser for Bibtex database
339 // files. All it does is to look for lines starting
340 // in @ and not being @preamble and @string entries.
341 // It does NOT do any syntax checking!
342 ifstream ifs(it->c_str());
344 while (getline(ifs, linebuf0)) {
345 string linebuf = trim(linebuf0);
346 if (linebuf.empty()) continue;
347 if (prefixIs(linebuf, "@")) {
348 linebuf = subst(linebuf, '{', '(');
350 linebuf = split(linebuf, tmp, '(');
351 tmp = ascii_lowercase(tmp);
352 if (!prefixIs(tmp, "@string")
353 && !prefixIs(tmp, "@preamble")) {
354 linebuf = split(linebuf, tmp, ',');
355 tmp = ltrim(tmp, " \t");
357 keys.push_back(pair<string,string>(tmp,string()));
360 } else if (!keys.empty()) {
361 keys.back().second += linebuf + "\n";
368 bool InsetBibtex::addDatabase(string const & db)
371 string bibfiles(to_utf8(getParam("bibfiles")));
372 if (tokenPos(bibfiles, ',', db) == -1) {
373 if (!bibfiles.empty())
375 setParam("bibfiles", from_utf8(bibfiles + db));
382 bool InsetBibtex::delDatabase(string const & db)
385 string bibfiles(to_utf8(getParam("bibfiles")));
386 if (contains(bibfiles, db)) {
387 int const n = tokenPos(bibfiles, ',', db);
390 // this is not the first database
391 string tmp = ',' + bd;
392 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
394 // this is the first (or only) database
395 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
403 void InsetBibtex::validate(LaTeXFeatures & features) const
405 if (features.bufferParams().use_bibtopic)
406 features.require("bibtopic");