]> git.lyx.org Git - features.git/blob - src/mathed/formula.C
make the new code from Juergen compile and some small fixes to the same code.
[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
716 InsetFormula::LocalDispatch(BufferView * bv,
717                             int action, string const & arg)
718 {
719 //   extern char *dispatch_result;
720     MathedTextCodes varcode = LM_TC_MIN;       
721     bool was_macro = mathcursor->InMacroMode();
722     bool sel = false;
723     bool space_on = false;
724     bool was_selection = mathcursor->Selection();
725     RESULT result = DISPATCHED;
726     static MathSpaceInset * sp= 0;
727
728    HideInsetCursor(bv);
729
730     if (mathcursor->getLastCode() == LM_TC_TEX) { 
731         varcode = LM_TC_TEX;
732     }
733    switch (action) {
734        
735     // --- Cursor Movements ---------------------------------------------
736     case LFUN_RIGHTSEL: sel = true;
737     case LFUN_RIGHT:
738       {
739          result = DISPATCH_RESULT(mathcursor->Right(sel));
740          break;
741       }
742     case LFUN_LEFTSEL: sel = true;     
743     case LFUN_LEFT:
744       {
745          result = DISPATCH_RESULT(mathcursor->Left(sel));
746          break;
747       }
748     case LFUN_UPSEL: sel = true;  
749     case LFUN_UP:
750       result = DISPATCH_RESULT(mathcursor->Up(sel));
751       break;
752        
753     case LFUN_DOWNSEL: sel = true;  
754     case LFUN_DOWN:
755       result = DISPATCH_RESULT(mathcursor->Down(sel));
756       break;
757     case LFUN_HOME:
758       mathcursor->Home();
759       break;
760     case LFUN_END:
761       mathcursor->End();
762       break;
763     case LFUN_DELETE_LINE_FORWARD:
764             //current_view->lockedInsetStoreUndo(Undo::INSERT);
765             bv->lockedInsetStoreUndo(Undo::DELETE);
766       mathcursor->DelLine();
767       UpdateLocal(bv);
768       break;
769     case LFUN_BREAKLINE:
770       bv->lockedInsetStoreUndo(Undo::INSERT);
771       mathcursor->Insert(' ', LM_TC_CR);
772       par = mathcursor->GetPar();
773       UpdateLocal(bv);
774       break;
775     case LFUN_TAB:
776       bv->lockedInsetStoreUndo(Undo::INSERT);
777       mathcursor->Insert(0, LM_TC_TAB);
778       //UpdateInset(this);
779       break;     
780     case LFUN_TABINSERT:
781       bv->lockedInsetStoreUndo(Undo::INSERT);
782       mathcursor->Insert('T', LM_TC_TAB);
783       UpdateLocal(bv);
784       break;     
785     case LFUN_BACKSPACE:
786        if (!mathcursor->Left()) 
787          break;
788        
789        if (!mathcursor->InMacroMode() && mathcursor->pullArg()) {       
790            bv->updateInset(this, true);
791            break;
792        }
793       
794     case LFUN_DELETE:
795             //current_view->lockedInsetStoreUndo(Undo::INSERT);
796             bv->lockedInsetStoreUndo(Undo::DELETE);
797       mathcursor->Delete();       
798       bv->updateInset(this, true);
799       break;    
800 //    case LFUN_GETXY:
801 //      sprintf(dispatch_buffer, "%d %d",);
802 //      dispatch_result = dispatch_buffer;
803 //      break;
804     case LFUN_SETXY:
805       {
806          int x, y, x1, y1;
807          sscanf(arg.c_str(), "%d %d", &x, &y);
808          par->GetXY(x1, y1);
809          mathcursor->SetPos(x1+x, y1+y);
810       }
811       break;
812
813       /* cursor selection ---------------------------- */
814
815     case LFUN_PASTE:
816             if (was_macro)
817                 mathcursor->MacroModeClose();
818             bv->lockedInsetStoreUndo(Undo::INSERT);
819             mathcursor->SelPaste(); UpdateLocal(bv); break;
820     case LFUN_CUT:
821             bv->lockedInsetStoreUndo(Undo::DELETE);
822             mathcursor->SelCut(); UpdateLocal(bv); break;
823     case LFUN_COPY: mathcursor->SelCopy(); break;      
824     case LFUN_HOMESEL:
825     case LFUN_ENDSEL:
826     case LFUN_WORDRIGHTSEL:
827     case LFUN_WORDLEFTSEL:
828       break;
829       
830     // --- accented characters ------------------------------
831
832     case LFUN_UMLAUT: mathcursor->setAccent(LM_ddot); break;
833     case LFUN_CIRCUMFLEX: mathcursor->setAccent(LM_hat); break;
834     case LFUN_GRAVE: mathcursor->setAccent(LM_grave); break;
835     case LFUN_ACUTE: mathcursor->setAccent(LM_acute); break;
836     case LFUN_TILDE: mathcursor->setAccent(LM_tilde); break;
837     case LFUN_MACRON: mathcursor->setAccent(LM_bar); break;
838     case LFUN_DOT: mathcursor->setAccent(LM_dot); break;
839     case LFUN_CARON: mathcursor->setAccent(LM_check); break;
840     case LFUN_BREVE: mathcursor->setAccent(LM_breve); break;
841     case LFUN_VECTOR: mathcursor->setAccent(LM_vec); break; 
842       
843     // Greek mode     
844     case LFUN_GREEK:
845     {
846        if (!greek_kb_flag) {
847           greek_kb_flag = 1;
848           bv->owner()->getMiniBuffer()->Set(_("Math greek mode on"));
849        } else
850          greek_kb_flag = 0;
851        break;
852     }  
853       
854     // Greek keyboard      
855     case LFUN_GREEK_TOGGLE:
856     {
857        greek_kb_flag = (greek_kb_flag) ? 0 : 2;
858        if (greek_kb_flag)
859          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard on"));
860        else
861          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard off"));
862        break;
863     }  
864    
865       //  Math fonts 
866     case LFUN_BOLD:     mathcursor->setLastCode(LM_TC_BF); break;
867     case LFUN_SANS:  mathcursor->setLastCode( LM_TC_SF); break;
868     case LFUN_EMPH:  mathcursor->setLastCode(LM_TC_CAL); break;
869     case LFUN_ROMAN: mathcursor->setLastCode(LM_TC_RM); break;
870     case LFUN_CODE: mathcursor->setLastCode(LM_TC_TT); break;   
871     case LFUN_DEFAULT:  mathcursor->setLastCode(LM_TC_VAR ) ; break;
872     case LFUN_TEX: 
873     {
874 //       varcode = LM_TC_TEX;
875         mathcursor->setLastCode(LM_TC_TEX);
876         bv->owner()->getMiniBuffer()->Set(_("TeX mode")); 
877        break;
878     }
879
880     case LFUN_MATH_NUMBER:
881     {
882       bv->lockedInsetStoreUndo(Undo::INSERT);
883        if (disp_flag) {
884           short type = par->GetType();
885           bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
886           if (oldf) {
887              --type;
888              if (!label.empty()) {
889                      label.clear();
890              }
891              bv->owner()->getMiniBuffer()->Set(_("No number"));  
892           } else {
893              ++type;
894              bv->owner()->getMiniBuffer()->Set(_("Number"));
895           }
896           par->SetType(type);
897           UpdateLocal(bv);
898        }
899        break;
900     }
901     
902     case LFUN_MATH_NONUMBER:
903     { 
904         if (par->GetType() == LM_OT_MPARN) {
905 //         MathMatrixInset *mt = (MathMatrixInset*)par;
906            //BUG 
907 //         mt->SetNumbered(!mt->IsNumbered());
908             
909             mathcursor->setNumbered();
910            UpdateLocal(bv);
911         }
912         break;
913     }
914        
915     case LFUN_MATH_LIMITS:
916     {
917       bv->lockedInsetStoreUndo(Undo::INSERT);
918        if (mathcursor->Limits())
919          UpdateLocal(bv);
920     }
921  
922     case LFUN_MATH_SIZE:
923        if (!arg.empty()) {
924            latexkeys * l = in_word_set (arg.c_str(), strlen(arg.c_str()));
925            int sz = (l) ? l->id: -1;
926            mathcursor->SetSize(sz);
927            UpdateLocal(bv);
928            break;
929        }
930        
931     case LFUN_INSERT_MATH:
932     {
933         bv->lockedInsetStoreUndo(Undo::INSERT);
934         InsertSymbol(bv, arg.c_str());
935         break;
936     }
937     
938     case LFUN_INSERT_MATRIX:
939     { 
940       bv->lockedInsetStoreUndo(Undo::INSERT);
941        int k, m, n;
942        char s[80], arg2[80];
943        // This is just so that too long args won't ooze out of s.
944        strncpy(arg2, arg.c_str(), 80); arg2[79]= '\0';
945        k = sscanf(arg2, "%d %d %s", &m, &n, s);
946        s[79] = '\0';
947         
948        if (k < 1) {
949            m = n = 1;
950        } else if (k == 1) {
951            n = 1;
952        }
953         
954        MathMatrixInset * p = new MathMatrixInset(m, n);      
955        if (mathcursor && p) {
956           if (k > 2 && int(strlen(s)) > m)
957             p->SetAlign(s[0], &s[1]);
958           mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
959           UpdateLocal(bv);
960        }
961        break;
962     }
963       
964     case LFUN_MATH_DELIM:
965     {  
966       bv->lockedInsetStoreUndo(Undo::INSERT);
967        char lf[40], rg[40], arg2[40];
968        int ilf = '(', irg = '.';
969        latexkeys * l;
970        string vdelim("(){}[]./|");
971         
972        if (arg.empty())
973                break;
974        strncpy(arg2, arg.c_str(), 40); arg2[39]= '\0';
975        int n = sscanf(arg2, "%s %s", lf, rg);
976        lf[39] = '\0'; rg[39] = '\0';
977
978        if (n > 0) {
979            if (isdigit(lf[0])) 
980              ilf = atoi(lf);
981            else 
982              if (lf[1]) {
983                  l = in_word_set(lf, strlen(lf));
984                  // Long words will cause l == 0; so check.
985                  if(l) ilf = l->id;
986              } else
987              if (vdelim.find(lf[0]) != string::npos)
988                ilf = lf[0];
989            
990            if (n > 1) {
991                if (isdigit(rg[0]))
992                  irg = atoi(rg);
993                else 
994                  if (rg[1]) {
995                      l = in_word_set(rg, strlen(rg));
996                      if(l) irg = l->id;
997                  } else
998                  if (vdelim.find(rg[0]) != string::npos)
999                    irg = rg[0];
1000            }
1001        }
1002        
1003        MathDelimInset * p = new MathDelimInset(ilf, irg);
1004        mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
1005        UpdateLocal(bv);
1006        break;
1007     }
1008
1009     case LFUN_PROTECTEDSPACE:
1010     {
1011       bv->lockedInsetStoreUndo(Undo::INSERT);
1012        sp = new MathSpaceInset(1); 
1013        mathcursor->Insert(sp);
1014        space_on = true;
1015        UpdateLocal(bv);
1016        break;
1017     }
1018       
1019     case LFUN_INSERT_LABEL:
1020     {
1021        bv->lockedInsetStoreUndo(Undo::INSERT);
1022        if (par->GetType() < LM_OT_PAR) break;
1023        string lb = arg;
1024        if (lb.empty()) {
1025           pair<bool, string>
1026                 result = askForText(_("Enter new label to insert:"));
1027           if (result.first) {
1028              lb = result.second;
1029           }
1030        }
1031        if (!lb.empty() && lb[0] > ' ') {
1032           SetNumber(true);
1033           if (par->GetType() == LM_OT_MPARN) {
1034               mathcursor->setLabel(lb.c_str());
1035 //            MathMatrixInset *mt = (MathMatrixInset*)par;
1036 //            mt->SetLabel(lb);
1037           } else {
1038                   //if (label.notEmpty()) delete label;
1039               label = lb;
1040           }
1041           UpdateLocal(bv);
1042        } else
1043                label.clear();
1044        break;
1045     }
1046     
1047     case LFUN_MATH_DISPLAY:
1048             //current_view->lockedInsetStoreUndo(Undo::INSERT);
1049             bv->lockedInsetStoreUndo(Undo::EDIT);
1050       display(!disp_flag);
1051       UpdateLocal(bv);
1052       break;
1053       
1054     // Invalid actions under math mode
1055     case LFUN_MATH_MODE:  
1056     {
1057         if (mathcursor->getLastCode()!= LM_TC_TEXTRM) {
1058             bv->owner()->getMiniBuffer()->Set(_("math text mode"));
1059             varcode = LM_TC_TEXTRM;
1060         } else {
1061             varcode = LM_TC_VAR;
1062         }
1063         mathcursor->setLastCode(varcode);
1064         break; 
1065     }
1066     case LFUN_UNDO:
1067       bv->owner()->getMiniBuffer()->Set(_("Invalid action in math mode!"));
1068       break;
1069
1070     //------- dummy actions
1071     case LFUN_EXEC_COMMAND:
1072        bv->owner()->getMiniBuffer()->ExecCommand(); 
1073        break;
1074        
1075     default:
1076       if ((action == -1  || action == LFUN_SELFINSERT) && !arg.empty())  {
1077          unsigned char c = arg[0];
1078          bv->lockedInsetStoreUndo(Undo::INSERT);
1079          
1080          if (c == ' ' && mathcursor->getAccent() == LM_hat) {
1081              c = '^';
1082              mathcursor->setAccent(0);
1083          }
1084          if (c == 0) {      // Dead key, do nothing 
1085              //lyxerr << "deadkey" << endl;
1086              break;
1087          } 
1088          if (isalpha(c)) {
1089              if (mathcursor->getLastCode() == LM_TC_TEX) { 
1090                mathcursor->MacroModeOpen();
1091                mathcursor->clearLastCode();
1092                varcode = LM_TC_MIN;
1093             } else          
1094             if (!varcode) {             
1095                 short f = (mathcursor->getLastCode()) ? 
1096                           mathcursor->getLastCode() :
1097                           static_cast<MathedTextCodes>(mathcursor->GetFCode());
1098                 varcode = MathIsAlphaFont(f) ?
1099                         static_cast<MathedTextCodes>(f) :
1100                         LM_TC_VAR;
1101             }
1102
1103 //           lyxerr << "Varcode << vardoce;
1104             mathcursor->Insert(c, (greek_kb_flag) ? LM_TC_SYMB: varcode);
1105             varcode = LM_TC_MIN;
1106             if (greek_kb_flag<2) greek_kb_flag = 0;
1107          } else 
1108            if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
1109                mathcursor->Insert(c, LM_TC_TEX);
1110                if (c == '{') {
1111                    mathcursor->Insert('}', LM_TC_TEX);
1112                    mathcursor->Left();
1113                }
1114                mathcursor->clearLastCode();
1115 //             varcode = LM_TC_MIN;
1116            } else
1117            if (c == '_' && varcode == LM_TC_TEX) {
1118                mathcursor->Insert(c, LM_TC_SPECIAL);
1119                mathcursor->clearLastCode();
1120 //             varcode = LM_TC_MIN;
1121            } else
1122             if (('0'<= c && c<= '9') && (varcode == LM_TC_TEX||was_macro)) {
1123                 mathcursor->MacroModeOpen();
1124                 mathcursor->clearLastCode();
1125                 mathcursor->Insert(c, LM_TC_MIN);
1126             }
1127          else
1128            if (('0'<= c && c<= '9') || strchr(";:!|[]().,?", c)) 
1129               mathcursor->Insert(c, LM_TC_CONST);
1130          else
1131            if (strchr("+/-*<>=", c))
1132               mathcursor->Insert(c, LM_TC_BOP);
1133          else
1134            if (strchr(latex_special_chars, c) && c!= '_')
1135               mathcursor->Insert(c, LM_TC_SPECIAL);
1136          else
1137            if (c == '_' || c == '^') {
1138                char s[2];
1139                s[0] = c;
1140                s[1] = 0;
1141               mathcursor->Interpret (s);
1142            } else
1143            if (c == ' ') {          
1144                if (!varcode) {  
1145                    short f = (mathcursor->getLastCode()) ? 
1146                               mathcursor->getLastCode() :
1147                               static_cast<MathedTextCodes>(mathcursor->GetFCode());
1148                    varcode = MathIsAlphaFont(f) ?
1149                            static_cast<MathedTextCodes>(f) :
1150                            LM_TC_VAR;
1151                }
1152               if (varcode == LM_TC_TEXTRM) {
1153                   mathcursor->Insert(c, LM_TC_TEXTRM);
1154               } else
1155               if (was_macro)
1156                 mathcursor->MacroModeClose();
1157               else 
1158               if (sp) {
1159                  int isp = (sp->GetSpace()<5) ? sp->GetSpace()+1: 0;
1160                  sp->SetSpace(isp);
1161                  space_on = true;
1162               } else {
1163                   if (!mathcursor->Pop() && mathcursor->IsEnd()) 
1164                     result = FINISHED;
1165               }
1166            } else
1167            if (c == '\'') {
1168               mathcursor->Insert (c, LM_TC_VAR);
1169            } else
1170            if (c == '\\') {
1171               if (was_macro)
1172                 mathcursor->MacroModeClose();
1173               bv->owner()->getMiniBuffer()->Set(_("TeX mode")); 
1174                mathcursor->setLastCode(LM_TC_TEX);
1175            } 
1176          UpdateLocal(bv);
1177       } else {
1178         // lyxerr << "Closed by action " << action << endl;
1179         result =  FINISHED;
1180       }
1181    }
1182    if (was_macro != mathcursor->InMacroMode()
1183        && action >= 0
1184        && action != LFUN_BACKSPACE)
1185            UpdateLocal(bv);
1186    if (sp && !space_on) sp = 0;
1187    if (mathcursor->Selection() || was_selection)
1188        ToggleInsetSelection(bv);
1189     
1190    if (result == DISPATCHED)
1191       ShowInsetCursor(bv);
1192    else
1193       bv->unlockInset(this);
1194     
1195    return result;
1196 }
1197
1198
1199 void
1200 MathFuncInset::draw(Painter & pain, int x, int y)
1201
1202         if (name && name[0] > ' ') {
1203                 LyXFont font = WhichFont(LM_TC_TEXTRM, size);
1204                 font.setLatex(LyXFont::ON);
1205                 x += (font.textWidth("I", 1) + 3) / 4;
1206                 pain.text(x, y, name, font);
1207         }
1208 }
1209
1210
1211 void MathFuncInset::Metrics() 
1212 {
1213         ln = (name) ? strlen(name): 0;
1214         LyXFont  font = WhichFont(LM_TC_TEXTRM, size);
1215         font.setLatex(LyXFont::ON);
1216         width = font.textWidth(name, ln) + font.textWidth("I", 1)/2;
1217         mathed_string_height(LM_TC_TEXTRM, size,
1218                              reinterpret_cast<unsigned char const *>(name),
1219                              strlen(name), ascent, descent);
1220 }
1221
1222
1223 static
1224 void mathedValidate(LaTeXFeatures & features, MathParInset * par)
1225 {
1226     MathedIter it(par->GetData());
1227     
1228     while (it.OK() && !(features.binom && features.boldsymbol)) {
1229         if (it.IsInset()) {
1230             if(it.IsActive()) {
1231                 MathParInset * p = it.GetActiveInset();
1232                 if (!features.binom && p->GetType() == LM_OT_MACRO && 
1233                     strcmp(p->GetName(), "binom") == 0) {
1234                     features.binom = true;
1235                 } else {
1236                     for (int i = 0; i <= p->getMaxArgumentIdx(); ++i) {
1237                         p->setArgumentIdx(i);
1238                         mathedValidate(features, p);
1239                     }
1240                 }
1241             } else {
1242                 MathedInset* p = it.GetInset();
1243                 if (!features.boldsymbol && p->GetName() &&
1244                     strcmp(p->GetName(), "boldsymbol") == 0) {
1245                     features.boldsymbol = true;
1246                 }
1247             }       
1248         }
1249         it.Next();
1250     }
1251 }