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