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());
117 if (absolutePath(name) || !isFileReadable(FileName(fname + ext)))
119 else if (!runparams.nice)
122 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
128 int InsetBibtex::latex(Buffer const & buffer, odocstream & 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_type> Separator;
152 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
154 Separator const separator(from_ascii(",").c_str());
155 // The tokenizer must not be called with temporary strings, since
156 // it does not make a copy and uses iterators of the string further
157 // down. getParam returns a reference, so this is OK.
158 Tokenizer const tokens(getParam("bibfiles"), separator);
159 Tokenizer::const_iterator const begin = tokens.begin();
160 Tokenizer::const_iterator const end = tokens.end();
162 odocstringstream dbs;
163 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
164 docstring const input = trim(*it);
166 string utf8input(to_utf8(input));
168 normalize_name(buffer, runparams, utf8input, ".bib");
169 string const try_in_file = makeAbsPath(database + ".bib", buffer.filePath());
170 bool const not_from_texmf = isFileReadable(FileName(try_in_file));
172 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
175 // mangledFilename() needs the extension
176 DocFileName const in_file = DocFileName(try_in_file);
177 database = removeExtension(in_file.mangledFilename());
178 FileName const out_file = FileName(makeAbsPath(database + ".bib",
179 buffer.getMasterBuffer()->temppath()));
181 bool const success = copy(in_file, out_file);
183 lyxerr << "Failed to copy '" << in_file
184 << "' to '" << out_file << "'"
192 dbs << from_utf8(latex_path(database));
194 docstring const db_out = dbs.str();
196 // Post this warning only once.
197 static bool warned_about_spaces = false;
198 if (!warned_about_spaces &&
199 runparams.nice && db_out.find(' ') != docstring::npos) {
200 warned_about_spaces = true;
202 Alert::warning(_("Export Warning!"),
203 _("There are spaces in the paths to your BibTeX databases.\n"
204 "BibTeX will be unable to find them."));
209 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
211 if (prefixIs(style, "bibtotoc")) {
212 bibtotoc = "bibtotoc";
213 if (contains(style, ',')) {
214 style = split(style, bibtotoc, ',');
221 if (!style.empty()) {
223 normalize_name(buffer, runparams, style, ".bst");
224 string const try_in_file = makeAbsPath(base + ".bst", buffer.filePath());
225 bool const not_from_texmf = isFileReadable(FileName(try_in_file));
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 &&
232 // use new style name
233 DocFileName const in_file = DocFileName(try_in_file);
234 base = removeExtension(in_file.mangledFilename());
235 FileName const out_file = FileName(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<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
307 Path p(buffer.filePath());
309 vector<FileName> vec;
313 string bibfiles = to_utf8(getParam("bibfiles"));
314 bibfiles = split(bibfiles, tmp, ',');
315 while (!tmp.empty()) {
316 FileName const 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<FileName> const files = getFiles(buffer);
336 for (vector<FileName>::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!
343 // Officially bibtex does only support ASCII, but in practice
344 // you can use the encoding of the main document as long as
345 // some elements like keys and names are pure ASCII. Therefore
346 // we convert the file from the buffer encoding.
347 idocfstream ifs(it->toFilesystemEncoding().c_str(),
349 buffer.params().encoding().iconvName());
351 while (getline(ifs, linebuf0)) {
352 docstring linebuf = trim(linebuf0);
353 if (linebuf.empty()) continue;
354 if (prefixIs(linebuf, from_ascii("@"))) {
355 linebuf = subst(linebuf, '{', '(');
357 linebuf = split(linebuf, tmp, '(');
358 tmp = ascii_lowercase(tmp);
359 if (!prefixIs(tmp, from_ascii("@string")) &&
360 !prefixIs(tmp, from_ascii("@preamble"))) {
361 linebuf = split(linebuf, tmp, ',');
362 tmp = ltrim(tmp, " \t");
364 // to_ascii because bibtex keys may
365 // only consist of ASCII characters
366 keys.push_back(pair<string, string>(to_ascii(tmp), string()));
369 } else if (!keys.empty()) {
371 keys.back().second += to_utf8(linebuf + '\n');
378 bool InsetBibtex::addDatabase(string const & db)
381 string bibfiles(to_utf8(getParam("bibfiles")));
382 if (tokenPos(bibfiles, ',', db) == -1) {
383 if (!bibfiles.empty())
385 setParam("bibfiles", from_utf8(bibfiles + db));
392 bool InsetBibtex::delDatabase(string const & db)
395 string bibfiles(to_utf8(getParam("bibfiles")));
396 if (contains(bibfiles, db)) {
397 int const n = tokenPos(bibfiles, ',', db);
400 // this is not the first database
401 string tmp = ',' + bd;
402 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
404 // this is the first (or only) database
405 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
413 void InsetBibtex::validate(LaTeXFeatures & features) const
415 if (features.bufferParams().use_bibtopic)
416 features.require("bibtopic");