]> git.lyx.org Git - lyx.git/blob - src/insets/insetbibtex.C
The speed patch: redraw only rows that have changed
[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.nice && IsFileReadable(in_file)) {
164
165                         database = FileName(database).mangledFilename();
166                         string const out_file = MakeAbsPath(database + ".bib",
167                                         buffer.getMasterBuffer()->temppath());
168
169                         bool const success = copy(in_file, out_file);
170                         if (!success) {
171                                 lyxerr << "Failed to copy '" << in_file
172                                        << "' to '" << out_file << "'"
173                                        << endl;
174                         }
175                 }
176
177                 if (it != begin)
178                         dbs << ',';
179                 dbs << latex_path(database);
180         }
181         string const db_out = dbs.str();
182
183         // Post this warning only once.
184         static bool warned_about_spaces = false;
185         if (!warned_about_spaces &&
186             runparams.nice && db_out.find(' ') != string::npos) {
187                 warned_about_spaces = true;
188
189                 Alert::warning(_("Export Warning!"),
190                                _("There are spaces in the paths to your BibTeX databases.\n"
191                                  "BibTeX will be unable to find them."));
192
193         }
194
195         // Style-Options
196         string style = getOptions(); // maybe empty! and with bibtotoc
197         string bibtotoc;
198         if (prefixIs(style, "bibtotoc")) {
199                 bibtotoc = "bibtotoc";
200                 if (contains(style, ',')) {
201                         style = split(style, bibtotoc, ',');
202                 }
203         }
204
205         // line count
206         int nlines = 0;
207
208         if (!style.empty()) {
209                 os << "\\bibliographystyle{"
210                    << latex_path(normalize_name(buffer, runparams, style, ".bst"))
211                    << "}\n";
212                 nlines += 1;
213         }
214
215         if (!db_out.empty() && buffer.params().use_bibtopic){
216                 os << "\\begin{btSect}{" << db_out << "}\n";
217                 string btprint = getSecOptions();
218                 if (btprint.empty())
219                         // default
220                         btprint = "btPrintCited";
221                 os << "\\" << btprint << "\n"
222                    << "\\end{btSect}\n";
223                 nlines += 3;
224         }
225
226         // bibtotoc-Option
227         if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
228                 // maybe a problem when a textclass has no "art" as
229                 // part of its name, because it's than book.
230                 // For the "official" lyx-layouts it's no problem to support
231                 // all well
232                 if (!contains(buffer.params().getLyXTextClass().name(),
233                               "art")) {
234                         if (buffer.params().sides == LyXTextClass::OneSide) {
235                                 // oneside
236                                 os << "\\clearpage";
237                         } else {
238                                 // twoside
239                                 os << "\\cleardoublepage";
240                         }
241
242                         // bookclass
243                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
244
245                 } else {
246                         // article class
247                         os << "\\addcontentsline{toc}{section}{\\refname}";
248                 }
249         }
250
251         if (!db_out.empty() && !buffer.params().use_bibtopic){
252                 os << "\\bibliography{" << db_out << "}\n";
253                 nlines += 1;
254         }
255
256         return nlines;
257 }
258
259
260 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
261 {
262         Path p(buffer.filePath());
263
264         vector<string> vec;
265
266         string tmp;
267         string bibfiles = getContents();
268         bibfiles = split(bibfiles, tmp, ',');
269         while (!tmp.empty()) {
270                 string file = findtexfile(ChangeExtension(tmp, "bib"), "bib");
271                 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
272
273                 // If we didn't find a matching file name just fail silently
274                 if (!file.empty())
275                         vec.push_back(file);
276
277                 // Get next file name
278                 bibfiles = split(bibfiles, tmp, ',');
279         }
280
281         return vec;
282 }
283
284
285 // This method returns a comma separated list of Bibtex entries
286 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
287                                   std::vector<std::pair<string, string> > & keys) const
288 {
289         vector<string> const files = getFiles(buffer);
290         for (vector<string>::const_iterator it = files.begin();
291              it != files.end(); ++ it) {
292                 // This is a _very_ simple parser for Bibtex database
293                 // files. All it does is to look for lines starting
294                 // in @ and not being @preamble and @string entries.
295                 // It does NOT do any syntax checking!
296                 ifstream ifs(it->c_str());
297                 string linebuf0;
298                 while (getline(ifs, linebuf0)) {
299                         string linebuf = trim(linebuf0);
300                         if (linebuf.empty()) continue;
301                         if (prefixIs(linebuf, "@")) {
302                                 linebuf = subst(linebuf, '{', '(');
303                                 string tmp;
304                                 linebuf = split(linebuf, tmp, '(');
305                                 tmp = ascii_lowercase(tmp);
306                                 if (!prefixIs(tmp, "@string")
307                                     && !prefixIs(tmp, "@preamble")) {
308                                         linebuf = split(linebuf, tmp, ',');
309                                         tmp = ltrim(tmp, " \t");
310                                         if (!tmp.empty()) {
311                                                 keys.push_back(pair<string,string>(tmp,string()));
312                                         }
313                                 }
314                         } else if (!keys.empty()) {
315                                 keys.back().second += linebuf + "\n";
316                         }
317                 }
318         }
319 }
320
321
322 bool InsetBibtex::addDatabase(string const & db)
323 {
324         string contents(getContents());
325         if (tokenPos(contents, ',', db) == -1) {
326                 if (!contents.empty())
327                         contents += ',';
328                 setContents(contents + db);
329                 return true;
330         }
331         return false;
332 }
333
334
335 bool InsetBibtex::delDatabase(string const & db)
336 {
337         string contents(getContents());
338         if (contains(contents, db)) {
339                 int const n = tokenPos(contents, ',', db);
340                 string bd = db;
341                 if (n > 0) {
342                         // this is not the first database
343                         string tmp = ',' + bd;
344                         setContents(subst(contents, tmp, ""));
345                 } else if (n == 0)
346                         // this is the first (or only) database
347                         setContents(split(contents, bd, ','));
348                 else
349                         return false;
350         }
351         return true;
352 }
353
354
355 void InsetBibtex::validate(LaTeXFeatures & features) const
356 {
357         if (features.bufferParams().use_bibtopic)
358                 features.require("bibtopic");
359 }