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