]> git.lyx.org Git - lyx.git/blob - src/insets/insetbibtex.C
74fc533887114e6ee471417d51d13cc87d146f2e
[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 "latexrunparams.h"
22 #include "metricsinfo.h"
23
24 #include "support/filetools.h"
25 #include "support/lstrings.h"
26 #include "support/os.h"
27 #include "support/path.h"
28
29 #include <fstream>
30
31 using lyx::support::ascii_lowercase;
32 using lyx::support::ChangeExtension;
33 using lyx::support::contains;
34 using lyx::support::findtexfile;
35 using lyx::support::IsFileReadable;
36 using lyx::support::ltrim;
37 using lyx::support::MakeAbsPath;
38 using lyx::support::Path;
39 using lyx::support::prefixIs;
40 using lyx::support::rtrim;
41 using lyx::support::split;
42 using lyx::support::subst;
43 using lyx::support::tokenPos;
44 using lyx::support::trim;
45
46 namespace os = lyx::support::os;
47
48 using std::endl;
49 using std::getline;
50 using std::string;
51 using std::ifstream;
52 using std::ostream;
53 using std::pair;
54 using std::vector;
55
56
57 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
58         : InsetCommand(p)
59 {}
60
61
62 InsetBibtex::~InsetBibtex()
63 {
64         InsetCommandMailer("bibtex", *this).hideDialog();
65 }
66
67
68 std::auto_ptr<InsetBase> InsetBibtex::clone() const
69 {
70         return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
71 }
72
73
74 void InsetBibtex::metrics(MetricsInfo & mi, Dimension & dim) const
75 {
76         InsetCommand::metrics(mi, dim);
77         int center_indent = (mi.base.textwidth - dim.wid) / 2;
78         Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
79         button().setBox(b);
80         dim.wid = mi.base.textwidth;
81         dim_ = dim;
82 }
83
84
85 void InsetBibtex::draw(PainterInfo & pi, int x, int y) const
86 {
87         InsetCommand::draw(pi, x + button().box().x1, y);
88 }
89
90
91 DispatchResult
92 InsetBibtex::priv_dispatch(FuncRequest const & cmd,
93                            idx_type & idx, pos_type & pos)
94 {
95         switch (cmd.action) {
96
97         case LFUN_INSET_DIALOG_SHOW:
98                 InsetCommandMailer("bibtex", *this).showDialog(cmd.view());
99                 return DispatchResult(DISPATCHED);
100         case LFUN_MOUSE_RELEASE:
101                 if (button().box().contains(cmd.x, cmd.y))
102                         InsetCommandMailer("bibtex", *this).showDialog(cmd.view());
103                 return DispatchResult(DISPATCHED);
104
105         case LFUN_INSET_MODIFY: {
106                 InsetCommandParams p;
107                 InsetCommandMailer::string2params(cmd.argument, p);
108                 if (p.getCmdName().empty())
109                         return DispatchResult(DISPATCHED);
110                 setParams(p);
111                 return  DispatchResult(DISPATCHED);
112         }
113
114         default:
115                 return InsetCommand::priv_dispatch(cmd, idx, pos);
116         }
117
118 }
119
120 string const InsetBibtex::getScreenLabel(Buffer const &) const
121 {
122         return _("BibTeX Generated References");
123 }
124
125
126 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
127                        LatexRunParams const & runparams) const
128 {
129         // changing the sequence of the commands
130         // 1. \bibliographystyle{style}
131         // 2. \addcontentsline{...} - if option bibtotoc set
132         // 3. \bibliography{database}
133         string adb;
134         string db_in = getContents();
135         db_in = split(db_in, adb, ',');
136
137         // Style-Options
138         string style = getOptions(); // maybe empty! and with bibtotoc
139         string bibtotoc;
140         if (prefixIs(style, "bibtotoc")) {
141                 bibtotoc = "bibtotoc";
142                 if (contains(style, ',')) {
143                         style = split(style, bibtotoc, ',');
144                 }
145         }
146
147         if (!runparams.nice
148             && IsFileReadable(MakeAbsPath(style, buffer.filePath()) + ".bst")) {
149                 style = MakeAbsPath(style, buffer.filePath());
150         }
151
152         if (!style.empty()) { // we want no \biblio...{}
153                 os << "\\bibliographystyle{" << style << "}\n";
154         }
155
156         // bibtotoc-Option
157         if (!bibtotoc.empty()) {
158                 // maybe a problem when a textclass has no "art" as
159                 // part of its name, because it's than book.
160                 // For the "official" lyx-layouts it's no problem to support
161                 // all well
162                 if (!contains(buffer.params().getLyXTextClass().name(),
163                               "art")) {
164                         if (buffer.params().sides == LyXTextClass::OneSide) {
165                                 // oneside
166                                 os << "\\clearpage";
167                         } else {
168                                 // twoside
169                                 os << "\\cleardoublepage";
170                         }
171
172                         // bookclass
173                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
174
175                 } else {
176                         // article class
177                         os << "\\addcontentsline{toc}{section}{\\refname}";
178                 }
179         }
180
181         // database
182         // If we generate in a temp dir, we might need to give an
183         // absolute path there. This is a bit complicated since we can
184         // have a comma-separated list of bibliographies
185         string db_out;
186         while (!adb.empty()) {
187                 if (!runparams.nice &&
188                     IsFileReadable(MakeAbsPath(adb, buffer.filePath())+".bib"))
189                          adb = os::external_path(MakeAbsPath(adb, buffer.filePath()));
190                 db_out += adb;
191                 db_out += ',';
192                 db_in = split(db_in, adb,',');
193         }
194         db_out = rtrim(db_out, ",");
195         os   << "\\bibliography{" << db_out << "}\n";
196         return 2;
197 }
198
199
200 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
201 {
202         Path p(buffer.filePath());
203
204         vector<string> vec;
205
206         string tmp;
207         string bibfiles = getContents();
208         bibfiles = split(bibfiles, tmp, ',');
209         while (!tmp.empty()) {
210                 string file = findtexfile(ChangeExtension(tmp, "bib"), "bib");
211                 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
212
213                 // If we didn't find a matching file name just fail silently
214                 if (!file.empty())
215                         vec.push_back(file);
216
217                 // Get next file name
218                 bibfiles = split(bibfiles, tmp, ',');
219         }
220
221         return vec;
222 }
223
224
225 // This method returns a comma separated list of Bibtex entries
226 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
227                                   std::vector<std::pair<string, string> > & keys) const
228 {
229         vector<string> const files = getFiles(buffer);
230         for (vector<string>::const_iterator it = files.begin();
231              it != files.end(); ++ it) {
232                 // This is a _very_ simple parser for Bibtex database
233                 // files. All it does is to look for lines starting
234                 // in @ and not being @preamble and @string entries.
235                 // It does NOT do any syntax checking!
236                 ifstream ifs(it->c_str());
237                 string linebuf0;
238                 while (getline(ifs, linebuf0)) {
239                         string linebuf = trim(linebuf0);
240                         if (linebuf.empty()) continue;
241                         if (prefixIs(linebuf, "@")) {
242                                 linebuf = subst(linebuf, '{', '(');
243                                 string tmp;
244                                 linebuf = split(linebuf, tmp, '(');
245                                 tmp = ascii_lowercase(tmp);
246                                 if (!prefixIs(tmp, "@string")
247                                     && !prefixIs(tmp, "@preamble")) {
248                                         linebuf = split(linebuf, tmp, ',');
249                                         tmp = ltrim(tmp, " \t");
250                                         if (!tmp.empty()) {
251                                                 keys.push_back(pair<string,string>(tmp,string()));
252                                         }
253                                 }
254                         } else if (!keys.empty()) {
255                                 keys.back().second += linebuf + "\n";
256                         }
257                 }
258         }
259 }
260
261
262 bool InsetBibtex::addDatabase(string const & db)
263 {
264         string contents(getContents());
265         if (!contains(contents, db)) {
266                 if (!contents.empty())
267                         contents += ',';
268                 setContents(contents + db);
269                 return true;
270         }
271         return false;
272 }
273
274
275 bool InsetBibtex::delDatabase(string const & db)
276 {
277         if (contains(getContents(), db)) {
278                 string bd = db;
279                 int const n = tokenPos(getContents(), ',', bd);
280                 if (n > 0) {
281                         // Weird code, would someone care to explain this?(Lgb)
282                         string tmp(", ");
283                         tmp += bd;
284                         setContents(subst(getContents(), tmp, ", "));
285                 } else if (n == 0)
286                         setContents(split(getContents(), bd, ','));
287                 else
288                         return false;
289         }
290         return true;
291 }