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