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