]> git.lyx.org Git - lyx.git/blob - src/insets/insetbibtex.C
hopefully fix tex2lyx linking.
[lyx.git] / src / insets / insetbibtex.C
1 /**
2  * \file insetbibtex.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insetbibtex.h"
14
15 #include "buffer.h"
16 #include "bufferparams.h"
17 #include "dispatchresult.h"
18 #include "debug.h"
19 #include "funcrequest.h"
20 #include "gettext.h"
21 #include "LaTeXFeatures.h"
22 #include "metricsinfo.h"
23 #include "outputparams.h"
24
25 #include "frontends/Alert.h"
26
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"
33
34 #include <boost/tokenizer.hpp>
35
36 #include <fstream>
37 #include <sstream>
38
39
40 namespace lyx {
41
42 using support::absolutePath;
43 using support::ascii_lowercase;
44 using support::changeExtension;
45 using support::contains;
46 using support::copy;
47 using support::DocFileName;
48 using support::findtexfile;
49 using support::isFileReadable;
50 using support::latex_path;
51 using support::ltrim;
52 using support::makeAbsPath;
53 using support::makeRelPath;
54 using support::Path;
55 using support::prefixIs;
56 using support::removeExtension;
57 using support::rtrim;
58 using support::split;
59 using support::subst;
60 using support::tokenPos;
61 using support::trim;
62
63 namespace Alert = frontend::Alert;
64 namespace os = support::os;
65
66 using std::endl;
67 using std::getline;
68 using std::string;
69 using std::ifstream;
70 using std::ostream;
71 using std::pair;
72 using std::vector;
73
74
75 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
76         : InsetCommand(p, "bibtex")
77 {}
78
79
80 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
81 {
82         return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
83 }
84
85
86 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
87 {
88         switch (cmd.action) {
89
90         case LFUN_INSET_MODIFY: {
91                 InsetCommandParams p("bibtex");
92                 InsetCommandMailer::string2params("bibtex", to_utf8(cmd.argument()), p);
93                 if (!p.getCmdName().empty()) {
94                         setParams(p);
95                         cur.buffer().updateBibfilesCache();
96                 } else
97                         cur.noUpdate();
98                 break;
99         }
100
101         default:
102                 InsetCommand::doDispatch(cur, cmd);
103                 break;
104         }
105 }
106
107
108 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
109 {
110         return _("BibTeX Generated Bibliography");
111 }
112
113
114 namespace {
115
116 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
117                       string const & name, string const & ext)
118 {
119         string const fname = makeAbsPath(name, buffer.filePath());
120         if (absolutePath(name) || !isFileReadable(fname + ext))
121                 return name;
122         else if (!runparams.nice)
123                 return fname;
124         else
125                 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
126 }
127
128 }
129
130
131 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
132                        OutputParams const & runparams) const
133 {
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}
142         // 4. \end{btSect}
143
144         // Database(s)
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
148         // all databases.
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;
156
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();
164
165         odocstringstream dbs;
166         for (Tokenizer::const_iterator it = begin; it != end; ++it) {
167                 docstring const input = trim(*it);
168                 // FIXME UNICODE
169                 string utf8input(to_utf8(input));
170                 string database =
171                         normalize_name(buffer, runparams, utf8input, ".bib");
172                 string const in_file = database + ".bib";
173
174                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
175                     isFileReadable(in_file)) {
176
177                         // mangledFilename() needs the extension
178                         database = removeExtension(DocFileName(in_file).mangledFilename());
179                         string const out_file = makeAbsPath(database + ".bib",
180                                         buffer.getMasterBuffer()->temppath());
181
182                         bool const success = copy(in_file, out_file);
183                         if (!success) {
184                                 lyxerr << "Failed to copy '" << in_file
185                                        << "' to '" << out_file << "'"
186                                        << endl;
187                         }
188                 }
189
190                 if (it != begin)
191                         dbs << ',';
192                 // FIXME UNICODE
193                 dbs << from_utf8(latex_path(database));
194         }
195         docstring const db_out = dbs.str();
196
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;
202
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."));
206
207         }
208
209         // Style-Options
210         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
211         string bibtotoc;
212         if (prefixIs(style, "bibtotoc")) {
213                 bibtotoc = "bibtotoc";
214                 if (contains(style, ',')) {
215                         style = split(style, bibtotoc, ',');
216                 }
217         }
218
219         // line count
220         int nlines = 0;
221
222         if (!style.empty()) {
223                 string base =
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
229                 // in the file name.
230                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
231                     isFileReadable(in_file)) {
232                         // use new style name
233                         base = removeExtension(
234                                         DocFileName(in_file).mangledFilename());
235                         string const out_file = makeAbsPath(base + ".bst",
236                                         buffer.getMasterBuffer()->temppath());
237                         bool const success = copy(in_file, out_file);
238                         if (!success) {
239                                 lyxerr << "Failed to copy '" << in_file
240                                        << "' to '" << out_file << "'"
241                                        << endl;
242                         }
243                 }
244                 // FIXME UNICODE
245                 os << "\\bibliographystyle{"
246                    << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
247                    << "}\n";
248                 nlines += 1;
249         }
250
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."));
258         }
259
260         if (!db_out.empty() && buffer.params().use_bibtopic){
261                 os << "\\begin{btSect}{" << db_out << "}\n";
262                 docstring btprint = getParam("btprint");
263                 if (btprint.empty())
264                         // default
265                         btprint = from_ascii("btPrintCited");
266                 os << "\\" << btprint << "\n"
267                    << "\\end{btSect}\n";
268                 nlines += 3;
269         }
270
271         // bibtotoc-Option
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
276                 // all well
277                 if (!contains(buffer.params().getLyXTextClass().name(),
278                               "art")) {
279                         if (buffer.params().sides == LyXTextClass::OneSide) {
280                                 // oneside
281                                 os << "\\clearpage";
282                         } else {
283                                 // twoside
284                                 os << "\\cleardoublepage";
285                         }
286
287                         // bookclass
288                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
289
290                 } else {
291                         // article class
292                         os << "\\addcontentsline{toc}{section}{\\refname}";
293                 }
294         }
295
296         if (!db_out.empty() && !buffer.params().use_bibtopic){
297                 os << "\\bibliography{" << db_out << "}\n";
298                 nlines += 1;
299         }
300
301         return nlines;
302 }
303
304
305 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
306 {
307         Path p(buffer.filePath());
308
309         vector<string> vec;
310
311         string tmp;
312         // FIXME UNICODE
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;
318
319                 // If we didn't find a matching file name just fail silently
320                 if (!file.empty())
321                         vec.push_back(file);
322
323                 // Get next file name
324                 bibfiles = split(bibfiles, tmp, ',');
325         }
326
327         return vec;
328 }
329
330
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
334 {
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());
343                 string linebuf0;
344                 while (getline(ifs, linebuf0)) {
345                         string linebuf = trim(linebuf0);
346                         if (linebuf.empty()) continue;
347                         if (prefixIs(linebuf, "@")) {
348                                 linebuf = subst(linebuf, '{', '(');
349                                 string tmp;
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");
356                                         if (!tmp.empty()) {
357                                                 keys.push_back(pair<string,string>(tmp,string()));
358                                         }
359                                 }
360                         } else if (!keys.empty()) {
361                                 keys.back().second += linebuf + "\n";
362                         }
363                 }
364         }
365 }
366
367
368 bool InsetBibtex::addDatabase(string const & db)
369 {
370         // FIXME UNICODE
371         string bibfiles(to_utf8(getParam("bibfiles")));
372         if (tokenPos(bibfiles, ',', db) == -1) {
373                 if (!bibfiles.empty())
374                         bibfiles += ',';
375                 setParam("bibfiles", from_utf8(bibfiles + db));
376                 return true;
377         }
378         return false;
379 }
380
381
382 bool InsetBibtex::delDatabase(string const & db)
383 {
384         // FIXME UNICODE
385         string bibfiles(to_utf8(getParam("bibfiles")));
386         if (contains(bibfiles, db)) {
387                 int const n = tokenPos(bibfiles, ',', db);
388                 string bd = db;
389                 if (n > 0) {
390                         // this is not the first database
391                         string tmp = ',' + bd;
392                         setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
393                 } else if (n == 0)
394                         // this is the first (or only) database
395                         setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
396                 else
397                         return false;
398         }
399         return true;
400 }
401
402
403 void InsetBibtex::validate(LaTeXFeatures & features) const
404 {
405         if (features.bufferParams().use_bibtopic)
406                 features.require("bibtopic");
407 }
408
409
410 } // namespace lyx