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