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