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