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