]> git.lyx.org Git - lyx.git/blob - src/insets/insetbib.C
4f54ecd0bf0118e073ac113b019e7acab4e8de53
[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                 // Do NOT change this to
114                 // holder.view->buffer() as this code is used by both
115                 // InsetBibKey and InsetBibtex! Ughhhhhhh!!!!
116                 if (!current_view->buffer()->isReadonly()) {
117                         setContents(fl_get_input(form->key));
118                         setOptions(fl_get_input(form->label));
119                         // shouldn't mark the buffer dirty unless
120                         // something was actually altered
121                         current_view->updateInset( this, true );
122                         // We need to do a redraw becuase the maximum 
123                         // InsetBibKey width could have changed.
124                         current_view->redraw();
125                 } // fall through to Cancel
126         case 0:
127                 fl_hide_form(form->bibitem_form);
128                 break;
129         }
130 }
131
132
133 void InsetBibKey::setCounter(int c) 
134
135         counter = c; 
136 }
137
138
139 // I'm sorry but this is still necessary because \bibitem is used also
140 // as a LyX 2.x command, and lyxlex is not enough smart to understand
141 // real LaTeX commands. Yes, that could be fixed, but would be a waste 
142 // of time cause LyX3 won't use lyxlex anyway.  (ale)
143 void InsetBibKey::Write(Buffer const *, ostream & os) const
144 {
145         os << "\\bibitem ";
146         if (! getOptions().empty()) {
147                 os << '['
148                    << getOptions() << ']';
149         }
150         os << '{'
151            << getContents() << "}\n";
152 }
153
154
155 // This is necessary here because this is written without begin_inset
156 // This should be changed!!! (Jug)
157 void InsetBibKey::Read(Buffer const *, LyXLex & lex)
158 {    
159         string token;
160
161         if (lex.EatLine()) {
162                 token = lex.GetString();
163                 scanCommand(token);
164         } else
165                 lex.printError("InsetCommand: Parse error: `$$Token'");
166
167         if (prefixIs(getContents(), key_prefix)) {
168                 int key = strToInt(getContents().substr(key_prefix.length()));
169                 key_counter = max(key_counter, key);
170         }
171 }
172
173 string const InsetBibKey::getBibLabel() const
174 {
175         if (! getOptions().empty())
176                 return getOptions();
177         return tostr(counter);
178 }
179
180 string const InsetBibKey::getScreenLabel() const
181 {
182         return getContents() + " [" + getBibLabel() + "]";
183 }
184
185
186 /**
187   The value in "Key:" isn't allways set right after a few bibkey insets have
188   been added/removed.  Perhaps the wrong object is deleted/used somewhere
189   upwards?
190   (Joacim 1998-03-04)
191 */
192 void InsetBibKey::Edit(BufferView * bv, int, int, unsigned int)
193 {
194         if (bv->buffer()->isReadonly())
195                 WarnReadonly(bv->buffer()->fileName());
196         
197         if (!bibitem_form) {
198                 bibitem_form = create_form_bibitem_form();
199                 fl_set_form_atclose(bibitem_form->bibitem_form, 
200                                     CancelCloseBoxCB, 0);
201         }
202
203         holder.inset = this;
204         holder.view = bv;
205         
206         bibitem_form->bibitem_form->u_vdata = &holder;
207         // InsetBibtex uses the same form, with different labels
208         fl_set_object_label(bibitem_form->key, idex(_("Key:|#K")));
209         fl_set_button_shortcut(bibitem_form->key, scex(_("Key:|#K")), 1);
210         fl_set_object_label(bibitem_form->label, idex(_("Label:|#L")));
211         fl_set_button_shortcut(bibitem_form->label, scex(_("Label:|#L")), 1);
212         fl_set_input(bibitem_form->key, getContents().c_str());
213         fl_set_input(bibitem_form->label, getOptions().c_str());
214         if (bibitem_form->bibitem_form->visible) {
215                 fl_raise_form(bibitem_form->bibitem_form);
216         } else {
217                 fl_show_form(bibitem_form->bibitem_form,
218                              FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
219                              _("Bibliography item"));
220         }   
221 }
222
223
224 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
225         : InsetCommand(p)
226 {}
227
228
229 InsetBibtex::~InsetBibtex()
230 {
231         if (bibitem_form && bibitem_form->bibitem_form
232            && bibitem_form->bibitem_form->visible
233            && bibitem_form->bibitem_form->u_vdata == &holder)
234                 fl_hide_form(bibitem_form->bibitem_form);
235 }
236
237
238 string const InsetBibtex::getScreenLabel() const
239 {
240         return _("BibTeX Generated References");
241 }
242
243
244 int InsetBibtex::Latex(Buffer const * buffer, ostream & os,
245                        bool /*fragile*/, bool/*fs*/) const
246 {
247         // If we generate in a temp dir, we might need to give an
248         // absolute path there. This is a bit complicated since we can
249         // have a comma-separated list of bibliographies
250         string adb, db_out;
251         string db_in = getContents();
252         db_in = split(db_in, adb, ',');
253         while(!adb.empty()) {
254                 if (!buffer->niceFile &&
255                     IsFileReadable(MakeAbsPath(adb, buffer->filepath)+".bib")) 
256                          adb = MakeAbsPath(adb, buffer->filepath);
257
258                 db_out += adb;
259                 db_out += ',';
260                 db_in= split(db_in, adb,',');
261         }
262         db_out = strip(db_out, ',');
263         // Idem, but simpler
264         string style;
265         if (!buffer->niceFile 
266             && IsFileReadable(MakeAbsPath(getOptions(), buffer->filepath)
267                               + ".bst")) 
268                 style = MakeAbsPath(getOptions(), buffer->filepath);
269         else
270                 style = getOptions();
271
272         os << "\\bibliographystyle{" << style << "}\n"
273            << "\\bibliography{" << db_out << "}\n";
274         return 2;
275 }
276
277
278 // This method returns a comma separated list of Bibtex entries
279 vector<pair<string, string> > const InsetBibtex::getKeys(Buffer const * buffer) const
280 {
281         Path p(buffer->filepath);
282
283         vector<pair<string,string> > keys;
284         string tmp;
285         string bibfiles = getContents();
286         bibfiles = split(bibfiles, tmp, ',');
287         while(!tmp.empty()) {
288                 string fil = findtexfile(ChangeExtension(tmp, "bib"),
289                                          "bib");
290                 lyxerr[Debug::LATEX] << "Bibfile: " << fil << endl;
291                 // If we didn't find a matching file name just fail silently
292                 if (!fil.empty()) {
293                         // This is a _very_ simple parser for Bibtex database
294                         // files. All it does is to look for lines starting
295                         // in @ and not being @preamble and @string entries.
296                         // It does NOT do any syntax checking!
297                         ifstream ifs(fil.c_str());
298                         string linebuf0;
299                         while (getline(ifs, linebuf0)) {
300                                 string linebuf = frontStrip(strip(linebuf0));
301                                 if (linebuf.empty() ) continue;
302                                 if (prefixIs(linebuf, "@")) {
303                                         linebuf = subst(linebuf, '{', '(');
304                                         linebuf = split(linebuf, tmp, '(');
305                                         tmp = lowercase(tmp);
306                                         if (!prefixIs(tmp, "@string")
307                                             && !prefixIs(tmp, "@preamble")) {
308                                                 linebuf = split(linebuf, tmp, ',');
309                                                 tmp = frontStrip(tmp);
310                                                 if (!tmp.empty()) {
311                                                         keys.push_back(pair<string,string>(tmp,string()));
312                                                 }
313                                         }
314                                 } else if (!keys.empty()) {
315                                         keys.back().second += linebuf + "\n";
316                                 }
317                         }
318                 }
319                 // Get next file name
320                 bibfiles = split(bibfiles, tmp, ',');
321         }
322         return keys;
323 }
324
325
326 // BibTeX should have its own dialog. This is provisional.
327 void InsetBibtex::Edit(BufferView * bv, int, int, unsigned int)
328 {
329         if (!bibitem_form) {
330                 bibitem_form = create_form_bibitem_form();
331                 fl_set_form_atclose(bibitem_form->bibitem_form, 
332                                     CancelCloseBoxCB, 0);
333         }
334
335         holder.inset = this;
336         holder.view = bv;
337         bibitem_form->bibitem_form->u_vdata = &holder;
338
339         fl_set_object_label(bibitem_form->key, _("Database:"));
340         fl_set_object_label(bibitem_form->label, _("Style:  "));
341         fl_set_input(bibitem_form->key, getContents().c_str());
342         fl_set_input(bibitem_form->label, getOptions().c_str());
343         if (bibitem_form->bibitem_form->visible) {
344                 fl_raise_form(bibitem_form->bibitem_form);
345         } else {
346                 fl_show_form(bibitem_form->bibitem_form,
347                              FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
348                              _("BibTeX"));
349         }   
350 }
351
352
353 bool InsetBibtex::addDatabase(string const & db)
354 {
355         string contents(getContents());
356         if (!contains(contents, db)) {
357                 if (!contents.empty()) 
358                         contents += ",";
359                 setContents(contents + db);
360                 return true;
361         }
362         return false;
363 }
364
365
366 bool InsetBibtex::delDatabase(string const & db)
367 {
368         if (contains(getContents(), db)) {
369                 string bd = db;
370                 int const n = tokenPos(getContents(), ',', bd);
371                 if (n > 0) {
372                         // Weird code, would someone care to explain this?(Lgb)
373                         string tmp(", ");
374                         tmp += bd;
375                         setContents(subst(getContents(), tmp, ", "));
376                 } else if (n == 0)
377                         setContents(split(getContents(), bd, ','));
378                 else 
379                         return false;
380         }
381         return true;
382 }
383
384
385 // ale070405 This function maybe shouldn't be here. We'll fix this at 0.13.
386 int bibitemMaxWidth(BufferView * bv, LyXFont const & font)
387 {
388         int w = 0;
389         // Does look like a hack? It is! (but will change at 0.13)
390         LyXParagraph * par = bv->buffer()->paragraph;
391     
392         while (par) {
393                 if (par->bibkey) {
394                         int const wx = par->bibkey->width(bv, font);
395                         if (wx > w) w = wx;
396                 }
397                 par = par->next;
398         }
399         return w;
400 }
401
402
403 // ale070405
404 string const bibitemWidest(Buffer const * buffer)
405 {
406         int w = 0;
407         // Does look like a hack? It is! (but will change at 0.13)
408         LyXParagraph * par = buffer->paragraph;
409         InsetBibKey * bkey = 0;
410         LyXFont font;
411       
412         while (par) {
413                 if (par->bibkey) {
414                         int const wx =
415                                 lyxfont::width(par->bibkey->getBibLabel(),
416                                                font);
417                         if (wx > w) {
418                                 w = wx;
419                                 bkey = par->bibkey;
420                         }
421                 }
422                 par = par->next;
423         }
424     
425         if (bkey && !bkey->getBibLabel().empty())
426                 return bkey->getBibLabel();
427     
428         return "99";
429 }