]> git.lyx.org Git - lyx.git/blob - src/insets/insetbibtex.C
Fix bug 2868
[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 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;
59
60 namespace os = lyx::support::os;
61
62 using std::endl;
63 using std::getline;
64 using std::string;
65 using std::ifstream;
66 using std::ostream;
67 using std::pair;
68 using std::vector;
69
70
71 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
72         : InsetCommand(p, "bibtex")
73 {}
74
75
76 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
77 {
78         return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
79 }
80
81
82 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
83 {
84         switch (cmd.action) {
85
86         case LFUN_INSET_MODIFY: {
87                 InsetCommandParams p;
88                 InsetCommandMailer::string2params("bibtex", lyx::to_utf8(cmd.argument()), p);
89                 if (!p.getCmdName().empty()) {
90                         setParams(p);
91                         cur.buffer().updateBibfilesCache();
92                 } else
93                         cur.noUpdate();
94                 break;
95         }
96
97         default:
98                 InsetCommand::doDispatch(cur, cmd);
99                 break;
100         }
101 }
102
103
104 string const InsetBibtex::getScreenLabel(Buffer const &) const
105 {
106         // FIXME UNICODE
107         return lyx::to_utf8(_("BibTeX Generated Bibliography"));
108 }
109
110
111 namespace {
112
113 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
114                       string const & name, string const & ext)
115 {
116         string const fname = makeAbsPath(name, buffer.filePath());
117         if (absolutePath(name) || !isFileReadable(fname + ext))
118                 return name;
119         else if (!runparams.nice)
120                 return fname;
121         else
122                 return makeRelPath(fname, buffer.getMasterBuffer()->filePath());
123 }
124
125 }
126
127
128 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
129                        OutputParams const & runparams) const
130 {
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}
139         // 4. \end{btSect}
140
141         // Database(s)
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
145         // all databases.
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> Separator;
152         typedef boost::tokenizer<Separator> Tokenizer;
153
154         Separator const separator(",");
155         Tokenizer const tokens(getContents(), separator);
156         Tokenizer::const_iterator const begin = tokens.begin();
157         Tokenizer::const_iterator const end = tokens.end();
158
159         std::ostringstream dbs;
160         for (Tokenizer::const_iterator it = begin; it != end; ++it) {
161                 string const input = trim(*it);
162                 string database =
163                         normalize_name(buffer, runparams, input, ".bib");
164                 string const in_file = database + ".bib";
165
166                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
167                     isFileReadable(in_file)) {
168
169                         // mangledFilename() needs the extension
170                         database = removeExtension(FileName(in_file).mangledFilename());
171                         string const out_file = makeAbsPath(database + ".bib",
172                                         buffer.getMasterBuffer()->temppath());
173
174                         bool const success = copy(in_file, out_file);
175                         if (!success) {
176                                 lyxerr << "Failed to copy '" << in_file
177                                        << "' to '" << out_file << "'"
178                                        << endl;
179                         }
180                 }
181
182                 if (it != begin)
183                         dbs << ',';
184                 dbs << latex_path(database);
185         }
186         string const db_out = dbs.str();
187
188         // Post this warning only once.
189         static bool warned_about_spaces = false;
190         if (!warned_about_spaces &&
191             runparams.nice && db_out.find(' ') != string::npos) {
192                 warned_about_spaces = true;
193
194                 // FIXME UNICODE
195                 Alert::warning(_("Export Warning!"),
196                                _("There are spaces in the paths to your BibTeX databases.\n"
197                                               "BibTeX will be unable to find them."));
198
199         }
200
201         // Style-Options
202         string style = getOptions(); // maybe empty! and with bibtotoc
203         string bibtotoc;
204         if (prefixIs(style, "bibtotoc")) {
205                 bibtotoc = "bibtotoc";
206                 if (contains(style, ',')) {
207                         style = split(style, bibtotoc, ',');
208                 }
209         }
210
211         // line count
212         int nlines = 0;
213
214         if (!style.empty()) {
215                 string base =
216                         normalize_name(buffer, runparams, style, ".bst");
217                 string const in_file = base + ".bst";
218                 // If this style does not come from texmf and we are not
219                 // exporting to .tex copy it to the tmp directory.
220                 // This prevents problems with spaces and 8bit charcaters
221                 // in the file name.
222                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
223                     isFileReadable(in_file)) {
224                         // use new style name
225                         base = removeExtension(
226                                         FileName(in_file).mangledFilename());
227                         string const out_file = makeAbsPath(base + ".bst",
228                                         buffer.getMasterBuffer()->temppath());
229                         bool const success = copy(in_file, out_file);
230                         if (!success) {
231                                 lyxerr << "Failed to copy '" << in_file
232                                        << "' to '" << out_file << "'"
233                                        << endl;
234                         }
235                 }
236                 os << "\\bibliographystyle{"
237                    << latex_path(normalize_name(buffer, runparams, base, ".bst"))
238                    << "}\n";
239                 nlines += 1;
240         }
241
242         // Post this warning only once.
243         static bool warned_about_bst_spaces = false;
244         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
245                 warned_about_bst_spaces = true;
246                 // FIXME UNICODE
247                 Alert::warning(_("Export Warning!"),
248                                _("There are spaces in the path to your BibTeX style file.\n"
249                                               "BibTeX will be unable to find it."));
250         }
251
252         if (!db_out.empty() && buffer.params().use_bibtopic){
253                 os << "\\begin{btSect}{" << db_out << "}\n";
254                 string btprint = getSecOptions();
255                 if (btprint.empty())
256                         // default
257                         btprint = "btPrintCited";
258                 os << "\\" << btprint << "\n"
259                    << "\\end{btSect}\n";
260                 nlines += 3;
261         }
262
263         // bibtotoc-Option
264         if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
265                 // maybe a problem when a textclass has no "art" as
266                 // part of its name, because it's than book.
267                 // For the "official" lyx-layouts it's no problem to support
268                 // all well
269                 if (!contains(buffer.params().getLyXTextClass().name(),
270                               "art")) {
271                         if (buffer.params().sides == LyXTextClass::OneSide) {
272                                 // oneside
273                                 os << "\\clearpage";
274                         } else {
275                                 // twoside
276                                 os << "\\cleardoublepage";
277                         }
278
279                         // bookclass
280                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
281
282                 } else {
283                         // article class
284                         os << "\\addcontentsline{toc}{section}{\\refname}";
285                 }
286         }
287
288         if (!db_out.empty() && !buffer.params().use_bibtopic){
289                 os << "\\bibliography{" << db_out << "}\n";
290                 nlines += 1;
291         }
292
293         return nlines;
294 }
295
296
297 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
298 {
299         Path p(buffer.filePath());
300
301         vector<string> vec;
302
303         string tmp;
304         string bibfiles = getContents();
305         bibfiles = split(bibfiles, tmp, ',');
306         while (!tmp.empty()) {
307                 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
308                 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
309
310                 // If we didn't find a matching file name just fail silently
311                 if (!file.empty())
312                         vec.push_back(file);
313
314                 // Get next file name
315                 bibfiles = split(bibfiles, tmp, ',');
316         }
317
318         return vec;
319 }
320
321
322 // This method returns a comma separated list of Bibtex entries
323 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
324                                   std::vector<std::pair<string, string> > & keys) const
325 {
326         vector<string> const files = getFiles(buffer);
327         for (vector<string>::const_iterator it = files.begin();
328              it != files.end(); ++ it) {
329                 // This is a _very_ simple parser for Bibtex database
330                 // files. All it does is to look for lines starting
331                 // in @ and not being @preamble and @string entries.
332                 // It does NOT do any syntax checking!
333                 ifstream ifs(it->c_str());
334                 string linebuf0;
335                 while (getline(ifs, linebuf0)) {
336                         string linebuf = trim(linebuf0);
337                         if (linebuf.empty()) continue;
338                         if (prefixIs(linebuf, "@")) {
339                                 linebuf = subst(linebuf, '{', '(');
340                                 string tmp;
341                                 linebuf = split(linebuf, tmp, '(');
342                                 tmp = ascii_lowercase(tmp);
343                                 if (!prefixIs(tmp, "@string")
344                                     && !prefixIs(tmp, "@preamble")) {
345                                         linebuf = split(linebuf, tmp, ',');
346                                         tmp = ltrim(tmp, " \t");
347                                         if (!tmp.empty()) {
348                                                 keys.push_back(pair<string,string>(tmp,string()));
349                                         }
350                                 }
351                         } else if (!keys.empty()) {
352                                 keys.back().second += linebuf + "\n";
353                         }
354                 }
355         }
356 }
357
358
359 bool InsetBibtex::addDatabase(string const & db)
360 {
361         string contents(getContents());
362         if (tokenPos(contents, ',', db) == -1) {
363                 if (!contents.empty())
364                         contents += ',';
365                 setContents(contents + db);
366                 return true;
367         }
368         return false;
369 }
370
371
372 bool InsetBibtex::delDatabase(string const & db)
373 {
374         string contents(getContents());
375         if (contains(contents, db)) {
376                 int const n = tokenPos(contents, ',', db);
377                 string bd = db;
378                 if (n > 0) {
379                         // this is not the first database
380                         string tmp = ',' + bd;
381                         setContents(subst(contents, tmp, ""));
382                 } else if (n == 0)
383                         // this is the first (or only) database
384                         setContents(split(contents, bd, ','));
385                 else
386                         return false;
387         }
388         return true;
389 }
390
391
392 void InsetBibtex::validate(LaTeXFeatures & features) const
393 {
394         if (features.bufferParams().use_bibtopic)
395                 features.require("bibtopic");
396 }