]> git.lyx.org Git - features.git/blob - src/insets/insetbib.C
read the Changelog
[features.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"
38 void bibitem_cb(FL_OBJECT *, long data)
39 {
40         InsetBibKey::Holder * holder =
41                 static_cast<InsetBibKey::Holder*>
42                 (bibitem_form->bibitem_form->u_vdata);
43         
44         holder->inset->callback( bibitem_form, data );
45 }
46
47
48 FD_bibitem_form * create_form_bibitem_form(void)
49 {
50         FL_OBJECT * obj;
51         FD_bibitem_form * fdui = (FD_bibitem_form *) fl_calloc(1, sizeof(FD_bibitem_form));
52
53         fdui->bibitem_form = fl_bgn_form(FL_NO_BOX, 220, 130);
54         obj = fl_add_box(FL_UP_BOX, 0, 0, 220, 130, "");
55         fdui->key = obj = fl_add_input(FL_NORMAL_INPUT, 80, 10, 130, 30, idex(_("Key:|#K")));
56         fl_set_input_shortcut(obj, scex(_("Key:|#K")), 1);
57         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
58         obj = fl_add_button(FL_RETURN_BUTTON, 20, 90, 90, 30, _("OK"));
59         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
60         fl_set_object_callback(obj, bibitem_cb, 1);
61         obj = fl_add_button(FL_NORMAL_BUTTON, 120, 90, 90, 30, idex(_("Cancel|^[")));
62         fl_set_button_shortcut(obj, scex(_("Cancel|^[")), 1);
63         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
64         fl_set_object_callback(obj, bibitem_cb, 0);
65         fdui->label = obj = fl_add_input(FL_NORMAL_INPUT, 80, 50, 130, 30, idex(_("Label:|#L")));
66         fl_set_input_shortcut(obj, scex(_("Label:|#L")), 1);
67         fl_set_object_lsize(obj, FL_NORMAL_SIZE);
68         fl_end_form();
69
70         //fdui->bibitem_form->fdui = fdui;
71
72         return fdui;
73 }
74
75
76 InsetBibKey::InsetBibKey(string const & key, string const & label)
77         : InsetCommand("bibitem", key, label)
78 {
79         counter = 1;
80         if (key.empty())
81                 setCmdName(" ");
82 }
83
84
85 InsetBibKey::InsetBibKey(InsetBibKey const * b)
86         : InsetCommand("bibitem", b->getContents(), b->getOptions())
87 {
88         counter = b->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 void InsetBibKey::callback( FD_bibitem_form * form, long data )
102 {
103         switch (data) {
104         case 1:
105                 if(!holder.view->buffer()->isReadonly()) {
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 // This is necessary here because this is written without begin_inset
145 // This should be changed!!! (Jug)
146 void InsetBibKey::Read(Buffer const *, LyXLex & lex)
147 {    
148         string token;
149
150         if (lex.EatLine()) {
151                 token = lex.GetString();
152                 scanCommand(token);
153         } else
154                 lex.printError("InsetCommand: Parse error: `$$Token'");
155 }
156
157
158 string InsetBibKey::getScreenLabel() const
159 {
160         if (! getOptions().empty())
161                 return getOptions();
162     
163         return tostr(counter);
164 }
165
166
167 /**
168   The value in "Key:" isn't allways set right after a few bibkey insets have
169   been added/removed.  Perhaps the wrong object is deleted/used somewhere
170   upwards?
171   (Joacim 1998-03-04)
172 */
173 void InsetBibKey::Edit(BufferView * bv, int, int, unsigned int)
174 {
175         if(bv->buffer()->isReadonly())
176                 WarnReadonly(bv->buffer()->fileName());
177         
178         if (!bibitem_form) {
179                 bibitem_form = create_form_bibitem_form();
180                 fl_set_form_atclose(bibitem_form->bibitem_form, 
181                                     CancelCloseBoxCB, 0);
182         }
183
184         holder.inset = this;
185         holder.view = bv;
186         
187         bibitem_form->bibitem_form->u_vdata = &holder;
188         // InsetBibtex uses the same form, with different labels
189         fl_set_object_label(bibitem_form->key, idex(_("Key:|#K")));
190         fl_set_button_shortcut(bibitem_form->key, scex(_("Key:|#K")), 1);
191         fl_set_object_label(bibitem_form->label, idex(_("Label:|#L")));
192         fl_set_button_shortcut(bibitem_form->label, scex(_("Label:|#L")), 1);
193         fl_set_input(bibitem_form->key, getContents().c_str());
194         fl_set_input(bibitem_form->label, getOptions().c_str());
195         if (bibitem_form->bibitem_form->visible) {
196                 fl_raise_form(bibitem_form->bibitem_form);
197         } else {
198                 fl_show_form(bibitem_form->bibitem_form, FL_PLACE_MOUSE,
199                              FL_FULLBORDER,
200                              _("Bibliography item"));
201         }   
202 }
203
204
205 InsetBibtex::InsetBibtex(string const & dbase, string const & style,
206                          Buffer * o)
207         : InsetCommand("BibTeX", dbase, style), owner(o)
208 {}
209
210
211 InsetBibtex::~InsetBibtex()
212 {
213         if(bibitem_form && bibitem_form->bibitem_form
214            && bibitem_form->bibitem_form->visible
215            && bibitem_form->bibitem_form->u_vdata == &holder)
216                 fl_hide_form(bibitem_form->bibitem_form);
217 }
218
219
220 string InsetBibtex::getScreenLabel() const
221 {
222         return _("BibTeX Generated References");
223 }
224
225
226 int InsetBibtex::Latex(Buffer const *, ostream & os,
227                        bool /*fragile*/, bool/*fs*/) const
228 {
229         // this looks like an horrible hack and it is :) The problem
230         // is that owner is not initialized correctly when the bib
231         // inset is cut and pasted. Such hacks will not be needed
232         // later (JMarc)
233         if (!owner) {
234                 owner = current_view->buffer();
235         }
236         // If we generate in a temp dir, we might need to give an
237         // absolute path there. This is a bit complicated since we can
238         // have a comma-separated list of bibliographies
239         string adb, db_out;
240         string db_in = getContents();
241         db_in = split(db_in, adb, ',');
242         while(!adb.empty()) {
243                 if (!owner->niceFile &&
244                     IsFileReadable(MakeAbsPath(adb, owner->filepath)+".bib")) 
245                          adb = MakeAbsPath(adb, owner->filepath);
246
247                 db_out += adb;
248                 db_out += ',';
249                 db_in= split(db_in, adb,',');
250         }
251         db_out = strip(db_out, ',');
252         // Idem, but simpler
253         string style;
254         if (!owner->niceFile 
255             && IsFileReadable(MakeAbsPath(getOptions(), owner->filepath)
256                               + ".bst")) 
257                 style = MakeAbsPath(getOptions(), owner->filepath);
258         else
259                 style = getOptions();
260
261         os << "\\bibliographystyle{" << style << "}\n"
262            << "\\bibliography{" << db_out << "}\n";
263         return 2;
264 }
265
266
267 // This method returns a comma separated list of Bibtex entries
268 vector<pair<string,string> > InsetBibtex::getKeys() const
269 {
270         // This hack is copied from InsetBibtex::Latex.
271         // Is it still needed? Probably yes.
272         // Why is this needed here when it already is in Latex?
273         // Anyway we need a different way to get to the
274         // buffer the inset is in. (Lgb)
275         
276         //if (!owner) {
277         //      owner = current_view->buffer();
278         //}
279         
280         Path p(owner->filepath);
281
282         vector<pair<string,string> > keys;
283         string tmp;
284         string bibfiles = getContents();
285         bibfiles = split(bibfiles, tmp, ',');
286         while(!tmp.empty()) {
287                 string fil = findtexfile(ChangeExtension(tmp, "bib"),
288                                          "bib");
289                 lyxerr[Debug::LATEX] << "Bibfile: " << fil << endl;
290                 // If we didn't find a matching file name just fail silently
291                 if (!fil.empty()) {
292                         // This is a _very_ simple parser for Bibtex database
293                         // files. All it does is to look for lines starting
294                         // in @ and not being @preamble and @string entries.
295                         // It does NOT do any syntax checking!
296                         ifstream ifs(fil.c_str());
297                         string linebuf0;
298                         while (getline(ifs, linebuf0)) {
299                                 string linebuf = frontStrip(strip(linebuf0));
300                                 if( linebuf.empty() ) continue;
301                                 if (prefixIs(linebuf, "@")) {
302                                         linebuf = subst(linebuf, '{', '(');
303                                         linebuf = split(linebuf, tmp, '(');
304                                         tmp = lowercase(tmp);
305                                         if (!prefixIs(tmp, "@string")
306                                             && !prefixIs(tmp, "@preamble")) {
307                                                 linebuf = split(linebuf, tmp, ',');
308                                                 tmp = frontStrip(tmp);
309                                                 if (!tmp.empty()) {
310                                                         keys.push_back(pair<string,string>(tmp,string()));
311                                                 }
312                                         }
313                                 } else if( !keys.empty() ) {
314                                         keys.back().second += linebuf + "\n";
315                                 }
316                         }
317                 }
318                 // Get next file name
319                 bibfiles = split(bibfiles, tmp, ',');
320         }
321         return keys;
322 }
323
324
325 // BibTeX should have its own dialog. This is provisional.
326 void InsetBibtex::Edit(BufferView * bv, int, int, unsigned int)
327 {
328         if (!bibitem_form) {
329                 bibitem_form = create_form_bibitem_form();
330                 fl_set_form_atclose(bibitem_form->bibitem_form, 
331                                     CancelCloseBoxCB, 0);
332         }
333
334         holder.inset = this;
335         holder.view = bv;
336         bibitem_form->bibitem_form->u_vdata = &holder;
337
338         fl_set_object_label(bibitem_form->key, _("Database:"));
339         fl_set_object_label(bibitem_form->label, _("Style:  "));
340         fl_set_input(bibitem_form->key, getContents().c_str());
341         fl_set_input(bibitem_form->label, getOptions().c_str());
342         if (bibitem_form->bibitem_form->visible) {
343                 fl_raise_form(bibitem_form->bibitem_form);
344         } else {
345                 fl_show_form(bibitem_form->bibitem_form,
346                              FL_PLACE_MOUSE, FL_FULLBORDER,
347                              _("BibTeX"));
348         }   
349 }
350
351
352 bool InsetBibtex::addDatabase(string const & db)
353 {
354         if (!contains(getContents(), db.c_str())) {
355                 if (!getContents().empty()) 
356                         addContents(",");
357                 addContents(db);
358                 return true;
359         }
360         return false;
361 }
362
363
364 bool InsetBibtex::delDatabase(string const & db)
365 {
366         if (contains(getContents(), db.c_str())) {
367                 string bd = db;
368                 int n = tokenPos(getContents(), ',', bd);
369                 if (n > 0) {
370                         // Weird code, would someone care to explain this?(Lgb)
371                         string tmp(", ");
372                         tmp += bd;
373                         setContents(subst(getContents(), tmp.c_str(), ", "));
374                 } else if (n == 0)
375                         setContents(split(getContents(), bd, ','));
376                 else 
377                         return false;
378         }
379         return true;
380 }
381
382
383 // ale070405 This function maybe shouldn't be here. We'll fix this at 0.13.
384 int bibitemMaxWidth(BufferView * bv, LyXFont const & font)
385 {
386         int w = 0;
387         // Does look like a hack? It is! (but will change at 0.13)
388         LyXParagraph * par = current_view->buffer()->paragraph;
389     
390         while (par) {
391                 if (par->bibkey) {
392                         int wx = par->bibkey->width(bv, font);
393                         if (wx > w) w = wx;
394                 }
395                 par = par->next;
396         }
397         return w;
398 }
399
400
401 // ale070405
402 string bibitemWidest(BufferView * bv)
403 {
404         int w = 0;
405         // Does look like a hack? It is! (but will change at 0.13)
406         LyXParagraph * par = current_view->buffer()->paragraph;
407         InsetBibKey * bkey = 0;
408         LyXFont font;
409       
410         while (par) {
411                 if (par->bibkey) {
412                         int wx = par->bibkey->width(bv, font);
413                         if (wx > w) {
414                                 w = wx;
415                                 bkey = par->bibkey;
416                         }
417                 }
418                 par = par->next;
419         }
420     
421         if (bkey && !bkey->getScreenLabel().empty())
422                 return bkey->getScreenLabel();
423     
424         return "99";
425 }