]> git.lyx.org Git - lyx.git/blob - src/insets/insetbibtex.C
move everything into namespace lyx
[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::FileName;
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> Separator;
155         typedef boost::tokenizer<Separator> Tokenizer;
156
157         Separator const separator(",");
158         Tokenizer const tokens(to_utf8(getParam("bibfiles")), separator);
159         Tokenizer::const_iterator const begin = tokens.begin();
160         Tokenizer::const_iterator const end = tokens.end();
161
162         std::ostringstream dbs;
163         for (Tokenizer::const_iterator it = begin; it != end; ++it) {
164                 string const input = trim(*it);
165                 string database =
166                         normalize_name(buffer, runparams, input, ".bib");
167                 string const in_file = database + ".bib";
168
169                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
170                     isFileReadable(in_file)) {
171
172                         // mangledFilename() needs the extension
173                         database = removeExtension(FileName(in_file).mangledFilename());
174                         string const out_file = makeAbsPath(database + ".bib",
175                                         buffer.getMasterBuffer()->temppath());
176
177                         bool const success = copy(in_file, out_file);
178                         if (!success) {
179                                 lyxerr << "Failed to copy '" << in_file
180                                        << "' to '" << out_file << "'"
181                                        << endl;
182                         }
183                 }
184
185                 if (it != begin)
186                         dbs << ',';
187                 dbs << latex_path(database);
188         }
189         // FIXME UNICODE
190         docstring const db_out = from_utf8(dbs.str());
191
192         // Post this warning only once.
193         static bool warned_about_spaces = false;
194         if (!warned_about_spaces &&
195             runparams.nice && db_out.find(' ') != docstring::npos) {
196                 warned_about_spaces = true;
197
198                 Alert::warning(_("Export Warning!"),
199                                _("There are spaces in the paths to your BibTeX databases.\n"
200                                               "BibTeX will be unable to find them."));
201
202         }
203
204         // Style-Options
205         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
206         string bibtotoc;
207         if (prefixIs(style, "bibtotoc")) {
208                 bibtotoc = "bibtotoc";
209                 if (contains(style, ',')) {
210                         style = split(style, bibtotoc, ',');
211                 }
212         }
213
214         // line count
215         int nlines = 0;
216
217         if (!style.empty()) {
218                 string base =
219                         normalize_name(buffer, runparams, style, ".bst");
220                 string const in_file = base + ".bst";
221                 // If this style does not come from texmf and we are not
222                 // exporting to .tex copy it to the tmp directory.
223                 // This prevents problems with spaces and 8bit charcaters
224                 // in the file name.
225                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
226                     isFileReadable(in_file)) {
227                         // use new style name
228                         base = removeExtension(
229                                         FileName(in_file).mangledFilename());
230                         string const out_file = makeAbsPath(base + ".bst",
231                                         buffer.getMasterBuffer()->temppath());
232                         bool const success = copy(in_file, out_file);
233                         if (!success) {
234                                 lyxerr << "Failed to copy '" << in_file
235                                        << "' to '" << out_file << "'"
236                                        << endl;
237                         }
238                 }
239                 // FIXME UNICODE
240                 os << "\\bibliographystyle{"
241                    << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
242                    << "}\n";
243                 nlines += 1;
244         }
245
246         // Post this warning only once.
247         static bool warned_about_bst_spaces = false;
248         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
249                 warned_about_bst_spaces = true;
250                 Alert::warning(_("Export Warning!"),
251                                _("There are spaces in the path to your BibTeX style file.\n"
252                                               "BibTeX will be unable to find it."));
253         }
254
255         if (!db_out.empty() && buffer.params().use_bibtopic){
256                 os << "\\begin{btSect}{" << db_out << "}\n";
257                 docstring btprint = getParam("btprint");
258                 if (btprint.empty())
259                         // default
260                         btprint = from_ascii("btPrintCited");
261                 os << "\\" << btprint << "\n"
262                    << "\\end{btSect}\n";
263                 nlines += 3;
264         }
265
266         // bibtotoc-Option
267         if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
268                 // maybe a problem when a textclass has no "art" as
269                 // part of its name, because it's than book.
270                 // For the "official" lyx-layouts it's no problem to support
271                 // all well
272                 if (!contains(buffer.params().getLyXTextClass().name(),
273                               "art")) {
274                         if (buffer.params().sides == LyXTextClass::OneSide) {
275                                 // oneside
276                                 os << "\\clearpage";
277                         } else {
278                                 // twoside
279                                 os << "\\cleardoublepage";
280                         }
281
282                         // bookclass
283                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
284
285                 } else {
286                         // article class
287                         os << "\\addcontentsline{toc}{section}{\\refname}";
288                 }
289         }
290
291         if (!db_out.empty() && !buffer.params().use_bibtopic){
292                 os << "\\bibliography{" << db_out << "}\n";
293                 nlines += 1;
294         }
295
296         return nlines;
297 }
298
299
300 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
301 {
302         Path p(buffer.filePath());
303
304         vector<string> vec;
305
306         string tmp;
307         // FIXME UNICODE
308         string bibfiles = to_utf8(getParam("bibfiles"));
309         bibfiles = split(bibfiles, tmp, ',');
310         while (!tmp.empty()) {
311                 string file = findtexfile(changeExtension(tmp, "bib"), "bib");
312                 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
313
314                 // If we didn't find a matching file name just fail silently
315                 if (!file.empty())
316                         vec.push_back(file);
317
318                 // Get next file name
319                 bibfiles = split(bibfiles, tmp, ',');
320         }
321
322         return vec;
323 }
324
325
326 // This method returns a comma separated list of Bibtex entries
327 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
328                                   std::vector<std::pair<string, string> > & keys) const
329 {
330         vector<string> const files = getFiles(buffer);
331         for (vector<string>::const_iterator it = files.begin();
332              it != files.end(); ++ it) {
333                 // This is a _very_ simple parser for Bibtex database
334                 // files. All it does is to look for lines starting
335                 // in @ and not being @preamble and @string entries.
336                 // It does NOT do any syntax checking!
337                 ifstream ifs(it->c_str());
338                 string linebuf0;
339                 while (getline(ifs, linebuf0)) {
340                         string linebuf = trim(linebuf0);
341                         if (linebuf.empty()) continue;
342                         if (prefixIs(linebuf, "@")) {
343                                 linebuf = subst(linebuf, '{', '(');
344                                 string tmp;
345                                 linebuf = split(linebuf, tmp, '(');
346                                 tmp = ascii_lowercase(tmp);
347                                 if (!prefixIs(tmp, "@string")
348                                     && !prefixIs(tmp, "@preamble")) {
349                                         linebuf = split(linebuf, tmp, ',');
350                                         tmp = ltrim(tmp, " \t");
351                                         if (!tmp.empty()) {
352                                                 keys.push_back(pair<string,string>(tmp,string()));
353                                         }
354                                 }
355                         } else if (!keys.empty()) {
356                                 keys.back().second += linebuf + "\n";
357                         }
358                 }
359         }
360 }
361
362
363 bool InsetBibtex::addDatabase(string const & db)
364 {
365         // FIXME UNICODE
366         string bibfiles(to_utf8(getParam("bibfiles")));
367         if (tokenPos(bibfiles, ',', db) == -1) {
368                 if (!bibfiles.empty())
369                         bibfiles += ',';
370                 setParam("bibfiles", from_utf8(bibfiles + db));
371                 return true;
372         }
373         return false;
374 }
375
376
377 bool InsetBibtex::delDatabase(string const & db)
378 {
379         // FIXME UNICODE
380         string bibfiles(to_utf8(getParam("bibfiles")));
381         if (contains(bibfiles, db)) {
382                 int const n = tokenPos(bibfiles, ',', db);
383                 string bd = db;
384                 if (n > 0) {
385                         // this is not the first database
386                         string tmp = ',' + bd;
387                         setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
388                 } else if (n == 0)
389                         // this is the first (or only) database
390                         setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
391                 else
392                         return false;
393         }
394         return true;
395 }
396
397
398 void InsetBibtex::validate(LaTeXFeatures & features) const
399 {
400         if (features.bufferParams().use_bibtopic)
401                 features.require("bibtopic");
402 }
403
404
405 } // namespace lyx