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