]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
74e2cc0ce4a39932e542c1e407eb52f1e298fd71
[lyx.git] / src / mathed / formula.C
1 /*
2  *  File:        formula.C
3  *  Purpose:     Implementation of formula inset
4  *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx> 
5  *  Created:     January 1996
6  *  Description: Allows the edition of math paragraphs inside Lyx. 
7  *
8  *  Copyright: 1996-1998 Alejandro Aguilar Sierra
9  *
10  *  Version: 0.4, Lyx project.
11  *
12  *   You are free to use and modify this code under the terms of
13  *   the GNU General Public Licence version 2 or later.
14  */
15
16 #include <config.h>
17
18 #ifdef HAVE_SSTREAM
19 #include <sstream>
20 using std::istringstream;
21 #else
22 #include <strstream>
23 #endif
24
25 #ifdef __GNUG__
26 #pragma implementation "formula.h"
27 #endif
28
29 #include "formula.h"
30 #include "commandtags.h"
31 #include "math_cursor.h"
32 #include "math_parser.h"
33 #include "lyx_main.h"
34 #include "minibuffer.h"
35 #include "BufferView.h"
36 #include "lyxtext.h"
37 #include "gettext.h"
38 #include "LaTeXFeatures.h"
39 #include "debug.h"
40 #include "lyx_gui_misc.h"
41 #include "support/LOstream.h"
42 #include "LyXView.h"
43 #include "Painter.h"
44 #include "font.h"
45
46 using std::ostream;
47 using std::istream;
48 using std::pair;
49 using std::endl;
50 using std::vector;
51
52 extern char * mathed_label;
53
54 extern char const * latex_special_chars;
55
56 short greek_kb_flag = 0;
57
58 LyXFont * Math_Fonts = 0; // this is only used by Whichfont and mathed_init_fonts (Lgb)
59
60 static LyXFont::FONT_SIZE lfont_size = LyXFont::SIZE_NORMAL;
61
62 // local global 
63 static int sel_x, sel_y;
64 static bool sel_flag;
65 MathedCursor * InsetFormula::mathcursor = 0; 
66
67
68 int MathedInset::df_asc;
69 int MathedInset::df_des;
70 int MathedInset::df_width;
71
72
73 inline
74 bool IsMacro(short token, int id)
75 {
76    return (token != LM_TK_FRAC && token != LM_TK_SQRT &&
77           !((token == LM_TK_SYM || token == LM_TC_BSYM) && id < 255));
78 }
79
80
81 static
82 void mathedValidate(LaTeXFeatures & features, MathParInset * par);
83
84
85 LyXFont WhichFont(short type, int size)
86 {
87     LyXFont f;
88     
89       if (!Math_Fonts)
90         mathed_init_fonts();
91    
92    switch (type) {
93     case LM_TC_SYMB:         
94       f = Math_Fonts[2];
95       break;
96     case LM_TC_BSYM:         
97       f = Math_Fonts[2];
98       break;
99     case LM_TC_VAR:
100     case LM_TC_IT:
101       f = Math_Fonts[0];
102       break;
103     case LM_TC_BF:
104       f = Math_Fonts[3];
105       break;
106     case LM_TC_SF:
107       f = Math_Fonts[7];
108       break;
109     case LM_TC_CAL:
110       f = Math_Fonts[4];
111       break;
112     case LM_TC_TT:
113       f = Math_Fonts[5];
114       break;
115     case LM_TC_SPECIAL: //f = Math_Fonts[0]; break;
116     case LM_TC_TEXTRM:
117     case LM_TC_RM:    
118       f = Math_Fonts[6];
119       break;
120     default:
121       f = Math_Fonts[1];
122       break;   
123    }
124     
125     f.setSize(lfont_size);
126     
127     switch (size) {
128      case LM_ST_DISPLAY:     
129         if (type == LM_TC_BSYM) {
130             f.incSize();
131             f.incSize();
132         }
133         break;
134      case LM_ST_TEXT:
135         break;
136      case LM_ST_SCRIPT:
137         f.decSize();
138         break;
139      case LM_ST_SCRIPTSCRIPT:
140         f.decSize();
141         f.decSize();
142         break;
143      default:
144              lyxerr << "Mathed Error: wrong font size: " << size << endl;
145         break;
146     }
147
148     if (type != LM_TC_TEXTRM) 
149       f.setColor(LColor::math);
150     return f;
151 }
152
153
154 void mathed_init_fonts() //removed 'static' because DEC cxx does not
155                          //like it (JMarc)
156         // Probably because this func is declared as a friend in math_defs.h
157         // Lgb
158 {
159
160     Math_Fonts = new LyXFont[8]; //DEC cxx cannot initialize all fonts
161                                  //at once (JMarc) rc
162     for (int i = 0 ; i < 8 ; ++i) { 
163         Math_Fonts[i] = LyXFont(LyXFont::ALL_SANE);
164     }
165     Math_Fonts[0].setShape(LyXFont::ITALIC_SHAPE);
166     
167     Math_Fonts[1].setFamily(LyXFont::SYMBOL_FAMILY);
168     
169     Math_Fonts[2].setFamily(LyXFont::SYMBOL_FAMILY);
170     Math_Fonts[2].setShape(LyXFont::ITALIC_SHAPE);
171
172     Math_Fonts[3].setSeries(LyXFont::BOLD_SERIES);
173       
174     Math_Fonts[4].setFamily(LyXFont::SANS_FAMILY);
175     Math_Fonts[4].setShape(LyXFont::ITALIC_SHAPE);
176       
177     Math_Fonts[5].setFamily(LyXFont::TYPEWRITER_FAMILY);
178
179     Math_Fonts[6].setFamily(LyXFont::ROMAN_FAMILY);
180
181     Math_Fonts[7].setFamily(LyXFont::SANS_FAMILY);
182     
183     LyXFont f = WhichFont(LM_TC_VAR, LM_ST_TEXT);
184     MathedInset::df_asc = lyxfont::maxAscent(f); 
185     MathedInset::df_des = lyxfont::maxDescent(f);
186     MathedInset::df_width = lyxfont::width('I', f);    
187 }
188
189
190 LyXFont mathed_get_font(short type, int size)
191 {
192         LyXFont f = WhichFont(type, size);
193         if (type == LM_TC_TEX) {
194                 f.setLatex(LyXFont::ON);
195         }
196         return f;
197 }
198
199
200 int mathed_string_width(short type, int size, byte const * s, int ls)
201 {
202     LyXFont f = WhichFont(type, size);
203
204     byte sx[80];
205     if (MathIsBinary(type)) {
206         byte * ps = &sx[0];
207         for (int i = 0; i < ls && i < 75; ++i) {
208             *(ps++) = ' ';
209             *(ps++) = s[i];
210             *(ps++) = ' ';
211         }
212         *(ps++) = '\0';
213         ls *= 3;
214         s = &sx[0];
215     }
216     return lyxfont::width(reinterpret_cast<char const *>(s), ls, f);
217 }
218
219
220 int mathed_char_width(short type, int size, byte c)
221 {
222     int t = (MathIsBinary(type)) ? mathed_string_width(type, size, &c, 1) :
223            lyxfont::width(c, WhichFont(type, size));
224     return t;
225 }
226
227
228 int mathed_string_height(short type, int size, byte const * s,
229                          int ls, int & asc, int & des)
230 {
231    LyXFont font = WhichFont(type, size);
232    asc = des = 0;
233    for (int i = 0; i < ls; ++i) {
234       if (lyxfont::descent(s[i], font) > des)
235         des = lyxfont::descent(s[i], font);
236       if (lyxfont::ascent(s[i], font) > asc)
237         asc = lyxfont::ascent(s[i], font);
238    }
239    return asc + des;
240 }
241
242
243 int mathed_char_height(short type, int size, byte c, int & asc, int & des)
244 {
245    LyXFont font = WhichFont(type, size);
246    asc = des = 0;
247    des = lyxfont::descent(c, font);
248    asc = lyxfont::ascent(c, font);
249    return asc + des;
250 }
251
252
253 // In a near future maybe we use a better fonts renderer
254 void MathedInset::drawStr(Painter & pain, short type, int siz,
255                           int x, int y, byte const * s, int ls)
256 {
257         string st;
258         if (MathIsBinary(type)) {
259                 for (int i = 0; i < ls; ++i) {
260                         st += string(" ") + char(s[i]) + ' ';
261                 }
262         } else {
263                 st = string(reinterpret_cast<char const *>(s), ls);
264         }
265         LyXFont mf = mathed_get_font(type, siz);
266         pain.text(x, y, st, mf);
267 }
268
269
270 InsetFormula::InsetFormula(bool display)
271 {
272   par = new MathParInset; // this leaks
273   //   mathcursor = 0;
274   disp_flag = display;
275   //label = 0;
276   if (disp_flag) {
277     par->SetType(LM_OT_PAR);
278     par->SetStyle(LM_ST_DISPLAY);
279   }
280 }
281
282
283 InsetFormula::InsetFormula(MathParInset * p)
284 {
285    par = (p->GetType()>= LM_OT_MPAR) ? 
286          new MathMatrixInset(static_cast<MathMatrixInset*>(p)): 
287          new MathParInset(p);
288 //   mathcursor = 0;
289    
290    disp_flag = (par->GetType()>0);
291    //label = 0;
292 }
293
294
295 InsetFormula::~InsetFormula()
296 {
297    delete par;
298 }
299
300
301 Inset * InsetFormula::Clone() const
302 {
303     InsetFormula * f = new InsetFormula(par);
304     f->label = label;
305     return f;
306 }
307
308
309 void InsetFormula::Write(Buffer const * buf, ostream & os) const
310 {
311         os << "Formula ";
312         Latex(buf, os, false, false);
313 }
314
315
316 int InsetFormula::Latex(Buffer const *, ostream & os, bool fragile, bool) const
317 {
318     int ret = 0;      
319 //#warning Alejandro, the number of lines is not returned in this case
320 // This problem will disapear at 0.13.
321     mathed_write(par, os, &ret, fragile, label.c_str());
322     return ret;
323 }
324
325
326 int InsetFormula::Ascii(Buffer const *, ostream & os) const
327 {
328     par->Write(os, false);
329     return 0;
330 }
331
332
333 int InsetFormula::Linuxdoc(Buffer const * buf, ostream & os) const
334 {
335     return Ascii(buf, os);
336 }
337
338
339 int InsetFormula::DocBook(Buffer const * buf, ostream & os) const
340 {
341     return Ascii(buf, os);
342 }
343
344
345 // Check if uses AMS macros 
346 void InsetFormula::Validate(LaTeXFeatures & features) const
347 {
348     // Validation only necesary if not using an AMS Style
349     if (!features.amsstyle)
350       mathedValidate(features, par);
351 }
352
353
354 void InsetFormula::Read(Buffer const *, LyXLex & lex)
355 {
356         istream & is = lex.getStream();
357     
358         mathed_parser_file(is, lex.GetLineNo());   
359    
360         // Silly hack to read labels. 
361         mathed_label = 0;
362         mathed_parse(0, 0, &par);
363         par->Metrics();
364         disp_flag = (par->GetType() > 0);
365         
366         // Update line number
367         lex.setLineNo(mathed_parser_lineno());
368         
369         if (mathed_label) {
370                 label = mathed_label;
371                 mathed_label = 0;
372         }
373         // reading of end_inset in the inset!!!
374         while (lex.IsOK()) {
375                 lex.nextToken();
376                 if (lex.GetString() == "\\end_inset")
377                         break;
378         }
379    
380 #ifdef DEBUG
381         Write(lyxerr);
382 #endif
383 }
384
385
386 int InsetFormula::ascent(Painter &, LyXFont const &) const
387 {
388    return par->Ascent() + ((disp_flag) ? 8 : 1);
389 }
390
391
392 int InsetFormula::descent(Painter &, LyXFont const &) const
393 {
394    return par->Descent() + ((disp_flag) ? 8 : 1);
395 }
396
397
398 int InsetFormula::width(Painter &, LyXFont const & f) const
399 {
400     lfont_size = f.size();
401     par->Metrics();
402     return par->Width(); //+2;
403 }
404
405
406 void InsetFormula::draw(Painter & pain, LyXFont const & f,
407                         int baseline, float & x) const
408 {
409         // Seems commenting out solves a problem.
410         LyXFont font = mathed_get_font(LM_TC_TEXTRM, LM_ST_TEXT);
411         font.setSize(f.size());
412         lfont_size = font.size();
413         /// Let's try to wait a bit with this... (Lgb)
414         //UpdatableInset::draw(pain, font, baseline, x);
415         
416         // otherwise a segfault could occur
417         // in some XDrawRectangles (i.e. matrix) (Matthias)
418         if (mathcursor && mathcursor->GetPar() == par) { 
419                 if (mathcursor->Selection()) {
420                         int n;
421                         int * xp = 0;
422                         int * yp = 0;
423                         mathcursor->SelGetArea(&xp, &yp, n);
424                         pain.fillPolygon(xp, yp, n, LColor::selection);
425                 }
426                 mathcursor->draw(pain, int(x), baseline);
427         } else {
428                 par->draw(pain, int(x), baseline);
429         }
430         x += float(width(pain, font));
431         
432         if (par->GetType() == LM_OT_PARN || par->GetType() == LM_OT_MPARN) {
433                 LyXFont wfont = WhichFont(LM_TC_BF, par->size);
434                 wfont.setLatex(LyXFont::OFF);
435                 
436                 if (par->GetType() == LM_OT_PARN) {
437                         string str;
438                         if (!label.empty())
439                                 str = string("(") + label + ")";
440                         else
441                                 str = string("(#)");
442                         pain.text(int(x + 20), baseline, str, wfont);
443                 } else if (par->GetType() == LM_OT_MPARN) {
444                         MathMatrixInset * mt =
445                                 static_cast<MathMatrixInset*>(par);
446                         int y;
447                         MathedRowSt const * crow = mt->getRowSt();
448                         while (crow) {
449                                 y = baseline + crow->getBaseline();
450                                 if (crow->isNumbered()) {
451                                         string str;
452                                         if (crow->getLabel())
453                                                 str = string("(") + crow->getLabel() + ")";
454                                         else
455                                                 str = "(#)";
456                                         pain.text(int(x + 20), y, str, wfont);
457                                 }
458                                 crow = crow->getNext();
459                         }
460                 }
461         }
462         cursor_visible = false;
463 }
464
465
466 char const * InsetFormula::EditMessage() const 
467 {
468         return _("Math editor mode");
469 }
470
471
472 void InsetFormula::Edit(BufferView * bv, int x, int y, unsigned int)
473 {
474     mathcursor = new MathedCursor(par);
475     if (!bv->lockInset(this))
476         lyxerr[Debug::MATHED] << "Cannot lock inset!!!" << endl;
477     par->Metrics();
478     bv->updateInset(this, false);
479     x += par->xo; 
480     y += par->yo; 
481     mathcursor->SetPos(x, y);
482     sel_x = sel_y = 0;
483     sel_flag = false;
484 }
485
486
487 void InsetFormula::InsetUnlock(BufferView * bv)
488 {
489    if (mathcursor) {
490        if (mathcursor->InMacroMode()) {
491            mathcursor->MacroModeClose();
492            UpdateLocal(bv);
493        }                                         
494      delete mathcursor;
495    }
496    mathcursor = 0;
497    bv->updateInset(this, false);
498 }
499
500
501 // Now a symbol can be inserted only if the inset is locked
502 void InsetFormula::InsertSymbol(BufferView * bv, char const * s)
503
504    if (!s || !mathcursor) return;   
505    mathcursor->Interpret(s);
506    UpdateLocal(bv);
507 }
508
509    
510 void InsetFormula::GetCursorPos(int& x, int& y) const
511 {
512     mathcursor->GetPos(x, y);
513     x -= par->xo; 
514     y -= par->yo;
515 }
516
517 void InsetFormula::ToggleInsetCursor(BufferView * bv)
518 {
519   if (!mathcursor)
520     return;
521
522   int x, y;
523   mathcursor->GetPos(x, y);
524 //  x -= par->xo; 
525   y -= par->yo; 
526     LyXFont font = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
527   int asc = lyxfont::maxAscent(font);
528   int desc = lyxfont::maxDescent(font);
529   
530   if (cursor_visible)
531     bv->hideLockedInsetCursor();
532   else
533     bv->showLockedInsetCursor(x, y, asc, desc);
534   cursor_visible = !cursor_visible;
535 }
536
537
538 void InsetFormula::ShowInsetCursor(BufferView * bv)
539 {
540   if (!cursor_visible) {
541     if (mathcursor) {
542       int x, y;
543       mathcursor->GetPos(x, y);
544       //  x -= par->xo; 
545       y -= par->yo;
546         LyXFont font = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
547         int asc = lyxfont::maxAscent(font);
548         int desc = lyxfont::maxDescent(font);
549       bv->fitLockedInsetCursor(x, y, asc, desc);
550     }
551     ToggleInsetCursor(bv);
552   }
553 }
554
555
556 void InsetFormula::HideInsetCursor(BufferView * bv)
557 {
558   if (cursor_visible)
559     ToggleInsetCursor(bv);
560 }
561
562
563 void InsetFormula::ToggleInsetSelection(BufferView * bv)
564 {
565     if (!mathcursor)
566       return;
567     
568 //    int x, y, w, h;
569     //int n;
570     //XPoint * p = 
571     //mathcursor->SelGetArea(n);
572 //    XFillPolygon(fl_display, pm, LyXGetSelectionGC(), p, n, Nonconvex, CoordModeOrigin);
573 //    x -= par->xo; 
574 //    y -= par->yo;
575
576     bv->updateInset(this, false);
577       
578 }
579
580
581 void InsetFormula::display(bool dspf)
582 {
583    if (dspf != disp_flag) {
584       if (dspf) {
585          par->SetType(LM_OT_PAR);
586          par->SetStyle(LM_ST_DISPLAY);
587       } else {
588          if (par->GetType() >= LM_OT_MPAR) { 
589             MathParInset * p = new MathParInset(par);
590             delete par;
591             par = p;
592             if (mathcursor) 
593                mathcursor->SetPar(par); 
594          }
595          par->SetType(LM_OT_MIN);
596          par->SetStyle(LM_ST_TEXT);
597          if (!label.empty() && par->GetType() != LM_OT_MPARN) {
598                  label.erase();
599          }
600       }
601       disp_flag = dspf;
602    }
603 }
604
605
606 vector<string> InsetFormula::getLabelList() const
607 {
608 //#warning This is dirty, I know. Ill clean it at 0.11
609 // Correction, the only way to clean this is with a new kernel: 0.13.
610
611         vector<string> label_list;
612
613         if (par->GetType() == LM_OT_MPARN) {
614                 MathMatrixInset * mt = static_cast<MathMatrixInset*>(par);
615                 MathedRowSt const * crow = mt->getRowSt();
616                 while (crow) {
617                         if (crow->getLabel())
618                                 label_list.push_back(crow->getLabel());
619                         crow = crow->getNext();
620                 }
621         } else if (!label.empty())
622                 label_list.push_back(label);
623
624         return label_list;
625 }
626
627
628 void InsetFormula::UpdateLocal(BufferView * bv)
629 {
630    par->Metrics();  // To inform lyx kernel the exact size 
631                   // (there were problems with arrays).
632    bv->updateInset(this, true);
633 }
634
635
636 void InsetFormula::InsetButtonRelease(BufferView * bv,
637                                       int x, int y, int /*button*/)
638 {
639     if (mathcursor) {
640         HideInsetCursor(bv);
641         x += par->xo;
642         y += par->yo;
643         mathcursor->SetPos(x, y);
644         ShowInsetCursor(bv);
645         if (sel_flag) {
646             sel_flag = false; 
647             sel_x = sel_y = 0;
648             bv->updateInset(this, false); 
649         }
650     }
651 }
652
653
654 void InsetFormula::InsetButtonPress(BufferView * bv,
655                                     int x, int y, int /*button*/)
656 {
657     sel_flag = false;
658     sel_x = x;  sel_y = y;
659     if (mathcursor && mathcursor->Selection()) {
660         mathcursor->SelClear();
661         bv->updateInset(this, false); 
662     }
663 }
664
665
666 void InsetFormula::InsetMotionNotify(BufferView * bv,
667                                      int x, int y, int /*button*/)
668 {
669     if (sel_x && sel_y && abs(x-sel_x) > 4 && !sel_flag) {
670         sel_flag = true;
671         HideInsetCursor(bv);
672         mathcursor->SetPos(sel_x + par->xo, sel_y + par->yo);
673         mathcursor->SelStart();
674         ShowInsetCursor(bv); 
675         mathcursor->GetPos(sel_x, sel_y);
676     } else
677       if (sel_flag) {
678           HideInsetCursor(bv);
679           x += par->xo;
680           y += par->yo;
681           mathcursor->SetPos(x, y);
682           ShowInsetCursor(bv);
683           mathcursor->GetPos(x, y);
684           if (sel_x!= x || sel_y!= y)
685             bv->updateInset(this, false); 
686           sel_x = x;  sel_y = y;
687       }
688 }
689
690
691 void InsetFormula::InsetKeyPress(XKeyEvent *)
692 {
693         lyxerr[Debug::MATHED] << "Used InsetFormula::InsetKeyPress." << endl;
694 }
695
696
697 // Special Mathed functions
698 bool InsetFormula::SetNumber(bool numbf)
699 {
700    if (disp_flag) {
701       short type = par->GetType();
702       bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
703       if (numbf && !oldf) ++type;
704       if (!numbf && oldf) --type;
705       par->SetType(type);
706       return oldf;
707    } else
708      return false;
709 }
710
711
712 UpdatableInset::RESULT
713 InsetFormula::LocalDispatch(BufferView * bv,
714                             int action, string const & arg)
715 {
716 //   extern char *dispatch_result;
717     MathedTextCodes varcode = LM_TC_MIN;       
718     bool was_macro = mathcursor->InMacroMode();
719     bool sel = false;
720     bool space_on = false;
721     bool was_selection = mathcursor->Selection();
722     RESULT result = DISPATCHED;
723     static MathSpaceInset * sp= 0;
724
725    HideInsetCursor(bv);
726
727     if (mathcursor->getLastCode() == LM_TC_TEX) { 
728         varcode = LM_TC_TEX;
729     }
730    switch (action) {
731        
732     // --- Cursor Movements ---------------------------------------------
733     case LFUN_RIGHTSEL: sel = true;
734     case LFUN_RIGHT:
735       {
736          result = DISPATCH_RESULT(mathcursor->Right(sel));
737          break;
738       }
739     case LFUN_LEFTSEL: sel = true;     
740     case LFUN_LEFT:
741       {
742          result = DISPATCH_RESULT(mathcursor->Left(sel));
743          break;
744       }
745     case LFUN_UPSEL: sel = true;  
746     case LFUN_UP:
747       result = DISPATCH_RESULT(mathcursor->Up(sel));
748       break;
749        
750     case LFUN_DOWNSEL: sel = true;  
751     case LFUN_DOWN:
752       result = DISPATCH_RESULT(mathcursor->Down(sel));
753       break;
754     case LFUN_HOME:
755       mathcursor->Home();
756       break;
757     case LFUN_END:
758       mathcursor->End();
759       break;
760     case LFUN_DELETE_LINE_FORWARD:
761             //current_view->lockedInsetStoreUndo(Undo::INSERT);
762             bv->lockedInsetStoreUndo(Undo::DELETE);
763       mathcursor->DelLine();
764       UpdateLocal(bv);
765       break;
766     case LFUN_BREAKLINE:
767       bv->lockedInsetStoreUndo(Undo::INSERT);
768       mathcursor->Insert(' ', LM_TC_CR);
769       par = mathcursor->GetPar();
770       UpdateLocal(bv);
771       break;
772     case LFUN_TAB:
773       bv->lockedInsetStoreUndo(Undo::INSERT);
774       mathcursor->Insert(0, LM_TC_TAB);
775       //UpdateInset(this);
776       break;     
777     case LFUN_TABINSERT:
778       bv->lockedInsetStoreUndo(Undo::INSERT);
779       mathcursor->Insert('T', LM_TC_TAB);
780       UpdateLocal(bv);
781       break;     
782     case LFUN_BACKSPACE:
783        if (!mathcursor->Left()) 
784          break;
785        
786        if (!mathcursor->InMacroMode() && mathcursor->pullArg()) {       
787            bv->updateInset(this, true);
788            break;
789        }
790       
791     case LFUN_DELETE:
792             //current_view->lockedInsetStoreUndo(Undo::INSERT);
793             bv->lockedInsetStoreUndo(Undo::DELETE);
794       mathcursor->Delete();       
795       bv->updateInset(this, true);
796       break;    
797 //    case LFUN_GETXY:
798 //      sprintf(dispatch_buffer, "%d %d",);
799 //      dispatch_result = dispatch_buffer;
800 //      break;
801     case LFUN_SETXY:
802       {
803          int x, y, x1, y1;
804 #ifdef HAVE_SSTREAM
805          istringstream ist(arg.c_str());
806 #else
807          istrstream ist(arg.c_str());
808 #endif
809          ist >> x >> y;
810          par->GetXY(x1, y1);
811          mathcursor->SetPos(x1 + x, y1 + y);
812       }
813       break;
814
815       /* cursor selection ---------------------------- */
816
817     case LFUN_PASTE:
818             if (was_macro)
819                 mathcursor->MacroModeClose();
820             bv->lockedInsetStoreUndo(Undo::INSERT);
821             mathcursor->SelPaste(); UpdateLocal(bv); break;
822     case LFUN_CUT:
823             bv->lockedInsetStoreUndo(Undo::DELETE);
824             mathcursor->SelCut(); UpdateLocal(bv); break;
825     case LFUN_COPY: mathcursor->SelCopy(); break;      
826     case LFUN_HOMESEL:
827     case LFUN_ENDSEL:
828     case LFUN_WORDRIGHTSEL:
829     case LFUN_WORDLEFTSEL:
830       break;
831       
832     // --- accented characters ------------------------------
833
834     case LFUN_UMLAUT: mathcursor->setAccent(LM_ddot); break;
835     case LFUN_CIRCUMFLEX: mathcursor->setAccent(LM_hat); break;
836     case LFUN_GRAVE: mathcursor->setAccent(LM_grave); break;
837     case LFUN_ACUTE: mathcursor->setAccent(LM_acute); break;
838     case LFUN_TILDE: mathcursor->setAccent(LM_tilde); break;
839     case LFUN_MACRON: mathcursor->setAccent(LM_bar); break;
840     case LFUN_DOT: mathcursor->setAccent(LM_dot); break;
841     case LFUN_CARON: mathcursor->setAccent(LM_check); break;
842     case LFUN_BREVE: mathcursor->setAccent(LM_breve); break;
843     case LFUN_VECTOR: mathcursor->setAccent(LM_vec); break; 
844       
845     // Greek mode     
846     case LFUN_GREEK:
847     {
848        if (!greek_kb_flag) {
849           greek_kb_flag = 1;
850           bv->owner()->getMiniBuffer()->Set(_("Math greek mode on"));
851        } else
852          greek_kb_flag = 0;
853        break;
854     }  
855       
856     // Greek keyboard      
857     case LFUN_GREEK_TOGGLE:
858     {
859        greek_kb_flag = (greek_kb_flag) ? 0 : 2;
860        if (greek_kb_flag)
861          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard on"));
862        else
863          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard off"));
864        break;
865     }  
866    
867       //  Math fonts 
868     case LFUN_BOLD:     mathcursor->setLastCode(LM_TC_BF); break;
869     case LFUN_SANS:  mathcursor->setLastCode( LM_TC_SF); break;
870     case LFUN_EMPH:  mathcursor->setLastCode(LM_TC_CAL); break;
871     case LFUN_ROMAN: mathcursor->setLastCode(LM_TC_RM); break;
872     case LFUN_CODE: mathcursor->setLastCode(LM_TC_TT); break;   
873     case LFUN_DEFAULT:  mathcursor->setLastCode(LM_TC_VAR ) ; break;
874     case LFUN_TEX: 
875     {
876 //       varcode = LM_TC_TEX;
877         mathcursor->setLastCode(LM_TC_TEX);
878         bv->owner()->getMiniBuffer()->Set(_("TeX mode")); 
879        break;
880     }
881
882     case LFUN_MATH_NUMBER:
883     {
884       bv->lockedInsetStoreUndo(Undo::INSERT);
885        if (disp_flag) {
886           short type = par->GetType();
887           bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
888           if (oldf) {
889              --type;
890              if (!label.empty()) {
891                      label.erase();
892              }
893              bv->owner()->getMiniBuffer()->Set(_("No number"));  
894           } else {
895              ++type;
896              bv->owner()->getMiniBuffer()->Set(_("Number"));
897           }
898           par->SetType(type);
899           UpdateLocal(bv);
900        }
901        break;
902     }
903     
904     case LFUN_MATH_NONUMBER:
905     { 
906         if (par->GetType() == LM_OT_MPARN) {
907 //         MathMatrixInset *mt = (MathMatrixInset*)par;
908            //BUG 
909 //         mt->SetNumbered(!mt->IsNumbered());
910             
911             mathcursor->setNumbered();
912            UpdateLocal(bv);
913         }
914         break;
915     }
916        
917     case LFUN_MATH_LIMITS:
918     {
919       bv->lockedInsetStoreUndo(Undo::INSERT);
920        if (mathcursor->Limits())
921          UpdateLocal(bv);
922     }
923  
924     case LFUN_MATH_SIZE:
925        if (!arg.empty()) {
926            latexkeys * l = in_word_set (arg.c_str(), strlen(arg.c_str()));
927            int sz = (l) ? l->id: -1;
928            mathcursor->SetSize(sz);
929            UpdateLocal(bv);
930            break;
931        }
932        
933     case LFUN_INSERT_MATH:
934     {
935         bv->lockedInsetStoreUndo(Undo::INSERT);
936         InsertSymbol(bv, arg.c_str());
937         break;
938     }
939     
940     case LFUN_INSERT_MATRIX:
941     { 
942       bv->lockedInsetStoreUndo(Undo::INSERT);
943        int k, m, n;
944        char s[80], arg2[80];
945        // This is just so that too long args won't ooze out of s.
946        strncpy(arg2, arg.c_str(), 80); arg2[79]= '\0';
947        k = sscanf(arg2, "%d %d %s", &m, &n, s);
948        s[79] = '\0';
949         
950        if (k < 1) {
951            m = n = 1;
952        } else if (k == 1) {
953            n = 1;
954        }
955         
956        MathMatrixInset * p = new MathMatrixInset(m, n);      
957        if (mathcursor && p) {
958           if (k > 2 && int(strlen(s)) > m)
959             p->SetAlign(s[0], &s[1]);
960           mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
961           UpdateLocal(bv);
962        }
963        break;
964     }
965       
966     case LFUN_MATH_DELIM:
967     {  
968       bv->lockedInsetStoreUndo(Undo::INSERT);
969        char lf[40], rg[40], arg2[40];
970        int ilf = '(', irg = '.';
971        latexkeys * l;
972        string vdelim("(){}[]./|");
973         
974        if (arg.empty())
975                break;
976        strncpy(arg2, arg.c_str(), 40); arg2[39]= '\0';
977        int n = sscanf(arg2, "%s %s", lf, rg);
978        lf[39] = '\0'; rg[39] = '\0';
979
980        if (n > 0) {
981            if (isdigit(lf[0])) 
982              ilf = atoi(lf);
983            else 
984              if (lf[1]) {
985                  l = in_word_set(lf, strlen(lf));
986                  // Long words will cause l == 0; so check.
987                  if(l) ilf = l->id;
988              } else
989              if (vdelim.find(lf[0]) != string::npos)
990                ilf = lf[0];
991            
992            if (n > 1) {
993                if (isdigit(rg[0]))
994                  irg = atoi(rg);
995                else 
996                  if (rg[1]) {
997                      l = in_word_set(rg, strlen(rg));
998                      if(l) irg = l->id;
999                  } else
1000                  if (vdelim.find(rg[0]) != string::npos)
1001                    irg = rg[0];
1002            }
1003        }
1004        
1005        MathDelimInset * p = new MathDelimInset(ilf, irg);
1006        mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
1007        UpdateLocal(bv);
1008        break;
1009     }
1010
1011     case LFUN_PROTECTEDSPACE:
1012     {
1013       bv->lockedInsetStoreUndo(Undo::INSERT);
1014        sp = new MathSpaceInset(1); 
1015        mathcursor->Insert(sp);
1016        space_on = true;
1017        UpdateLocal(bv);
1018        break;
1019     }
1020       
1021     case LFUN_INSERT_LABEL:
1022     {
1023        bv->lockedInsetStoreUndo(Undo::INSERT);
1024        if (par->GetType() < LM_OT_PAR) break;
1025        string lb = arg;
1026        if (lb.empty()) {
1027           pair<bool, string>
1028                 res = askForText(_("Enter new label to insert:"));
1029           if (res.first) {
1030              lb = res.second;
1031           }
1032        }
1033        if (!lb.empty() && lb[0] > ' ') {
1034           SetNumber(true);
1035           if (par->GetType() == LM_OT_MPARN) {
1036               mathcursor->setLabel(lb.c_str());
1037 //            MathMatrixInset *mt = (MathMatrixInset*)par;
1038 //            mt->SetLabel(lb);
1039           } else {
1040                   //if (label.notEmpty()) delete label;
1041               label = lb;
1042           }
1043           UpdateLocal(bv);
1044        } else
1045                label.erase();
1046        break;
1047     }
1048     
1049     case LFUN_MATH_DISPLAY:
1050             //current_view->lockedInsetStoreUndo(Undo::INSERT);
1051             bv->lockedInsetStoreUndo(Undo::EDIT);
1052       display(!disp_flag);
1053       UpdateLocal(bv);
1054       break;
1055       
1056     // Invalid actions under math mode
1057     case LFUN_MATH_MODE:  
1058     {
1059         if (mathcursor->getLastCode()!= LM_TC_TEXTRM) {
1060             bv->owner()->getMiniBuffer()->Set(_("math text mode"));
1061             varcode = LM_TC_TEXTRM;
1062         } else {
1063             varcode = LM_TC_VAR;
1064         }
1065         mathcursor->setLastCode(varcode);
1066         break; 
1067     }
1068     case LFUN_UNDO:
1069       bv->owner()->getMiniBuffer()->Set(_("Invalid action in math mode!"));
1070       break;
1071
1072     //------- dummy actions
1073     case LFUN_EXEC_COMMAND:
1074        bv->owner()->getMiniBuffer()->ExecCommand(); 
1075        break;
1076        
1077     default:
1078       if ((action == -1  || action == LFUN_SELFINSERT) && !arg.empty())  {
1079          unsigned char c = arg[0];
1080          bv->lockedInsetStoreUndo(Undo::INSERT);
1081          
1082          if (c == ' ' && mathcursor->getAccent() == LM_hat) {
1083              c = '^';
1084              mathcursor->setAccent(0);
1085          }
1086          if (c == 0) {      // Dead key, do nothing 
1087              //lyxerr << "deadkey" << endl;
1088              break;
1089          } 
1090          if (isalpha(c)) {
1091              if (mathcursor->getLastCode() == LM_TC_TEX) { 
1092                mathcursor->MacroModeOpen();
1093                mathcursor->clearLastCode();
1094                varcode = LM_TC_MIN;
1095             } else          
1096             if (!varcode) {             
1097                 short f = (mathcursor->getLastCode()) ? 
1098                           mathcursor->getLastCode() :
1099                           static_cast<MathedTextCodes>(mathcursor->GetFCode());
1100                 varcode = MathIsAlphaFont(f) ?
1101                         static_cast<MathedTextCodes>(f) :
1102                         LM_TC_VAR;
1103             }
1104
1105 //           lyxerr << "Varcode << vardoce;
1106             mathcursor->Insert(c, (greek_kb_flag) ? LM_TC_SYMB: varcode);
1107             varcode = LM_TC_MIN;
1108             if (greek_kb_flag<2) greek_kb_flag = 0;
1109          } else 
1110            if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
1111                mathcursor->Insert(c, LM_TC_TEX);
1112                if (c == '{') {
1113                    mathcursor->Insert('}', LM_TC_TEX);
1114                    mathcursor->Left();
1115                }
1116                mathcursor->clearLastCode();
1117 //             varcode = LM_TC_MIN;
1118            } else
1119            if (c == '_' && varcode == LM_TC_TEX) {
1120                mathcursor->Insert(c, LM_TC_SPECIAL);
1121                mathcursor->clearLastCode();
1122 //             varcode = LM_TC_MIN;
1123            } else
1124             if (('0'<= c && c<= '9') && (varcode == LM_TC_TEX||was_macro)) {
1125                 mathcursor->MacroModeOpen();
1126                 mathcursor->clearLastCode();
1127                 mathcursor->Insert(c, LM_TC_MIN);
1128             }
1129          else
1130            if (('0'<= c && c<= '9') || strchr(";:!|[]().,?", c)) 
1131               mathcursor->Insert(c, LM_TC_CONST);
1132          else
1133            if (strchr("+/-*<>=", c))
1134               mathcursor->Insert(c, LM_TC_BOP);
1135          else
1136            if (strchr(latex_special_chars, c) && c!= '_')
1137               mathcursor->Insert(c, LM_TC_SPECIAL);
1138          else
1139            if (c == '_' || c == '^') {
1140                char s[2];
1141                s[0] = c;
1142                s[1] = 0;
1143               mathcursor->Interpret (s);
1144            } else
1145            if (c == ' ') {          
1146                if (!varcode) {  
1147                    short f = (mathcursor->getLastCode()) ? 
1148                               mathcursor->getLastCode() :
1149                               static_cast<MathedTextCodes>(mathcursor->GetFCode());
1150                    varcode = MathIsAlphaFont(f) ?
1151                            static_cast<MathedTextCodes>(f) :
1152                            LM_TC_VAR;
1153                }
1154               if (varcode == LM_TC_TEXTRM) {
1155                   mathcursor->Insert(c, LM_TC_TEXTRM);
1156               } else
1157               if (was_macro)
1158                 mathcursor->MacroModeClose();
1159               else 
1160               if (sp) {
1161                  int isp = (sp->GetSpace()<5) ? sp->GetSpace()+1: 0;
1162                  sp->SetSpace(isp);
1163                  space_on = true;
1164               } else {
1165                   if (!mathcursor->Pop() && mathcursor->IsEnd()) 
1166                     result = FINISHED;
1167               }
1168            } else
1169            if (c == '\'') {
1170               mathcursor->Insert (c, LM_TC_VAR);
1171            } else
1172            if (c == '\\') {
1173               if (was_macro)
1174                 mathcursor->MacroModeClose();
1175               bv->owner()->getMiniBuffer()->Set(_("TeX mode")); 
1176                mathcursor->setLastCode(LM_TC_TEX);
1177            } 
1178          UpdateLocal(bv);
1179       } else {
1180         // lyxerr << "Closed by action " << action << endl;
1181         result =  FINISHED;
1182       }
1183    }
1184    if (was_macro != mathcursor->InMacroMode()
1185        && action >= 0
1186        && action != LFUN_BACKSPACE)
1187            UpdateLocal(bv);
1188    if (sp && !space_on) sp = 0;
1189    if (mathcursor->Selection() || was_selection)
1190        ToggleInsetSelection(bv);
1191     
1192    if (result == DISPATCHED)
1193       ShowInsetCursor(bv);
1194    else
1195       bv->unlockInset(this);
1196     
1197    return result;
1198 }
1199
1200
1201 void
1202 MathFuncInset::draw(Painter & pain, int x, int y)
1203
1204         if (name && name[0] > ' ') {
1205                 LyXFont font = WhichFont(LM_TC_TEXTRM, size);
1206                 font.setLatex(LyXFont::ON);
1207                 x += (lyxfont::width('I', font) + 3) / 4;
1208                 pain.text(x, y, name, font);
1209         }
1210 }
1211
1212
1213 void MathFuncInset::Metrics() 
1214 {
1215         ln = (name) ? strlen(name): 0;
1216         LyXFont  font = WhichFont(LM_TC_TEXTRM, size);
1217         font.setLatex(LyXFont::ON);
1218         width = lyxfont::width(name, ln, font)
1219                 + lyxfont::width('I', font) / 2;
1220         mathed_string_height(LM_TC_TEXTRM, size,
1221                              reinterpret_cast<unsigned char const *>(name),
1222                              strlen(name), ascent, descent);
1223 }
1224
1225
1226 static
1227 void mathedValidate(LaTeXFeatures & features, MathParInset * par)
1228 {
1229     MathedIter it(par->GetData());
1230     
1231     while (it.OK() && !(features.binom && features.boldsymbol)) {
1232         if (it.IsInset()) {
1233             if(it.IsActive()) {
1234                 MathParInset * p = it.GetActiveInset();
1235                 if (!features.binom && p->GetType() == LM_OT_MACRO && 
1236                     strcmp(p->GetName(), "binom") == 0) {
1237                     features.binom = true;
1238                 } else {
1239                     for (int i = 0; i <= p->getMaxArgumentIdx(); ++i) {
1240                         p->setArgumentIdx(i);
1241                         mathedValidate(features, p);
1242                     }
1243                 }
1244             } else {
1245                 MathedInset* p = it.GetInset();
1246                 if (!features.boldsymbol && p->GetName() &&
1247                     strcmp(p->GetName(), "boldsymbol") == 0) {
1248                     features.boldsymbol = true;
1249                 }
1250             }       
1251         }
1252         it.Next();
1253     }
1254 }