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