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"
20 #include "funcrequest.h"
22 #include "LaTeXFeatures.h"
23 #include "metricsinfo.h"
24 #include "outputparams.h"
26 #include "frontends/Alert.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 support::absolutePath;
40 using support::ascii_lowercase;
41 using support::changeExtension;
42 using support::contains;
44 using support::DocFileName;
45 using support::FileName;
46 using support::findtexfile;
47 using support::isFileReadable;
48 using support::latex_path;
50 using support::makeAbsPath;
51 using support::makeRelPath;
53 using support::prefixIs;
54 using support::removeExtension;
58 using support::tokenPos;
61 namespace Alert = frontend::Alert;
62 namespace os = support::os;
72 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
73 : InsetCommand(p, "bibtex")
77 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
79 return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
83 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
87 case LFUN_INSET_MODIFY: {
88 InsetCommandParams p("bibtex");
89 InsetCommandMailer::string2params("bibtex", to_utf8(cmd.argument()), p);
90 if (!p.getCmdName().empty()) {
92 cur.buffer().updateBibfilesCache();
99 InsetCommand::doDispatch(cur, cmd);
105 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
107 return _("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()).absFilename();
117 if (absolutePath(name) || !isFileReadable(FileName(fname + ext)))
119 else if (!runparams.nice)
123 return to_utf8(makeRelPath(from_utf8(fname),
124 from_utf8(buffer.getMasterBuffer()->filePath())));
130 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
131 OutputParams const & runparams) const
133 // the sequence of the commands:
134 // 1. \bibliographystyle{style}
135 // 2. \addcontentsline{...} - if option bibtotoc set
136 // 3. \bibliography{database}
137 // and with bibtopic:
138 // 1. \bibliographystyle{style}
139 // 2. \begin{btSect}{database}
140 // 3. \btPrint{Cited|NotCited|All}
144 // If we are processing the LaTeX file in a temp directory then
145 // copy the .bib databases to this temp directory, mangling their
146 // names in the process. Store this mangled name in the list of
148 // (We need to do all this because BibTeX *really*, *really*
149 // can't handle "files with spaces" and Windows users tend to
150 // use such filenames.)
151 // Otherwise, store the (maybe absolute) path to the original,
152 // unmangled database name.
153 typedef boost::char_separator<char_type> Separator;
154 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
156 Separator const separator(from_ascii(",").c_str());
157 // The tokenizer must not be called with temporary strings, since
158 // it does not make a copy and uses iterators of the string further
159 // down. getParam returns a reference, so this is OK.
160 Tokenizer const tokens(getParam("bibfiles"), separator);
161 Tokenizer::const_iterator const begin = tokens.begin();
162 Tokenizer::const_iterator const end = tokens.end();
164 odocstringstream dbs;
165 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
166 docstring const input = trim(*it);
168 string utf8input(to_utf8(input));
170 normalize_name(buffer, runparams, utf8input, ".bib");
171 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
172 bool const not_from_texmf = isFileReadable(try_in_file);
174 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
177 // mangledFilename() needs the extension
178 DocFileName const in_file = DocFileName(try_in_file);
179 database = removeExtension(in_file.mangledFilename());
180 FileName const out_file(makeAbsPath(database + ".bib",
181 buffer.getMasterBuffer()->temppath()));
183 bool const success = copy(in_file, out_file);
185 lyxerr << "Failed to copy '" << in_file
186 << "' to '" << out_file << "'"
194 dbs << from_utf8(latex_path(database));
196 docstring const db_out = dbs.str();
198 // Post this warning only once.
199 static bool warned_about_spaces = false;
200 if (!warned_about_spaces &&
201 runparams.nice && db_out.find(' ') != docstring::npos) {
202 warned_about_spaces = true;
204 Alert::warning(_("Export Warning!"),
205 _("There are spaces in the paths to your BibTeX databases.\n"
206 "BibTeX will be unable to find them."));
211 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
213 if (prefixIs(style, "bibtotoc")) {
214 bibtotoc = "bibtotoc";
215 if (contains(style, ',')) {
216 style = split(style, bibtotoc, ',');
223 if (!style.empty()) {
225 normalize_name(buffer, runparams, style, ".bst");
226 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
227 bool const not_from_texmf = isFileReadable(try_in_file);
228 // If this style does not come from texmf and we are not
229 // exporting to .tex copy it to the tmp directory.
230 // This prevents problems with spaces and 8bit charcaters
232 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
234 // use new style name
235 DocFileName const in_file = DocFileName(try_in_file);
236 base = removeExtension(in_file.mangledFilename());
237 FileName const out_file(makeAbsPath(base + ".bst",
238 buffer.getMasterBuffer()->temppath()));
239 bool const success = copy(in_file, out_file);
241 lyxerr << "Failed to copy '" << in_file
242 << "' to '" << out_file << "'"
247 os << "\\bibliographystyle{"
248 << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
253 // Post this warning only once.
254 static bool warned_about_bst_spaces = false;
255 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
256 warned_about_bst_spaces = true;
257 Alert::warning(_("Export Warning!"),
258 _("There are spaces in the path to your BibTeX style file.\n"
259 "BibTeX will be unable to find it."));
262 if (!db_out.empty() && buffer.params().use_bibtopic){
263 os << "\\begin{btSect}{" << db_out << "}\n";
264 docstring btprint = getParam("btprint");
267 btprint = from_ascii("btPrintCited");
268 os << "\\" << btprint << "\n"
269 << "\\end{btSect}\n";
274 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
275 // maybe a problem when a textclass has no "art" as
276 // part of its name, because it's than book.
277 // For the "official" lyx-layouts it's no problem to support
279 if (!contains(buffer.params().getLyXTextClass().name(),
281 if (buffer.params().sides == LyXTextClass::OneSide) {
286 os << "\\cleardoublepage";
290 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
294 os << "\\addcontentsline{toc}{section}{\\refname}";
298 if (!db_out.empty() && !buffer.params().use_bibtopic){
299 os << "\\bibliography{" << db_out << "}\n";
307 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
309 Path p(buffer.filePath());
311 vector<FileName> vec;
315 string bibfiles = to_utf8(getParam("bibfiles"));
316 bibfiles = split(bibfiles, tmp, ',');
317 while (!tmp.empty()) {
318 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
319 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
321 // If we didn't find a matching file name just fail silently
325 // Get next file name
326 bibfiles = split(bibfiles, tmp, ',');
333 // This method returns a comma separated list of Bibtex entries
334 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
335 std::vector<std::pair<string, docstring> > & keys) const
337 vector<FileName> const files = getFiles(buffer);
338 for (vector<FileName>::const_iterator it = files.begin();
339 it != files.end(); ++ it) {
340 // This is a _very_ simple parser for Bibtex database
341 // files. All it does is to look for lines starting
342 // in @ and not being @preamble and @string entries.
343 // It does NOT do any syntax checking!
345 // Officially bibtex does only support ASCII, but in practice
346 // you can use the encoding of the main document as long as
347 // some elements like keys and names are pure ASCII. Therefore
348 // we convert the file from the buffer encoding.
349 // We don't restrict keys to ASCII in LyX, since our own
350 // InsetBibitem can generate non-ASCII keys, and nonstandard
351 // 8bit clean bibtex forks exist.
352 idocfstream ifs(it->toFilesystemEncoding().c_str(),
354 buffer.params().encoding().iconvName());
356 while (getline(ifs, linebuf0)) {
357 docstring linebuf = trim(linebuf0);
360 if (prefixIs(linebuf, '@')) {
361 linebuf = subst(linebuf, '{', '(');
363 linebuf = split(linebuf, tmp, '(');
364 tmp = ascii_lowercase(tmp);
365 if (!prefixIs(tmp, from_ascii("@string")) &&
366 !prefixIs(tmp, from_ascii("@preamble"))) {
367 linebuf = split(linebuf, tmp, ',');
368 tmp = ltrim(tmp, " \t");
371 keys.push_back(pair<string, docstring>(
372 to_utf8(tmp), docstring()));
375 } else if (!keys.empty())
376 keys.back().second += linebuf + '\n';
382 bool InsetBibtex::addDatabase(string const & db)
385 string bibfiles(to_utf8(getParam("bibfiles")));
386 if (tokenPos(bibfiles, ',', db) == -1) {
387 if (!bibfiles.empty())
389 setParam("bibfiles", from_utf8(bibfiles + db));
396 bool InsetBibtex::delDatabase(string const & db)
399 string bibfiles(to_utf8(getParam("bibfiles")));
400 if (contains(bibfiles, db)) {
401 int const n = tokenPos(bibfiles, ',', db);
404 // this is not the first database
405 string tmp = ',' + bd;
406 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
408 // this is the first (or only) database
409 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
417 void InsetBibtex::validate(LaTeXFeatures & features) const
419 if (features.bufferParams().use_bibtopic)
420 features.require("bibtopic");