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