]> git.lyx.org Git - lyx.git/blob - src/insets/insetbib.C
You won't believe I SOLVED the smart insettext-update, finally!
[lyx.git] / src / insets / insetbib.C
1 #include <config.h>
2
3 #include <fstream>
4 #include <cstdlib>
5
6 #ifdef __GNUG__
7 #pragma implementation
8 #endif
9
10 #include FORMS_H_LOCATION  
11 #include "insetbib.h"
12 #include "combox.h"
13 #include "buffer.h"
14 #include "debug.h"
15 #include "lyx_gui_misc.h"
16 #include "BufferView.h"
17 #include "gettext.h"
18 #include "bibforms.h"
19 #include "lyxtext.h"
20 #include "support/filetools.h"
21 #include "support/path.h"
22
23 using std::ostream;
24 using std::ifstream;
25 using std::getline;
26 using std::endl;
27 using std::vector;
28 using std::pair;
29
30 extern BufferView * current_view;
31
32 FD_bibitem_form * bibitem_form = 0;
33
34 FD_bibitem_form * create_form_bibitem_form(void);
35
36
37 extern "C" void bibitem_cb(FL_OBJECT *, long data)
38 {
39         InsetBibKey::Holder * holder =
40                 static_cast<InsetBibKey::Holder*>
41                 (bibitem_form->bibitem_form->u_vdata);
42
43         holder->inset->callback( bibitem_form, data );
44 }
45
46 FD_bibitem_form * create_form_bibitem_form(void)
47 {
48         FL_OBJECT * obj;
49         FD_bibitem_form * fdui = (FD_bibitem_form *) fl_calloc(1, sizeof(FD_bibitem_form));
50
51         fdui->bibitem_form = fl_bgn_form(FL_NO_BOX, 220, 130);
52         obj = fl_add_box(FL_UP_BOX, 0, 0, 220, 130, "");
53         fdui->key = obj = fl_add_input(FL_NORMAL_INPUT, 80, 10, 130, 30, idex(_("Key:|#K")));
54         fl_set_input_shortcut(obj, scex(_("Key:|#K")), 1);
55         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
56         obj = fl_add_button(FL_RETURN_BUTTON, 20, 90, 90, 30, _("OK"));
57         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
58         fl_set_object_callback(obj, bibitem_cb, 1);
59         obj = fl_add_button(FL_NORMAL_BUTTON, 120, 90, 90, 30, idex(_("Cancel|^[")));
60         fl_set_button_shortcut(obj, scex(_("Cancel|^[")), 1);
61         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
62         fl_set_object_callback(obj, bibitem_cb, 0);
63         fdui->label = obj = fl_add_input(FL_NORMAL_INPUT, 80, 50, 130, 30, idex(_("Label:|#L")));
64         fl_set_input_shortcut(obj, scex(_("Label:|#L")), 1);
65         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
66         fl_end_form();
67
68         //fdui->bibitem_form->fdui = fdui;
69
70         return fdui;
71 }
72
73
74 InsetBibKey::InsetBibKey(string const & key, string const & label):
75         InsetCommand("bibitem", key, label)
76 {
77         counter = 1;
78         if (key.empty())
79                 setCmdName(" ");
80 }
81
82
83 InsetBibKey::InsetBibKey(InsetBibKey const * b):
84         InsetCommand("bibitem", b->getContents(), b->getOptions())
85 {
86         counter = b->counter;
87 }
88
89
90 InsetBibKey::~InsetBibKey()
91 {
92         if(bibitem_form && bibitem_form->bibitem_form
93            && bibitem_form->bibitem_form->visible
94            && bibitem_form->bibitem_form->u_vdata == &holder)
95                 fl_hide_form(bibitem_form->bibitem_form);
96 }
97
98
99 void InsetBibKey::callback( FD_bibitem_form * form, long data )
100 {
101         switch (data)
102         {
103         case 1:
104                 if(!holder.view->buffer()->isReadonly())
105                 {
106                         setContents(fl_get_input(form->key));
107                         setOptions(fl_get_input(form->label));
108                         // shouldn't mark the buffer dirty unless
109                         // something was actually altered
110                         holder.view->updateInset( this, true );
111                 } // fall through to Cancel
112         case 0:
113                 fl_hide_form(form->bibitem_form);
114                 break;
115         }
116 }
117
118
119 void InsetBibKey::setCounter(int c) 
120
121         counter = c; 
122     
123         if (getCmdName().empty())
124                 setCmdName( tostr(counter) );
125 }
126
127
128 // I'm sorry but this is still necessary because \bibitem is used also
129 // as a LyX 2.x command, and lyxlex is not enough smart to understand
130 // real LaTeX commands. Yes, that could be fixed, but would be a waste 
131 // of time cause LyX3 won't use lyxlex anyway.  (ale)
132 void InsetBibKey::Write(Buffer const *, ostream & os) const
133 {
134         os << "\\bibitem ";
135         if (! getOptions().empty()) {
136                 os << '['
137                    << getOptions() << ']';
138         }
139         os << '{'
140            << getContents() << "}\n";
141 }
142
143
144 string InsetBibKey::getScreenLabel() const
145 {
146         if (! getOptions().empty())
147                 return getOptions();
148     
149         return tostr(counter);
150 }
151
152
153 /*
154   The value in "Key:" isn't allways set right after a few bibkey insets have
155   been added/removed.  Perhaps the wrong object is deleted/used somewhere
156   upwards?
157   (Joacim 1998-03-04)
158 */
159 void InsetBibKey::Edit(BufferView * bv, int, int, unsigned int)
160 {
161         if(bv->buffer()->isReadonly())
162                 WarnReadonly(bv->buffer()->fileName());
163         
164         if (!bibitem_form) {
165                 bibitem_form = create_form_bibitem_form();
166                 fl_set_form_atclose(bibitem_form->bibitem_form, 
167                                     CancelCloseBoxCB, 0);
168         }
169
170         holder.inset = this;
171         holder.view = bv;
172         
173         bibitem_form->bibitem_form->u_vdata = &holder;
174         // InsetBibtex uses the same form, with different labels
175         fl_set_object_label(bibitem_form->key, idex(_("Key:|#K")));
176         fl_set_button_shortcut(bibitem_form->key, scex(_("Key:|#K")), 1);
177         fl_set_object_label(bibitem_form->label, idex(_("Label:|#L")));
178         fl_set_button_shortcut(bibitem_form->label, scex(_("Label:|#L")), 1);
179         fl_set_input(bibitem_form->key, getContents().c_str());
180         fl_set_input(bibitem_form->label, getOptions().c_str());
181         if (bibitem_form->bibitem_form->visible) {
182                 fl_raise_form(bibitem_form->bibitem_form);
183         } else {
184                 fl_show_form(bibitem_form->bibitem_form, FL_PLACE_MOUSE,
185                              FL_FULLBORDER,
186                              _("Bibliography item"));
187         }   
188 }
189
190
191 InsetBibtex::InsetBibtex(string const & dbase, string const & style,
192                          Buffer * o)
193         : InsetCommand("BibTeX", dbase, style), owner(o)
194 {
195 }
196
197 InsetBibtex::~InsetBibtex()
198 {
199         if(bibitem_form && bibitem_form->bibitem_form
200            && bibitem_form->bibitem_form->visible
201            && bibitem_form->bibitem_form->u_vdata == &holder)
202                 fl_hide_form(bibitem_form->bibitem_form);
203 }
204
205
206 string InsetBibtex::getScreenLabel() const
207 {
208         return _("BibTeX Generated References");
209 }
210
211
212 int InsetBibtex::Latex(Buffer const *, ostream & os,
213                        bool /*fragile*/, bool/*fs*/) const
214 {
215         // this looks like an horrible hack and it is :) The problem
216         // is that owner is not initialized correctly when the bib
217         // inset is cut and pasted. Such hacks will not be needed
218         // later (JMarc)
219         if (!owner) {
220                 owner = current_view->buffer();
221         }
222         // If we generate in a temp dir, we might need to give an
223         // absolute path there. This is a bit complicated since we can
224         // have a comma-separated list of bibliographies
225         string adb, db_out;
226         string db_in = getContents();
227         db_in = split(db_in, adb, ',');
228         while(!adb.empty()) {
229                 if (!owner->niceFile &&
230                     IsFileReadable(MakeAbsPath(adb, owner->filepath)+".bib")) 
231                          adb = MakeAbsPath(adb, owner->filepath);
232
233                 db_out += adb;
234                 db_out += ',';
235                 db_in= split(db_in, adb,',');
236         }
237         db_out = strip(db_out, ',');
238         // Idem, but simpler
239         string style;
240         if (!owner->niceFile 
241             && IsFileReadable(MakeAbsPath(getOptions(), owner->filepath)
242                               + ".bst")) 
243                 style = MakeAbsPath(getOptions(), owner->filepath);
244         else
245                 style = getOptions();
246
247         os << "\\bibliographystyle{" << style << "}\n"
248            << "\\bibliography{" << db_out << "}\n";
249         return 2;
250 }
251
252
253 // This method returns a comma separated list of Bibtex entries
254 vector<pair<string,string> > InsetBibtex::getKeys() const
255 {
256         // This hack is copied from InsetBibtex::Latex.
257         // Is it still needed? Probably yes.
258         // Why is this needed here when it already is in Latex?
259         // Anyway we need a different way to get to the
260         // buffer the inset is in. (Lgb)
261         
262         //if (!owner) {
263         //      owner = current_view->buffer();
264         //}
265         
266         Path p(owner->filepath);
267
268         vector<pair<string,string> > keys;
269         string tmp;
270         string bibfiles = getContents();
271         bibfiles = split(bibfiles, tmp, ',');
272         while(!tmp.empty()) {
273                 string fil = findtexfile(ChangeExtension(tmp, "bib"),
274                                          "bib");
275                 lyxerr[Debug::LATEX] << "Bibfile: " << fil << endl;
276                 // If we didn't find a matching file name just fail silently
277                 if (!fil.empty()) {
278                         // This is a _very_ simple parser for Bibtex database
279                         // files. All it does is to look for lines starting
280                         // in @ and not being @preamble and @string entries.
281                         // It does NOT do any syntax checking!
282                         ifstream ifs(fil.c_str());
283                         string linebuf0;
284                         while (getline(ifs, linebuf0)) {
285                                 string linebuf = frontStrip(strip(linebuf0));
286                                 if( linebuf.empty() ) continue;
287                                 if (prefixIs(linebuf, "@")) {
288                                         linebuf = subst(linebuf, '{', '(');
289                                         linebuf = split(linebuf, tmp, '(');
290                                         tmp = lowercase(tmp);
291                                         if (!prefixIs(tmp, "@string")
292                                             && !prefixIs(tmp, "@preamble")) {
293                                                 linebuf = split(linebuf, tmp, ',');
294                                                 tmp = frontStrip(tmp);
295                                                 if (!tmp.empty()) {
296                                                         keys.push_back(pair<string,string>(tmp,string()));
297                                                 }
298                                         }
299                                 } else if( !keys.empty() ) {
300                                         keys.back().second += linebuf + "\n";
301                                 }
302                         }
303                 }
304                 // Get next file name
305                 bibfiles = split(bibfiles, tmp, ',');
306         }
307         return keys;
308 }
309
310
311 // BibTeX should have its own dialog. This is provisional.
312 void InsetBibtex::Edit(BufferView * bv, int, int, unsigned int)
313 {
314         if (!bibitem_form) {
315                 bibitem_form = create_form_bibitem_form();
316                 fl_set_form_atclose(bibitem_form->bibitem_form, 
317                                     CancelCloseBoxCB, 0);
318         }
319
320         holder.inset = this;
321         holder.view = bv;
322         bibitem_form->bibitem_form->u_vdata = &holder;
323
324         fl_set_object_label(bibitem_form->key, _("Database:"));
325         fl_set_object_label(bibitem_form->label, _("Style:  "));
326         fl_set_input(bibitem_form->key, getContents().c_str());
327         fl_set_input(bibitem_form->label, getOptions().c_str());
328         if (bibitem_form->bibitem_form->visible) {
329                 fl_raise_form(bibitem_form->bibitem_form);
330         } else {
331                 fl_show_form(bibitem_form->bibitem_form,
332                              FL_PLACE_MOUSE, FL_FULLBORDER,
333                              _("BibTeX"));
334         }   
335 }
336
337
338 bool InsetBibtex::addDatabase(string const & db)
339 {
340         if (!contains(getContents(), db.c_str())) {
341                 if (!getContents().empty()) 
342                         addContents(",");
343                 addContents(db);
344                 return true;
345         }
346         return false;
347 }
348
349
350 bool InsetBibtex::delDatabase(string const & db)
351 {
352         if (contains(getContents(), db.c_str())) {
353                 string bd = db;
354                 int n = tokenPos(getContents(), ',', bd);
355                 if (n > 0) {
356                         // Weird code, would someone care to explain this?(Lgb)
357                         string tmp(", ");
358                         tmp += bd;
359                         setContents(subst(getContents(), tmp.c_str(), ", "));
360                 } else if (n == 0)
361                         setContents(split(getContents(), bd, ','));
362                 else 
363                         return false;
364         }
365         return true;
366 }
367
368
369 // ale070405 This function maybe shouldn't be here. We'll fix this at 0.13.
370 int bibitemMaxWidth(BufferView * bv, LyXFont const & font)
371 {
372         int w = 0;
373         // Does look like a hack? It is! (but will change at 0.13)
374         LyXParagraph * par = current_view->buffer()->paragraph;
375     
376         while (par) {
377                 if (par->bibkey) {
378                         int wx = par->bibkey->width(bv, font);
379                         if (wx > w) w = wx;
380                 }
381                 par = par->next;
382         }
383         return w;
384 }
385
386
387 // ale070405
388 string bibitemWidest(BufferView * bv)
389 {
390         int w = 0;
391         // Does look like a hack? It is! (but will change at 0.13)
392         LyXParagraph * par = current_view->buffer()->paragraph;
393         InsetBibKey * bkey = 0;
394         LyXFont font;
395       
396         while (par) {
397                 if (par->bibkey) {
398                         int wx = par->bibkey->width(bv, font);
399                         if (wx > w) {
400                                 w = wx;
401                                 bkey = par->bibkey;
402                         }
403                 }
404                 par = par->next;
405         }
406     
407         if (bkey && !bkey->getScreenLabel().empty())
408                 return bkey->getScreenLabel();
409     
410         return "99";
411 }